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