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 TurnItemId,
36} from "@t3tools/contracts";
37import * as Context from "effect/Context";
38import * as Schema from "effect/Schema";
39import type * as Effect from "effect/Effect";
40import type * as Scope from "effect/Scope";
41import type * as Stream from "effect/Stream";
42
43import type {
44 ProviderSelectionTransitionInput,
45 ProviderSelectionTransitionPlan,
46} from "./selectionTransition.ts";
47
48export const ProviderAdapterV2RuntimePolicy = Schema.Struct({
49 runtimeMode: RuntimeMode,
50 interactionMode: ProviderInteractionMode,
51 cwd: Schema.NullOr(Schema.String),
52 approvalPolicy: Schema.optional(Schema.Unknown),
53 sandboxPolicy: Schema.optional(Schema.Unknown),
54 /**
55 * The administrator's ceiling, when a managed policy sets one. `runtimeMode` is already under
56 * it; adapters use it to refuse native mode choices a user makes beside T3 Code's own.
57 */
58 maxRuntimeMode: Schema.optional(RuntimeMode),
59});
60export type ProviderAdapterV2RuntimePolicy = typeof ProviderAdapterV2RuntimePolicy.Type;
61
62export const ProviderAdapterV2TurnMessage = Schema.Struct({
63 messageId: MessageId,
64 text: Schema.String,
65 attachments: Schema.Array(ChatAttachment),
66 createdBy: OrchestrationV2ConversationMessage.fields.createdBy,
67 creationSource: OrchestrationV2ConversationMessage.fields.creationSource,
68 scheduledTaskId: OrchestrationV2ConversationMessage.fields.scheduledTaskId,
69 senderThreadId: OrchestrationV2ConversationMessage.fields.senderThreadId,
70});
71export type ProviderAdapterV2TurnMessage = typeof ProviderAdapterV2TurnMessage.Type;
72
73export const ProviderAdapterV2SessionStatus = Schema.Literals([
74 "starting",
75 "ready",
76 "running",
77 "waiting",
78 "stopped",
79 "error",
80]);
81export type ProviderAdapterV2SessionStatus = typeof ProviderAdapterV2SessionStatus.Type;
82
83export const ProviderAdapterV2Event = Schema.Union([
84 Schema.Struct({
85 type: Schema.Literal("app_thread.created"),
86 driver: ProviderDriverKind,
87 appThread: OrchestrationV2AppThread,
88 createOnly: Schema.optional(Schema.Boolean),
89 }),
90 Schema.Struct({
91 type: Schema.Literal("provider_session.updated"),
92 driver: ProviderDriverKind,
93 providerSession: OrchestrationV2ProviderSession,
94 }),
95 Schema.Struct({
96 type: Schema.Literal("provider_thread.updated"),
97 driver: ProviderDriverKind,
98 providerThread: OrchestrationV2ProviderThread,
99 /** Work remaining at this point in the event stream, including native continuations. */
100 pendingBackgroundWork: Schema.optional(Schema.Boolean),
101 retainedNativeTurnIds: Schema.optional(Schema.Array(Schema.String)),
102 }),
103 Schema.Struct({
104 type: Schema.Literal("provider_turn.updated"),
105 driver: ProviderDriverKind,
106 threadId: Schema.optional(ThreadId),
107 providerTurn: OrchestrationV2ProviderTurn,
108 }),
109 Schema.Struct({
110 type: Schema.Literal("node.updated"),
111 driver: ProviderDriverKind,
112 node: OrchestrationV2ExecutionNode,
113 }),
114 Schema.Struct({
115 type: Schema.Literal("subagent.updated"),
116 driver: ProviderDriverKind,
117 subagent: OrchestrationV2Subagent,
118 }),
119 Schema.Struct({
120 type: Schema.Literal("message.updated"),
121 driver: ProviderDriverKind,
122 message: OrchestrationV2ConversationMessage,
123 }),
124 Schema.Struct({
125 type: Schema.Literal("turn_item.updated"),
126 driver: ProviderDriverKind,
127 turnItem: OrchestrationV2TurnItem,
128 }),
129 /** A steer the provider queued stays `pending` until the agent reads it; `cancelled` if dropped unread. */
130 Schema.Struct({
131 type: Schema.Literal("steer.updated"),
132 driver: ProviderDriverKind,
133 threadId: ThreadId,
134 runId: RunId,
135 messageId: MessageId,
136 status: Schema.Literals(["pending", "completed", "cancelled"]),
137 }),
138 // Start before the root terminal; clear only after the final covered projection.
139 // Consumer lifetime cannot depend on a producer probe that runs ahead of its queue.
140 Schema.Struct({
141 type: Schema.Literal("background_work.updated"),
142 driver: ProviderDriverKind,
143 providerTurnId: ProviderTurnId,
144 pending: Schema.Boolean,
145 }),
146 /** Unpersisted deltas go only to clients showing the row; final output arrives in turn_item.updated. */
147 Schema.Struct({
148 type: Schema.Literal("command_output.delta"),
149 driver: ProviderDriverKind,
150 threadId: ThreadId,
151 itemId: TurnItemId,
152 chunk: Schema.String,
153 }),
154 /** Unpersisted predicted next prompt; arrives after the run's root terminal. */
155 Schema.Struct({
156 type: Schema.Literal("prompt_suggestion.updated"),
157 driver: ProviderDriverKind,
158 threadId: ThreadId,
159 runId: RunId,
160 text: Schema.String,
161 }),
162 Schema.Struct({
163 type: Schema.Literal("runtime_request.updated"),
164 driver: ProviderDriverKind,
165 threadId: Schema.optional(ThreadId),
166 runtimeRequest: OrchestrationV2RuntimeRequest,
167 }),
168 Schema.Struct({
169 type: Schema.Literal("plan.updated"),
170 driver: ProviderDriverKind,
171 plan: OrchestrationV2PlanArtifact,
172 }),
173 Schema.Struct({
174 type: Schema.Literal("turn.terminal"),
175 driver: ProviderDriverKind,
176 providerThreadId: ProviderThreadId,
177 providerTurnId: ProviderTurnId,
178 runOrdinal: PositiveInt,
179 status: Schema.Literals(["completed", "interrupted", "cancelled"]),
180 failure: Schema.Null,
181 reason: Schema.optional(Schema.String),
182 threadDisposition: Schema.Literals(["reusable", "broken"]),
183 }),
184 Schema.Struct({
185 type: Schema.Literal("turn.terminal"),
186 driver: ProviderDriverKind,
187 providerThreadId: ProviderThreadId,
188 providerTurnId: ProviderTurnId,
189 runOrdinal: PositiveInt,
190 failureItemOrdinal: PositiveInt,
191 status: Schema.Literal("failed"),
192 failure: OrchestrationV2ProviderFailure,
193 retry: Schema.optional(OrchestrationV2ProviderRetry),
194 retryStartedAt: Schema.optional(Schema.DateTimeUtc),
195 threadDisposition: Schema.Literals(["reusable", "broken"]),
196 /** Child turns outlive root failure and report their own terminals; otherwise open children settle. */
197 childTurnsContinue: Schema.optional(Schema.Literal(true)),
198 }),
199]);
200export type ProviderAdapterV2Event = typeof ProviderAdapterV2Event.Type;
201
202export class ProviderAdapterCapabilitiesError extends Schema.TaggedError<ProviderAdapterCapabilitiesError>()(
203 "ProviderAdapterCapabilitiesError",
204 {
205 driver: ProviderDriverKind,
206 cause: Schema.optional(Schema.Defect()),
207 },
208) {
209 override get message(): string {
210 return `Failed to read ${this.driver} provider capabilities.`;
211 }
212}
213
214export class ProviderAdapterOpenSessionError extends Schema.TaggedError<ProviderAdapterOpenSessionError>()(
215 "ProviderAdapterOpenSessionError",
216 {
217 driver: ProviderDriverKind,
218 providerSessionId: ProviderSessionId,
219 requiresSignIn: Schema.optional(Schema.Literal(true)),
220 cause: Schema.optional(Schema.Defect()),
221 },
222) {
223 override get message(): string {
224 return `Failed to open ${this.driver} provider session ${this.providerSessionId}.`;
225 }
226}
227
228export class ProviderAdapterCloseSessionError extends Schema.TaggedError<ProviderAdapterCloseSessionError>()(
229 "ProviderAdapterCloseSessionError",
230 {
231 driver: ProviderDriverKind,
232 providerSessionId: ProviderSessionId,
233 cause: Schema.optional(Schema.Defect()),
234 },
235) {
236 override get message(): string {
237 return `Failed to close ${this.driver} provider session ${this.providerSessionId}.`;
238 }
239}
240
241export class ProviderAdapterResumeThreadError extends Schema.TaggedError<ProviderAdapterResumeThreadError>()(
242 "ProviderAdapterResumeThreadError",
243 {
244 driver: ProviderDriverKind,
245 providerSessionId: ProviderSessionId,
246 providerThreadId: ProviderThreadId,
247 cause: Schema.optional(Schema.Defect()),
248 },
249) {
250 override get message(): string {
251 return `Failed to resume ${this.driver} provider thread ${this.providerThreadId}.`;
252 }
253}
254
255/**
256 * The native thread is live in another process that owns its writes. Starting
257 * a replacement would split the conversation, so callers must not fall back.
258 */
259export class ProviderAdapterThreadInUseError extends Schema.TaggedError<ProviderAdapterThreadInUseError>()(
260 "ProviderAdapterThreadInUseError",
261 {
262 driver: ProviderDriverKind,
263 providerThreadId: ProviderThreadId,
264 detail: Schema.String,
265 cause: Schema.Defect(),
266 },
267) {
268 override get message(): string {
269 return this.detail;
270 }
271}
272
273export class ProviderAdapterEnsureThreadError extends Schema.TaggedError<ProviderAdapterEnsureThreadError>()(
274 "ProviderAdapterEnsureThreadError",
275 {
276 driver: ProviderDriverKind,
277 threadId: ThreadId,
278 cause: Schema.optional(Schema.Defect()),
279 },
280) {
281 override get message(): string {
282 return `Failed to ensure ${this.driver} provider thread for app thread ${this.threadId}.`;
283 }
284}
285
286export class ProviderAdapterReadThreadSnapshotError extends Schema.TaggedError<ProviderAdapterReadThreadSnapshotError>()(
287 "ProviderAdapterReadThreadSnapshotError",
288 {
289 driver: ProviderDriverKind,
290 providerThreadId: ProviderThreadId,
291 cause: Schema.optional(Schema.Defect()),
292 },
293) {
294 override get message(): string {
295 return `Failed to read ${this.driver} provider thread snapshot ${this.providerThreadId}.`;
296 }
297}
298
299export class ProviderAdapterRollbackThreadError extends Schema.TaggedError<ProviderAdapterRollbackThreadError>()(
300 "ProviderAdapterRollbackThreadError",
301 {
302 driver: ProviderDriverKind,
303 providerThreadId: ProviderThreadId,
304 checkpointId: Schema.optional(CheckpointId),
305 cause: Schema.optional(Schema.Defect()),
306 },
307) {
308 override get message(): string {
309 return `Failed to roll back ${this.driver} provider thread ${this.providerThreadId}.`;
310 }
311}
312
313export class ProviderAdapterForkThreadError extends Schema.TaggedError<ProviderAdapterForkThreadError>()(
314 "ProviderAdapterForkThreadError",
315 {
316 driver: ProviderDriverKind,
317 providerThreadId: ProviderThreadId,
318 cause: Schema.optional(Schema.Defect()),
319 },
320) {
321 override get message(): string {
322 return `Failed to fork ${this.driver} provider thread ${this.providerThreadId}.`;
323 }
324}
325
326export class ProviderAdapterTurnStartError extends Schema.TaggedError<ProviderAdapterTurnStartError>()(
327 "ProviderAdapterTurnStartError",
328 {
329 driver: ProviderDriverKind,
330 threadId: ThreadId,
331 providerThreadId: ProviderThreadId,
332 runId: RunId,
333 cause: Schema.optional(Schema.Defect()),
334 },
335) {
336 override get message(): string {
337 return `Failed to start run ${this.runId} on ${this.driver} provider thread ${this.providerThreadId}.`;
338 }
339}
340
341export class ProviderAdapterSteerRunUnsupportedError extends Schema.TaggedError<ProviderAdapterSteerRunUnsupportedError>()(
342 "ProviderAdapterSteerRunUnsupportedError",
343 {
344 driver: ProviderDriverKind,
345 providerThreadId: ProviderThreadId,
346 },
347) {
348 override get message(): string {
349 return `${this.driver} provider thread ${this.providerThreadId} does not support active-run steering.`;
350 }
351}
352
353export class ProviderAdapterSteerRunError extends Schema.TaggedError<ProviderAdapterSteerRunError>()(
354 "ProviderAdapterSteerRunError",
355 {
356 driver: ProviderDriverKind,
357 providerThreadId: ProviderThreadId,
358 providerTurnId: ProviderTurnId,
359 cause: Schema.optional(Schema.Defect()),
360 },
361) {
362 override get message(): string {
363 return `Failed to steer active run ${this.providerTurnId} on ${this.driver} provider thread ${this.providerThreadId}.`;
364 }
365}
366
367export class ProviderAdapterInterruptError extends Schema.TaggedError<ProviderAdapterInterruptError>()(
368 "ProviderAdapterInterruptError",
369 {
370 driver: ProviderDriverKind,
371 providerThreadId: ProviderThreadId,
372 providerTurnId: ProviderTurnId,
373 cause: Schema.optional(Schema.Defect()),
374 },
375) {
376 override get message(): string {
377 return `Failed to interrupt ${this.driver} provider turn ${this.providerTurnId}.`;
378 }
379}
380
381/** The provider did not confirm a stop in time; its processes may still be running. */
382export class ProviderAdapterInterruptTimeoutError extends Schema.TaggedError<ProviderAdapterInterruptTimeoutError>()(
383 "ProviderAdapterInterruptTimeoutError",
384 {
385 driver: ProviderDriverKind,
386 providerThreadId: ProviderThreadId,
387 providerTurnId: ProviderTurnId,
388 timeoutMs: Schema.Number,
389 },
390) {
391 override get message(): string {
392 return `The ${this.driver} provider did not confirm stopping turn ${this.providerTurnId} within ${this.timeoutMs} ms.`;
393 }
394}
395
396export class ProviderAdapterRuntimeRequestResponseError extends Schema.TaggedError<ProviderAdapterRuntimeRequestResponseError>()(
397 "ProviderAdapterRuntimeRequestResponseError",
398 {
399 driver: ProviderDriverKind,
400 requestId: RuntimeRequestId,
401 cause: Schema.optional(Schema.Defect()),
402 },
403) {
404 override get message(): string {
405 return `Failed to respond to ${this.driver} runtime request ${this.requestId}.`;
406 }
407}
408
409export class ProviderAdapterEventStreamError extends Schema.TaggedError<ProviderAdapterEventStreamError>()(
410 "ProviderAdapterEventStreamError",
411 {
412 driver: ProviderDriverKind,
413 providerSessionId: ProviderSessionId,
414 cause: Schema.optional(Schema.Defect()),
415 },
416) {
417 override get message(): string {
418 return `Failed while streaming ${this.driver} provider session ${this.providerSessionId} events.`;
419 }
420}
421
422// Only fixed reasons reach failure messages; detail can contain private configuration.
423const ProviderAdapterFailureReason = Schema.Literals([
424 "previous_turn_active",
425 "attachment_unreadable",
426]);
427export type ProviderAdapterFailureReason = typeof ProviderAdapterFailureReason.Type;
428
429export class ProviderAdapterProtocolError extends Schema.TaggedError<ProviderAdapterProtocolError>()(
430 "ProviderAdapterProtocolError",
431 {
432 driver: ProviderDriverKind,
433 detail: Schema.String,
434 reason: Schema.optional(ProviderAdapterFailureReason),
435 cause: Schema.optional(Schema.Defect()),
436 payload: Schema.optional(Schema.Unknown),
437 },
438) {
439 override get message(): string {
440 return `${this.driver} provider protocol error: ${this.detail}.`;
441 }
442}
443
444export class ProviderAdapterSessionStoppedError extends Schema.TaggedError<ProviderAdapterSessionStoppedError>()(
445 "ProviderAdapterSessionStoppedError",
446 { driver: ProviderDriverKind },
447) {
448 override get message(): string {
449 return `No running ${this.driver} session owns this thread.`;
450 }
451}
452
453export const ProviderAdapterV2Error = Schema.Union([
454 ProviderAdapterCapabilitiesError,
455 ProviderAdapterOpenSessionError,
456 ProviderAdapterCloseSessionError,
457 ProviderAdapterResumeThreadError,
458 ProviderAdapterThreadInUseError,
459 ProviderAdapterEnsureThreadError,
460 ProviderAdapterReadThreadSnapshotError,
461 ProviderAdapterRollbackThreadError,
462 ProviderAdapterForkThreadError,
463 ProviderAdapterTurnStartError,
464 ProviderAdapterSteerRunUnsupportedError,
465 ProviderAdapterSteerRunError,
466 ProviderAdapterInterruptError,
467 ProviderAdapterInterruptTimeoutError,
468 ProviderAdapterRuntimeRequestResponseError,
469 ProviderAdapterEventStreamError,
470 ProviderAdapterProtocolError,
471 ProviderAdapterSessionStoppedError,
472]);
473export type ProviderAdapterV2Error = typeof ProviderAdapterV2Error.Type;
474
475export interface ProviderAdapterV2OpenSessionInput {
476 readonly threadId: ThreadId;
477 readonly providerSessionId: ProviderSessionId;
478 readonly modelSelection: ModelSelection;
479 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
480 /** Labs flag, read live: emit `prompt_suggestion.updated` after completed turns, where the provider can. */
481 readonly promptSuggestions?: Effect.Effect<boolean>;
482 readonly resumeFromSession?: OrchestrationV2ProviderSession;
483 readonly initialNativeThreadId?: string;
484 readonly initialProviderItemIdentityVersion?: 2;
485}
486
487export interface ProviderAdapterV2EnsureThreadInput {
488 readonly threadId: ThreadId;
489 readonly title?: string;
490 readonly modelSelection: ModelSelection;
491 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
492 readonly providerSessionId?: ProviderSessionId;
493 readonly existingProviderThread?: OrchestrationV2ProviderThread;
494 readonly forceNewNativeThread?: boolean;
495}
496
497export interface ProviderAdapterV2TurnInput {
498 readonly appThread: OrchestrationV2AppThread;
499 readonly threadId: ThreadId;
500 readonly runId: RunId;
501 readonly runOrdinal: number;
502 readonly nativeThreadHasTurns?: boolean;
503 readonly providerTurnOrdinal: number;
504 readonly restartContinuationOfRunId?: RunId;
505 readonly attemptId: RunAttemptId;
506 readonly rootNodeId: NodeId;
507 readonly providerThread: OrchestrationV2ProviderThread;
508 readonly message: ProviderAdapterV2TurnMessage;
509 readonly modelSelection: ModelSelection;
510 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
511 readonly appContext?: ReadonlyArray<{ readonly key: string; readonly text: string }>;
512}
513
514export interface ProviderAdapterV2SteerInput {
515 readonly threadId: ThreadId;
516 readonly runId: RunId;
517 readonly providerThread: OrchestrationV2ProviderThread;
518 readonly providerTurnId: ProviderTurnId;
519 readonly message: ProviderAdapterV2TurnMessage;
520}
521
522export interface ProviderAdapterV2InterruptInput {
523 readonly providerThread: OrchestrationV2ProviderThread;
524 readonly providerTurnId: ProviderTurnId;
525 readonly requestRuntimeRestart?: boolean;
526}
527
528export interface ProviderAdapterV2RuntimeRequestResponseInput {
529 readonly requestId: RuntimeRequestId;
530 readonly decision?: ProviderApprovalDecision;
531 readonly feedback?: string;
532 readonly answers?: ProviderUserInputAnswers;
533}
534
535export interface ProviderAdapterV2ThreadSnapshot {
536 readonly providerThread: OrchestrationV2ProviderThread;
537 readonly providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
538 readonly messages: ReadonlyArray<OrchestrationV2ConversationMessage>;
539 readonly runtimeRequests: ReadonlyArray<OrchestrationV2RuntimeRequest>;
540 readonly providerPayload?: unknown;
541}
542
543export interface ProviderAdapterV2ReadThreadSnapshotInput {
544 readonly providerThread: OrchestrationV2ProviderThread;
545}
546
547export type ProviderAdapterV2RollbackTarget =
548 | {
549 readonly type: "thread_start";
550 readonly checkpointId: CheckpointId;
551 readonly appRunOrdinal: 0;
552 }
553 | {
554 readonly type: "provider_turn";
555 readonly checkpointId: CheckpointId;
556 readonly appRunOrdinal: number;
557 readonly providerTurn: OrchestrationV2ProviderTurn;
558 readonly message?: Pick<OrchestrationV2ConversationMessage, "role" | "text" | "attachments">;
559 };
560
561export interface ProviderAdapterV2RollbackThreadInput {
562 readonly providerThread: OrchestrationV2ProviderThread;
563 readonly target: ProviderAdapterV2RollbackTarget;
564 readonly providerThreadTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
565}
566
567export interface ProviderAdapterV2ForkThreadInput {
568 readonly sourceProviderThread: OrchestrationV2ProviderThread;
569 readonly sourceProviderTurns?: ReadonlyArray<OrchestrationV2ProviderTurn>;
570 readonly providerTurnId?: ProviderTurnId;
571 readonly targetThreadId: ThreadId;
572 readonly ownerNodeId?: NodeId;
573 readonly modelSelection?: ModelSelection;
574 readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy;
575}
576
577export interface ProviderAdapterV2EventSubscription {
578 readonly events: Stream.Stream<ProviderAdapterV2Event, ProviderAdapterV2Error>;
579 readonly close: Effect.Effect<void>;
580}
581
582export interface ProviderAdapterV2HistoricalContext {
583 readonly messages: ReadonlyArray<OrchestrationV2HistoricalMessage>;
584 readonly context: string;
585}
586
587export interface ProviderAdapterV2McpTool {
588 readonly name: string;
589 // Apps reject a `hostContext.toolInfo.tool` without one.
590 readonly inputSchema: unknown;
591 readonly _meta?: unknown;
592 readonly annotations?: unknown;
593}
594
595export interface ProviderAdapterV2McpCallToolResult {
596 readonly content: ReadonlyArray<unknown>;
597 readonly structuredContent?: unknown;
598 readonly isError?: boolean;
599 readonly _meta?: unknown;
600}
601
602export interface ProviderAdapterV2McpApps {
603 readonly listTools: (input: {
604 readonly providerThread: OrchestrationV2ProviderThread;
605 readonly server: string;
606 }) => Effect.Effect<ReadonlyArray<ProviderAdapterV2McpTool>, ProviderAdapterV2Error>;
607 readonly callTool: (input: {
608 readonly providerThread: OrchestrationV2ProviderThread;
609 readonly server: string;
610 readonly tool: string;
611 readonly arguments: Record<string, unknown>;
612 }) => Effect.Effect<ProviderAdapterV2McpCallToolResult, ProviderAdapterV2Error>;
613 readonly readResource: (input: {
614 readonly providerThread: OrchestrationV2ProviderThread;
615 readonly server: string;
616 readonly uri: string;
617 }) => Effect.Effect<{ readonly contents: ReadonlyArray<unknown> }, ProviderAdapterV2Error>;
618}
619
620export type ProviderAdapterV2SubagentOutcome = {
621 readonly status: "completed" | "failed" | "cancelled";
622 readonly completedAt: NonNullable<OrchestrationV2Subagent["completedAt"]>;
623 readonly result: OrchestrationV2Subagent["result"];
624};
625
626export interface ProviderAdapterV2SessionRuntime {
627 readonly instanceId: ProviderInstanceId;
628 readonly driver: ProviderDriverKind;
629 readonly providerSessionId: ProviderSessionId;
630 readonly providerSession: OrchestrationV2ProviderSession;
631 /** False keeps conversations alive when the provider cannot restore them after a restart. */
632 readonly canResumeAfterRestart?: boolean;
633 readonly events: Stream.Stream<ProviderAdapterV2Event, ProviderAdapterV2Error>;
634 /** Manager runtimes broadcast independent subscriptions; adapters may expose only a single-consumer stream. */
635 readonly subscribeEvents?: Effect.Effect<ProviderAdapterV2EventSubscription>;
636 readonly hasPendingBackgroundWork?: Effect.Effect<boolean>;
637 /** Root-subscription probe; replacement checks opt in to subagents owned by the live process. */
638 readonly hasPendingBackgroundWorkForThread?: (
639 providerThread: OrchestrationV2ProviderThread,
640 options?: { readonly includeSubagents?: boolean },
641 ) => Effect.Effect<boolean>;
642 /** Set only if all session background tasks end with its process; otherwise threads must keep Waiting. */
643 readonly backgroundTasksEndWithProcess?: true;
644 readonly getModelContextWindow?: (
645 modelSelection: ModelSelection,
646 cwd?: string | null,
647 ) => number | undefined;
648 readonly canReuseContextUsage?: (previous: ModelSelection, next: ModelSelection) => boolean;
649 readonly ensureThread: (
650 input: ProviderAdapterV2EnsureThreadInput,
651 ) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
652 readonly resumeThread: (input: {
653 readonly providerThread: OrchestrationV2ProviderThread;
654 readonly threadId?: ThreadId;
655 readonly modelSelection?: ModelSelection;
656 readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy;
657 }) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
658 /** False means the native protocol explicitly does not support history injection. */
659 readonly injectHistory?: (
660 input: ProviderAdapterV2HistoricalContext & {
661 readonly providerThread: OrchestrationV2ProviderThread;
662 },
663 ) => Effect.Effect<boolean, ProviderAdapterV2Error>;
664 readonly startTurn: (
665 input: ProviderAdapterV2TurnInput,
666 ) => Effect.Effect<void, ProviderAdapterV2Error>;
667 readonly compactThread?: (
668 input: ProviderAdapterV2TurnInput,
669 ) => Effect.Effect<void, ProviderAdapterV2Error>;
670 readonly steerTurn: (
671 input: ProviderAdapterV2SteerInput,
672 ) => Effect.Effect<void, ProviderAdapterV2Error>;
673 readonly stopTask?: (input: {
674 readonly providerThread: OrchestrationV2ProviderThread;
675 readonly taskId: string;
676 }) => Effect.Effect<void, ProviderAdapterV2Error>;
677 /**
678 * Marks or unmarks background tasks the agent will resume from, using the ids the agent saw.
679 * Ids not running on this provider thread come back unmatched and change nothing.
680 */
681 readonly awaitBackgroundTasks?: (input: {
682 readonly providerThread: OrchestrationV2ProviderThread;
683 readonly taskIds: ReadonlyArray<string>;
684 readonly awaited: boolean;
685 }) => Effect.Effect<{ readonly matched: ReadonlyArray<string> }, ProviderAdapterV2Error>;
686 readonly interruptTurn: (
687 input: ProviderAdapterV2InterruptInput,
688 ) => Effect.Effect<void, ProviderAdapterV2Error>;
689 readonly stopSubagent?: (input: {
690 readonly providerThread: OrchestrationV2ProviderThread;
691 readonly nativeTaskId: string;
692 /** A delayed Stop must not interrupt a task resumed after this request. */
693 readonly requestedAt?: NonNullable<OrchestrationV2Subagent["startedAt"]>;
694 }) => Effect.Effect<void | ProviderAdapterV2SubagentOutcome, ProviderAdapterV2Error>;
695 readonly unloadThread?: (input: {
696 readonly providerThread: OrchestrationV2ProviderThread;
697 }) => Effect.Effect<void, ProviderAdapterV2Error>;
698 readonly respondToRuntimeRequest: (
699 input: ProviderAdapterV2RuntimeRequestResponseInput,
700 ) => Effect.Effect<void, ProviderAdapterV2Error>;
701 readonly readThreadSnapshot: (
702 input: ProviderAdapterV2ReadThreadSnapshotInput,
703 ) => Effect.Effect<ProviderAdapterV2ThreadSnapshot, ProviderAdapterV2Error>;
704 readonly uploadFeedback?: (input: {
705 readonly providerThread: OrchestrationV2ProviderThread;
706 readonly reason?: string;
707 }) => Effect.Effect<{ readonly feedbackId: string }, ProviderAdapterV2Error>;
708 /** Absent means non-interactive apps with plain tool rows. */
709 readonly mcpApps?: ProviderAdapterV2McpApps;
710 readonly rollbackThread: (
711 input: ProviderAdapterV2RollbackThreadInput,
712 ) => Effect.Effect<ProviderAdapterV2ThreadSnapshot, ProviderAdapterV2Error>;
713 readonly forkThread: (
714 input: ProviderAdapterV2ForkThreadInput,
715 ) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
716}
717
718export class ProviderAdapterV2 extends Context.Service<
719 ProviderAdapterV2,
720 {
721 readonly instanceId: ProviderInstanceId;
722 readonly driver: ProviderDriverKind;
723 readonly getCapabilities: () => Effect.Effect<
724 OrchestrationV2ProviderCapabilities,
725 ProviderAdapterV2Error
726 >;
727 readonly planSelectionTransition: (
728 input: ProviderSelectionTransitionInput,
729 ) => Effect.Effect<ProviderSelectionTransitionPlan, ProviderAdapterV2Error>;
730 readonly openSession: (
731 input: ProviderAdapterV2OpenSessionInput,
732 ) => Effect.Effect<ProviderAdapterV2SessionRuntime, ProviderAdapterV2Error, Scope.Scope>;
733 }
734>()("@t3tools/provider-core/server/ProviderAdapter/ProviderAdapterV2") {}