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

ProviderAdapter.ts

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