Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderAdapter.ts

554 lines18.9 KB

1import {
2 ChatAttachment,
3 CheckpointId,
4 MessageId,
5 ModelSelection,
6 NodeId,
7 OrchestrationV2AppThread,
8 OrchestrationV2ConversationMessage,
9 OrchestrationV2ExecutionNode,
10 OrchestrationV2ProviderSession,
11 OrchestrationV2PlanArtifact,
12 OrchestrationV2ProviderCapabilities,
13 OrchestrationV2ProviderFailure,
14 OrchestrationV2ProviderRetry,
15 OrchestrationV2ProviderThread,
16 OrchestrationV2ProviderTurn,
17 OrchestrationV2RuntimeRequest,
18 OrchestrationV2Subagent,
19 OrchestrationV2TurnItem,
20 ProviderApprovalDecision,
21 ProviderInteractionMode,
22 ProviderDriverKind,
23 ProviderInstanceId,
24 PositiveInt,
25 ProviderUserInputAnswers,
26 ProviderSessionId,
27 ProviderThreadId,
28 ProviderTurnId,
29 RuntimeMode,
30 RuntimeRequestId,
31 RunAttemptId,
32 RunId,
33 ThreadId,
34} from "@t3tools/contracts";
35import * as Context from "effect/Context";
36import * as Schema from "effect/Schema";
37import type * as Effect from "effect/Effect";
38import type * as Scope from "effect/Scope";
39import type * as Stream from "effect/Stream";
40​
41import type {
42 ProviderSelectionTransitionInput,
43 ProviderSelectionTransitionPlan,
44} from "./ProviderSelectionTransition.ts";
45​
46export const ProviderAdapterV2RuntimePolicy = Schema.Struct({
47 runtimeMode: RuntimeMode,
48 interactionMode: ProviderInteractionMode,
49 cwd: Schema.NullOr(Schema.String),
50 approvalPolicy: Schema.optional(Schema.Unknown),
51 sandboxPolicy: Schema.optional(Schema.Unknown),
52 reasoningEffort: Schema.optional(Schema.String),
53});
54export type ProviderAdapterV2RuntimePolicy = typeof ProviderAdapterV2RuntimePolicy.Type;
55​
56export const ProviderAdapterV2TurnMessage = Schema.Struct({
57 messageId: MessageId,
58 text: Schema.String,
59 attachments: Schema.Array(ChatAttachment),
60 createdBy: OrchestrationV2ConversationMessage.fields.createdBy,
61 creationSource: OrchestrationV2ConversationMessage.fields.creationSource,
62});
63export type ProviderAdapterV2TurnMessage = typeof ProviderAdapterV2TurnMessage.Type;
64​
65export const ProviderAdapterV2SessionStatus = Schema.Literals([
66 "starting",
67 "ready",
68 "running",
69 "waiting",
70 "stopped",
71 "error",
72]);
73export type ProviderAdapterV2SessionStatus = typeof ProviderAdapterV2SessionStatus.Type;
74​
75export const ProviderAdapterV2Event = Schema.Union([
76 Schema.Struct({
77 type: Schema.Literal("app_thread.created"),
78 driver: ProviderDriverKind,
79 appThread: OrchestrationV2AppThread,
80 }),
81 Schema.Struct({
82 type: Schema.Literal("provider_session.updated"),
83 driver: ProviderDriverKind,
84 providerSession: OrchestrationV2ProviderSession,
85 }),
86 Schema.Struct({
87 type: Schema.Literal("provider_thread.updated"),
88 driver: ProviderDriverKind,
89 providerThread: OrchestrationV2ProviderThread,
90 }),
91 Schema.Struct({
92 type: Schema.Literal("provider_turn.updated"),
93 driver: ProviderDriverKind,
94 threadId: Schema.optional(ThreadId),
95 providerTurn: OrchestrationV2ProviderTurn,
96 }),
97 Schema.Struct({
98 type: Schema.Literal("node.updated"),
99 driver: ProviderDriverKind,
100 node: OrchestrationV2ExecutionNode,
101 }),
102 Schema.Struct({
103 type: Schema.Literal("subagent.updated"),
104 driver: ProviderDriverKind,
105 subagent: OrchestrationV2Subagent,
106 }),
107 Schema.Struct({
108 type: Schema.Literal("message.updated"),
109 driver: ProviderDriverKind,
110 message: OrchestrationV2ConversationMessage,
111 }),
112 Schema.Struct({
113 type: Schema.Literal("turn_item.updated"),
114 driver: ProviderDriverKind,
115 turnItem: OrchestrationV2TurnItem,
116 }),
117 Schema.Struct({
118 type: Schema.Literal("runtime_request.updated"),
119 driver: ProviderDriverKind,
120 threadId: Schema.optional(ThreadId),
121 runtimeRequest: OrchestrationV2RuntimeRequest,
122 }),
123 Schema.Struct({
124 type: Schema.Literal("plan.updated"),
125 driver: ProviderDriverKind,
126 plan: OrchestrationV2PlanArtifact,
127 }),
128 Schema.Struct({
129 type: Schema.Literal("turn.terminal"),
130 driver: ProviderDriverKind,
131 providerThreadId: ProviderThreadId,
132 providerTurnId: ProviderTurnId,
133 runOrdinal: PositiveInt,
134 status: Schema.Literals(["completed", "interrupted", "cancelled"]),
135 failure: Schema.Null,
136 threadDisposition: Schema.Literals(["reusable", "broken"]),
137 }),
138 Schema.Struct({
139 type: Schema.Literal("turn.terminal"),
140 driver: ProviderDriverKind,
141 providerThreadId: ProviderThreadId,
142 providerTurnId: ProviderTurnId,
143 runOrdinal: PositiveInt,
144 failureItemOrdinal: PositiveInt,
145 status: Schema.Literal("failed"),
146 failure: OrchestrationV2ProviderFailure,
147 retry: Schema.optional(OrchestrationV2ProviderRetry),
148 retryStartedAt: Schema.optional(Schema.DateTimeUtc),
149 threadDisposition: Schema.Literals(["reusable", "broken"]),
150 }),
151]);
152export type ProviderAdapterV2Event = typeof ProviderAdapterV2Event.Type;
153​
154export class ProviderAdapterCapabilitiesError extends Schema.TaggedErrorClass<ProviderAdapterCapabilitiesError>()(
155 "ProviderAdapterCapabilitiesError",
156 {
157 driver: ProviderDriverKind,
158 cause: Schema.optional(Schema.Defect()),
159 },
160) {
161 override get message(): string {
162 return `Failed to read ${this.driver} provider capabilities.`;
163 }
165​
166export class ProviderAdapterOpenSessionError extends Schema.TaggedErrorClass<ProviderAdapterOpenSessionError>()(
167 "ProviderAdapterOpenSessionError",
168 {
169 driver: ProviderDriverKind,
170 providerSessionId: ProviderSessionId,
171 cause: Schema.optional(Schema.Defect()),
172 },
173) {
174 override get message(): string {
175 return `Failed to open ${this.driver} provider session ${this.providerSessionId}.`;
176 }
178​
179export class ProviderAdapterCloseSessionError extends Schema.TaggedErrorClass<ProviderAdapterCloseSessionError>()(
180 "ProviderAdapterCloseSessionError",
181 {
182 driver: ProviderDriverKind,
183 providerSessionId: ProviderSessionId,
184 cause: Schema.optional(Schema.Defect()),
185 },
186) {
187 override get message(): string {
188 return `Failed to close ${this.driver} provider session ${this.providerSessionId}.`;
189 }
191​
192export class ProviderAdapterResumeThreadError extends Schema.TaggedErrorClass<ProviderAdapterResumeThreadError>()(
193 "ProviderAdapterResumeThreadError",
194 {
195 driver: ProviderDriverKind,
196 providerSessionId: ProviderSessionId,
197 providerThreadId: ProviderThreadId,
198 cause: Schema.optional(Schema.Defect()),
199 },
200) {
201 override get message(): string {
202 return `Failed to resume ${this.driver} provider thread ${this.providerThreadId}.`;
203 }
205​
206export class ProviderAdapterEnsureThreadError extends Schema.TaggedErrorClass<ProviderAdapterEnsureThreadError>()(
207 "ProviderAdapterEnsureThreadError",
208 {
209 driver: ProviderDriverKind,
210 threadId: ThreadId,
211 cause: Schema.optional(Schema.Defect()),
212 },
213) {
214 override get message(): string {
215 return `Failed to ensure ${this.driver} provider thread for app thread ${this.threadId}.`;
216 }
218​
219export class ProviderAdapterReadThreadSnapshotError extends Schema.TaggedErrorClass<ProviderAdapterReadThreadSnapshotError>()(
220 "ProviderAdapterReadThreadSnapshotError",
221 {
222 driver: ProviderDriverKind,
223 providerThreadId: ProviderThreadId,
224 cause: Schema.optional(Schema.Defect()),
225 },
226) {
227 override get message(): string {
228 return `Failed to read ${this.driver} provider thread snapshot ${this.providerThreadId}.`;
229 }
231​
232export class ProviderAdapterRollbackThreadError extends Schema.TaggedErrorClass<ProviderAdapterRollbackThreadError>()(
233 "ProviderAdapterRollbackThreadError",
234 {
235 driver: ProviderDriverKind,
236 providerThreadId: ProviderThreadId,
237 checkpointId: Schema.optional(CheckpointId),
238 cause: Schema.optional(Schema.Defect()),
239 },
240) {
241 override get message(): string {
242 return `Failed to roll back ${this.driver} provider thread ${this.providerThreadId}.`;
243 }
245​
246export class ProviderAdapterForkThreadError extends Schema.TaggedErrorClass<ProviderAdapterForkThreadError>()(
247 "ProviderAdapterForkThreadError",
248 {
249 driver: ProviderDriverKind,
250 providerThreadId: ProviderThreadId,
251 cause: Schema.optional(Schema.Defect()),
252 },
253) {
254 override get message(): string {
255 return `Failed to fork ${this.driver} provider thread ${this.providerThreadId}.`;
256 }
258​
259export class ProviderAdapterTurnStartError extends Schema.TaggedErrorClass<ProviderAdapterTurnStartError>()(
260 "ProviderAdapterTurnStartError",
261 {
262 driver: ProviderDriverKind,
263 threadId: ThreadId,
264 providerThreadId: ProviderThreadId,
265 runId: RunId,
266 cause: Schema.optional(Schema.Defect()),
267 },
268) {
269 override get message(): string {
270 return `Failed to start run ${this.runId} on ${this.driver} provider thread ${this.providerThreadId}.`;
271 }
273​
274export class ProviderAdapterSteerRunUnsupportedError extends Schema.TaggedErrorClass<ProviderAdapterSteerRunUnsupportedError>()(
275 "ProviderAdapterSteerRunUnsupportedError",
276 {
277 driver: ProviderDriverKind,
278 providerThreadId: ProviderThreadId,
279 },
280) {
281 override get message(): string {
282 return `${this.driver} provider thread ${this.providerThreadId} does not support active-run steering.`;
283 }
285​
286export class ProviderAdapterSteerRunError extends Schema.TaggedErrorClass<ProviderAdapterSteerRunError>()(
287 "ProviderAdapterSteerRunError",
288 {
289 driver: ProviderDriverKind,
290 providerThreadId: ProviderThreadId,
291 providerTurnId: ProviderTurnId,
292 cause: Schema.optional(Schema.Defect()),
293 },
294) {
295 override get message(): string {
296 return `Failed to steer active run ${this.providerTurnId} on ${this.driver} provider thread ${this.providerThreadId}.`;
297 }
299​
300export class ProviderAdapterInterruptError extends Schema.TaggedErrorClass<ProviderAdapterInterruptError>()(
301 "ProviderAdapterInterruptError",
302 {
303 driver: ProviderDriverKind,
304 providerThreadId: ProviderThreadId,
305 providerTurnId: ProviderTurnId,
306 cause: Schema.optional(Schema.Defect()),
307 },
308) {
309 override get message(): string {
310 return `Failed to interrupt ${this.driver} provider turn ${this.providerTurnId}.`;
311 }
313​
314export class ProviderAdapterRuntimeRequestResponseError extends Schema.TaggedErrorClass<ProviderAdapterRuntimeRequestResponseError>()(
315 "ProviderAdapterRuntimeRequestResponseError",
316 {
317 driver: ProviderDriverKind,
318 requestId: RuntimeRequestId,
319 cause: Schema.optional(Schema.Defect()),
320 },
321) {
322 override get message(): string {
323 return `Failed to respond to ${this.driver} runtime request ${this.requestId}.`;
324 }
326​
327export class ProviderAdapterEventStreamError extends Schema.TaggedErrorClass<ProviderAdapterEventStreamError>()(
328 "ProviderAdapterEventStreamError",
329 {
330 driver: ProviderDriverKind,
331 providerSessionId: ProviderSessionId,
332 cause: Schema.optional(Schema.Defect()),
333 },
334) {
335 override get message(): string {
336 return `Failed while streaming ${this.driver} provider session ${this.providerSessionId} events.`;
337 }
339​
340export class ProviderAdapterProtocolError extends Schema.TaggedErrorClass<ProviderAdapterProtocolError>()(
341 "ProviderAdapterProtocolError",
342 {
343 driver: ProviderDriverKind,
344 detail: Schema.String,
345 payload: Schema.optional(Schema.Unknown),
346 },
347) {
348 override get message(): string {
349 return `${this.driver} provider protocol error: ${this.detail}.`;
350 }
352​
353export const ProviderAdapterV2Error = Schema.Union([
354 ProviderAdapterCapabilitiesError,
355 ProviderAdapterOpenSessionError,
356 ProviderAdapterCloseSessionError,
357 ProviderAdapterResumeThreadError,
358 ProviderAdapterEnsureThreadError,
359 ProviderAdapterReadThreadSnapshotError,
360 ProviderAdapterRollbackThreadError,
361 ProviderAdapterForkThreadError,
362 ProviderAdapterTurnStartError,
363 ProviderAdapterSteerRunUnsupportedError,
364 ProviderAdapterSteerRunError,
365 ProviderAdapterInterruptError,
366 ProviderAdapterRuntimeRequestResponseError,
367 ProviderAdapterEventStreamError,
368 ProviderAdapterProtocolError,
369]);
370export type ProviderAdapterV2Error = typeof ProviderAdapterV2Error.Type;
371​
372export interface ProviderAdapterV2OpenSessionInput {
373 readonly threadId: ThreadId;
374 readonly providerSessionId: ProviderSessionId;
375 readonly modelSelection: ModelSelection;
376 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
377 readonly resumeFromSession?: OrchestrationV2ProviderSession;
379​
380export interface ProviderAdapterV2EnsureThreadInput {
381 readonly threadId: ThreadId;
382 readonly modelSelection: ModelSelection;
383 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
384 readonly providerSessionId?: ProviderSessionId;
385 readonly existingProviderThread?: OrchestrationV2ProviderThread;
387​
388export interface ProviderAdapterV2TurnInput {
389 readonly appThread: OrchestrationV2AppThread;
390 readonly threadId: ThreadId;
391 readonly runId: RunId;
392 readonly runOrdinal: number;
393 readonly providerTurnOrdinal: number;
394 readonly attemptId: RunAttemptId;
395 readonly rootNodeId: NodeId;
396 readonly providerThread: OrchestrationV2ProviderThread;
397 readonly message: ProviderAdapterV2TurnMessage;
398 readonly modelSelection: ModelSelection;
399 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
401​
402export interface ProviderAdapterV2SteerInput {
403 readonly threadId: ThreadId;
404 readonly runId: RunId;
405 readonly providerThread: OrchestrationV2ProviderThread;
406 readonly providerTurnId: ProviderTurnId;
407 readonly message: ProviderAdapterV2TurnMessage;
409​
410export interface ProviderAdapterV2InterruptInput {
411 readonly providerThread: OrchestrationV2ProviderThread;
412 readonly providerTurnId: ProviderTurnId;
413 /** When true, the next `startTurn` may respawn the provider runtime (Grok Stop recovery). */
414 readonly requestRuntimeRestart?: boolean;
416​
417export interface ProviderAdapterV2RuntimeRequestResponseInput {
418 readonly requestId: RuntimeRequestId;
419 readonly decision?: ProviderApprovalDecision;
420 readonly answers?: ProviderUserInputAnswers;
421 readonly response?: unknown;
423​
424export interface ProviderAdapterV2ThreadSnapshot {
425 readonly providerThread: OrchestrationV2ProviderThread;
426 readonly providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
427 readonly messages: ReadonlyArray<OrchestrationV2ConversationMessage>;
428 readonly runtimeRequests: ReadonlyArray<OrchestrationV2RuntimeRequest>;
429 readonly providerPayload?: unknown;
431​
432export interface ProviderAdapterV2ReadThreadSnapshotInput {
433 readonly providerThread: OrchestrationV2ProviderThread;
435​
436export type ProviderAdapterV2RollbackTarget =
437 | {
438 readonly type: "thread_start";
439 readonly checkpointId: CheckpointId;
440 readonly appRunOrdinal: 0;
441 }
442 | {
443 readonly type: "provider_turn";
444 readonly checkpointId: CheckpointId;
445 readonly appRunOrdinal: number;
446 readonly providerTurn: OrchestrationV2ProviderTurn;
447 };
448​
449export interface ProviderAdapterV2RollbackThreadInput {
450 readonly providerThread: OrchestrationV2ProviderThread;
451 readonly target: ProviderAdapterV2RollbackTarget;
452 readonly providerThreadTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
454​
455export interface ProviderAdapterV2ForkThreadInput {
456 readonly sourceProviderThread: OrchestrationV2ProviderThread;
457 readonly sourceProviderTurns?: ReadonlyArray<OrchestrationV2ProviderTurn>;
458 readonly providerTurnId?: ProviderTurnId;
459 readonly targetThreadId: ThreadId;
460 readonly ownerNodeId?: NodeId;
461 readonly modelSelection?: ModelSelection;
462 readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy;
464​
465export interface ProviderAdapterV2EventSubscription {
466 readonly events: Stream.Stream<ProviderAdapterV2Event, ProviderAdapterV2Error>;
467 readonly close: Effect.Effect<void>;
469​
470export interface ProviderAdapterV2SessionRuntime {
471 readonly instanceId: ProviderInstanceId;
472 readonly driver: ProviderDriverKind;
473 readonly providerSessionId: ProviderSessionId;
474 readonly providerSession: OrchestrationV2ProviderSession;
475 readonly events: Stream.Stream<ProviderAdapterV2Event, ProviderAdapterV2Error>;
476 /**
477 * Manager-owned runtimes expose a synchronous subscription so concurrent
478 * provider threads receive independent copies of the process event stream.
479 * Adapter runtimes may omit this and expose only their single-consumer event stream.
480 */
481 readonly subscribeEvents?: Effect.Effect<ProviderAdapterV2EventSubscription>;
482 /**
483 * Adapters whose native runtime can hold pending work outside an active
484 * turn (for example Claude background tasks and their wake turns) report it
485 * here so the session manager defers idle release while it is pending.
486 */
487 readonly hasPendingBackgroundWork?: Effect.Effect<boolean>;
488 /**
489 * Per-provider-thread pending work for root-run ingestion stop gates. When
490 * present, RunExecutionService uses only this probe (never the session-wide
491 * hasPendingBackgroundWork) so sibling native threads cannot pin an
492 * unrelated root subscription open.
493 */
494 readonly hasPendingBackgroundWorkForThread?: (
495 providerThread: OrchestrationV2ProviderThread,
496 ) => Effect.Effect<boolean>;
497 readonly ensureThread: (
498 input: ProviderAdapterV2EnsureThreadInput,
499 ) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
500 readonly resumeThread: (input: {
501 readonly providerThread: OrchestrationV2ProviderThread;
502 readonly threadId?: ThreadId;
503 readonly modelSelection?: ModelSelection;
504 readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy;
505 }) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
506 readonly startTurn: (
507 input: ProviderAdapterV2TurnInput,
508 ) => Effect.Effect<void, ProviderAdapterV2Error>;
509 readonly steerTurn: (
510 input: ProviderAdapterV2SteerInput,
511 ) => Effect.Effect<void, ProviderAdapterV2Error>;
512 readonly interruptTurn: (
513 input: ProviderAdapterV2InterruptInput,
514 ) => Effect.Effect<void, ProviderAdapterV2Error>;
515 readonly respondToRuntimeRequest: (
516 input: ProviderAdapterV2RuntimeRequestResponseInput,
517 ) => Effect.Effect<void, ProviderAdapterV2Error>;
518 readonly readThreadSnapshot: (
519 input: ProviderAdapterV2ReadThreadSnapshotInput,
520 ) => Effect.Effect<ProviderAdapterV2ThreadSnapshot, ProviderAdapterV2Error>;
521 /**
522 * Providers that accept product feedback for a thread (#7949, Codex → OpenAI)
523 * expose it here; absent means the driver has no feedback channel.
524 */
525 readonly uploadFeedback?: (input: {
526 readonly providerThread: OrchestrationV2ProviderThread;
527 readonly reason?: string;
528 }) => Effect.Effect<{ readonly feedbackId: string }, ProviderAdapterV2Error>;
529 readonly rollbackThread: (
530 input: ProviderAdapterV2RollbackThreadInput,
531 ) => Effect.Effect<ProviderAdapterV2ThreadSnapshot, ProviderAdapterV2Error>;
532 readonly forkThread: (
533 input: ProviderAdapterV2ForkThreadInput,
534 ) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
536​
537export interface ProviderAdapterV2Shape {
538 readonly instanceId: ProviderInstanceId;
539 readonly driver: ProviderDriverKind;
540 readonly getCapabilities: () => Effect.Effect<
541 OrchestrationV2ProviderCapabilities,
542 ProviderAdapterV2Error
543 >;
544 readonly planSelectionTransition: (
545 input: ProviderSelectionTransitionInput,
546 ) => Effect.Effect<ProviderSelectionTransitionPlan, ProviderAdapterV2Error>;
547 readonly openSession: (
548 input: ProviderAdapterV2OpenSessionInput,
549 ) => Effect.Effect<ProviderAdapterV2SessionRuntime, ProviderAdapterV2Error, Scope.Scope>;
551​
552export class ProviderAdapterV2 extends Context.Service<ProviderAdapterV2, ProviderAdapterV2Shape>()(
553 "t3/orchestration-v2/ProviderAdapter/ProviderAdapterV2",
554) {}