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

ProviderAdapter.ts

558 lines19.0 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 restartContinuationOfRunId?: RunId;
395 readonly attemptId: RunAttemptId;
396 readonly rootNodeId: NodeId;
397 readonly providerThread: OrchestrationV2ProviderThread;
398 readonly message: ProviderAdapterV2TurnMessage;
399 readonly modelSelection: ModelSelection;
400 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
402​
403export interface ProviderAdapterV2SteerInput {
404 readonly threadId: ThreadId;
405 readonly runId: RunId;
406 readonly providerThread: OrchestrationV2ProviderThread;
407 readonly providerTurnId: ProviderTurnId;
408 readonly message: ProviderAdapterV2TurnMessage;
410​
411export interface ProviderAdapterV2InterruptInput {
412 readonly providerThread: OrchestrationV2ProviderThread;
413 readonly providerTurnId: ProviderTurnId;
414 /** When true, the next `startTurn` may respawn the provider runtime (Grok Stop recovery). */
415 readonly requestRuntimeRestart?: boolean;
417​
418export interface ProviderAdapterV2RuntimeRequestResponseInput {
419 readonly requestId: RuntimeRequestId;
420 readonly decision?: ProviderApprovalDecision;
421 readonly answers?: ProviderUserInputAnswers;
422 readonly response?: unknown;
424​
425export interface ProviderAdapterV2ThreadSnapshot {
426 readonly providerThread: OrchestrationV2ProviderThread;
427 readonly providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
428 readonly messages: ReadonlyArray<OrchestrationV2ConversationMessage>;
429 readonly runtimeRequests: ReadonlyArray<OrchestrationV2RuntimeRequest>;
430 readonly providerPayload?: unknown;
432​
433export interface ProviderAdapterV2ReadThreadSnapshotInput {
434 readonly providerThread: OrchestrationV2ProviderThread;
436​
437export type ProviderAdapterV2RollbackTarget =
438 | {
439 readonly type: "thread_start";
440 readonly checkpointId: CheckpointId;
441 readonly appRunOrdinal: 0;
442 }
443 | {
444 readonly type: "provider_turn";
445 readonly checkpointId: CheckpointId;
446 readonly appRunOrdinal: number;
447 readonly providerTurn: OrchestrationV2ProviderTurn;
448 };
449​
450export interface ProviderAdapterV2RollbackThreadInput {
451 readonly providerThread: OrchestrationV2ProviderThread;
452 readonly target: ProviderAdapterV2RollbackTarget;
453 readonly providerThreadTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
455​
456export interface ProviderAdapterV2ForkThreadInput {
457 readonly sourceProviderThread: OrchestrationV2ProviderThread;
458 readonly sourceProviderTurns?: ReadonlyArray<OrchestrationV2ProviderTurn>;
459 readonly providerTurnId?: ProviderTurnId;
460 readonly targetThreadId: ThreadId;
461 readonly ownerNodeId?: NodeId;
462 readonly modelSelection?: ModelSelection;
463 readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy;
465​
466export interface ProviderAdapterV2EventSubscription {
467 readonly events: Stream.Stream<ProviderAdapterV2Event, ProviderAdapterV2Error>;
468 readonly close: Effect.Effect<void>;
470​
471export interface ProviderAdapterV2SessionRuntime {
472 readonly instanceId: ProviderInstanceId;
473 readonly driver: ProviderDriverKind;
474 readonly providerSessionId: ProviderSessionId;
475 readonly providerSession: OrchestrationV2ProviderSession;
476 readonly events: Stream.Stream<ProviderAdapterV2Event, ProviderAdapterV2Error>;
477 /**
478 * Manager-owned runtimes expose a synchronous subscription so concurrent
479 * provider threads receive independent copies of the process event stream.
480 * Adapter runtimes may omit this and expose only their single-consumer event stream.
481 */
482 readonly subscribeEvents?: Effect.Effect<ProviderAdapterV2EventSubscription>;
483 /**
484 * Adapters whose native runtime can hold pending work outside an active
485 * turn (for example Claude background tasks and their wake turns) report it
486 * here so the session manager defers idle release while it is pending.
487 */
488 readonly hasPendingBackgroundWork?: Effect.Effect<boolean>;
489 /**
490 * Per-provider-thread pending work for root-run ingestion stop gates. When
491 * present, RunExecutionService uses only this probe (never the session-wide
492 * hasPendingBackgroundWork) so sibling native threads cannot pin an
493 * unrelated root subscription open.
494 */
495 readonly hasPendingBackgroundWorkForThread?: (
496 providerThread: OrchestrationV2ProviderThread,
497 ) => Effect.Effect<boolean>;
498 readonly ensureThread: (
499 input: ProviderAdapterV2EnsureThreadInput,
500 ) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
501 readonly resumeThread: (input: {
502 readonly providerThread: OrchestrationV2ProviderThread;
503 readonly threadId?: ThreadId;
504 readonly modelSelection?: ModelSelection;
505 readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy;
506 }) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
507 readonly startTurn: (
508 input: ProviderAdapterV2TurnInput,
509 ) => Effect.Effect<void, ProviderAdapterV2Error>;
510 readonly compactThread?: (
511 input: ProviderAdapterV2TurnInput,
512 ) => Effect.Effect<void, ProviderAdapterV2Error>;
513 readonly steerTurn: (
514 input: ProviderAdapterV2SteerInput,
515 ) => Effect.Effect<void, ProviderAdapterV2Error>;
516 readonly interruptTurn: (
517 input: ProviderAdapterV2InterruptInput,
518 ) => Effect.Effect<void, ProviderAdapterV2Error>;
519 readonly respondToRuntimeRequest: (
520 input: ProviderAdapterV2RuntimeRequestResponseInput,
521 ) => Effect.Effect<void, ProviderAdapterV2Error>;
522 readonly readThreadSnapshot: (
523 input: ProviderAdapterV2ReadThreadSnapshotInput,
524 ) => Effect.Effect<ProviderAdapterV2ThreadSnapshot, ProviderAdapterV2Error>;
525 /**
526 * Providers that accept product feedback for a thread (#7949, Codex → OpenAI)
527 * expose it here; absent means the driver has no feedback channel.
528 */
529 readonly uploadFeedback?: (input: {
530 readonly providerThread: OrchestrationV2ProviderThread;
531 readonly reason?: string;
532 }) => Effect.Effect<{ readonly feedbackId: string }, ProviderAdapterV2Error>;
533 readonly rollbackThread: (
534 input: ProviderAdapterV2RollbackThreadInput,
535 ) => Effect.Effect<ProviderAdapterV2ThreadSnapshot, ProviderAdapterV2Error>;
536 readonly forkThread: (
537 input: ProviderAdapterV2ForkThreadInput,
538 ) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
540​
541export interface ProviderAdapterV2Shape {
542 readonly instanceId: ProviderInstanceId;
543 readonly driver: ProviderDriverKind;
544 readonly getCapabilities: () => Effect.Effect<
545 OrchestrationV2ProviderCapabilities,
546 ProviderAdapterV2Error
547 >;
548 readonly planSelectionTransition: (
549 input: ProviderSelectionTransitionInput,
550 ) => Effect.Effect<ProviderSelectionTransitionPlan, ProviderAdapterV2Error>;
551 readonly openSession: (
552 input: ProviderAdapterV2OpenSessionInput,
553 ) => Effect.Effect<ProviderAdapterV2SessionRuntime, ProviderAdapterV2Error, Scope.Scope>;
555​
556export class ProviderAdapterV2 extends Context.Service<ProviderAdapterV2, ProviderAdapterV2Shape>()(
557 "t3/orchestration-v2/ProviderAdapter/ProviderAdapterV2",
558) {}