@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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