Repository navigation
Expand file tree
/
Copy pathadapter.ts
More file actions
9422 lines (9223 loc) · 401 KB
/
Copy pathadapter.ts
File metadata and controls
9422 lines (9223 loc) · 401 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @effect-diagnostics nodeBuiltinImport:off
import {
type ChatAttachment,
type ModelSelection,
type OrchestrationV2ConversationMessage,
type OrchestrationV2ExecutionNode,
type OrchestrationV2PlanArtifact,
type OrchestrationV2PlanStep,
type OrchestrationV2ProviderCapabilities,
type OrchestrationV2ProviderFailure,
type OrchestrationV2ProviderRetry,
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
type OrchestrationV2ProviderThreadNativeMetadata,
type OrchestrationV2ProviderTurn,
type OrchestrationV2RuntimeRequest,
type OrchestrationV2Subagent,
type OrchestrationV2TurnItem,
type OrchestrationV2UserInputQuestion,
type OrchestrationV2WebSearchResult,
type ProviderApprovalDecision,
type ProviderApprovalOption,
type ProviderInstanceId,
type ProviderInteractionMode,
type ProviderDriverKind,
type ProviderRequestKind,
type ProviderThreadId,
type ProviderUserInputAnswers,
type RuntimeMode,
type RuntimeRequestId,
type ThreadTokenUsageSnapshot,
type ThreadId,
isRuntimeModeAbove,
type TurnTokenUsage,
} from "@t3tools/contracts";
import { AgentScope, AgentScopeThreadId } from "@t3tools/shared/AgentScope";
import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender";
import { modelSelectionsEqual } from "@t3tools/shared/model";
import { type SelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
import {
compactDynamicToolOutput,
htmlRenderFromToolItem,
mcpToolResultOutput,
} from "@t3tools/shared/toolOutput";
import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpProtocol from "effect-acp/protocol";
import type * as EffectAcpSchema from "effect-acp/compat";
import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/toolActivity";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import { makeAcpMcpOverAcpBridge, type AcpMcpOverAcpBridge } from "./mcpOverAcpBridge.ts";
import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import {
applyAcpAgentTerminalUpdate,
acpContentBlockDisplayText,
embeddedTerminalIdsFromSessionUpdate,
extractMcpToolCallIdentity,
findModelConfigOption,
mergeToolCallState,
parsePermissionRequest,
parseSessionUpdateEvent,
toolCallVisibleOutputChanged,
withTrackedPermissionToolCall,
type AcpPlanUpdate,
type AcpAgentTerminalState,
type AcpSessionModeState,
type AcpToolCallState,
} from "./runtimeModel.ts";
import {
acpClientExecuteDisposition,
acpMcpToolApprovalElicitationDisposition,
acpPermissionDisposition,
type AcpPermissionDisposition,
makeAcpClientPolicyGrants,
unknownRecord,
} from "./clientPolicy.ts";
import {
makeAcpClientTerminals,
resolveEmbeddedTerminalContent,
type AcpClientTerminals,
} from "./clientTerminals.ts";
import {
ACP_EMPTY_OPTION_VALUE,
ACP_SESSION_MODE_OPTION_ID,
flattenSelectChoices,
} from "./sessionConfig.ts";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
import {
t3AcpPromptWithInstructions,
type T3AcpInstructionState,
} from "@t3tools/provider-core/server/orchestrationInstructions";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import {
type BackgroundWork,
type BackgroundWorkReport,
backgroundWorkNotification,
} from "@t3tools/provider-core/server/notification";
import {
makeProviderFailure,
makeProviderRetryTurnItem,
} from "@t3tools/provider-core/server/failure";
import { acpSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
import {
isProviderNativeImageAttachment,
providerMessageTextWithAttachmentPaths,
} from "@t3tools/provider-core/server/attachmentPrompt";
import {
makeSubagentChildThread,
makeSubagentConversationArtifacts,
subagentThreadTitle,
} from "@t3tools/provider-core/server/subagentProjection";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
export const ACP_PROTOCOL = "acp.ndjson-jsonrpc" as const;
// Grok summaries can trail hydrated tools by over two seconds; shorter waits split the wake.
const ACP_DEFERRED_FINALIZE_DEBOUNCE: Duration.Input = "3000 millis";
/**
* Emit first chunks and segment-close events immediately; coalesce later chunks into full-text snapshots.
* This avoids quadratic output; scheduled flushes can run late under host load.
*/
const ACP_TEXT_FLUSH_INTERVAL: Duration.Input = "50 millis";
// Output of the running prompt. Session metadata and unknown updates do not reset its timeout.
const ACP_PROMPT_ACTIVITY_UPDATES: ReadonlySet<string> = new Set([
"agent_message",
"agent_message_chunk",
"agent_thought",
"agent_thought_chunk",
"tool_call",
"tool_call_update",
"tool_call_content_chunk",
"terminal_output_chunk",
"terminal_update",
"plan",
"plan_update",
"plan_removed",
"compaction_update",
"compaction_summary_chunk",
]);
export interface AcpAdapterV2RuntimeInput {
readonly cwd: string;
readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
readonly mcpServers: ReadonlyArray<EffectAcpSchema.McpServer>;
readonly acpMcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;
readonly httpMcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;
readonly processEnvironment?: NodeJS.ProcessEnv;
readonly resumeSessionId?: string;
readonly interruptPromptOnCancel?: boolean;
readonly clientCapabilities: EffectAcpSchema.InitializeRequest["clientCapabilities"];
readonly clientInfo: AcpSessionRuntime.AcpSessionRuntimeOptions["clientInfo"];
readonly requestLogger?: NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions["requestLogger"]>;
readonly protocolLogging: NonNullable<
AcpSessionRuntime.AcpSessionRuntimeOptions["protocolLogging"]
>;
readonly onTermination: NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions["onTermination"]>;
readonly onOutgoingResponseFailure?: AcpSessionRuntime.AcpSessionRuntimeOptions["onOutgoingResponseFailure"];
readonly onOutgoingResponse?: AcpSessionRuntime.AcpSessionRuntimeOptions["onOutgoingResponse"];
readonly onIncomingRequest?: AcpSessionRuntime.AcpSessionRuntimeOptions["onIncomingRequest"];
}
export type AcpAdapterV2NativeLogging = Pick<
AcpSessionRuntime.AcpSessionRuntimeOptions,
"requestLogger" | "protocolLogging"
>;
export interface AcpAdapterV2UserInputRequest {
readonly nativeItemId: string;
readonly nativeRequestId: string;
readonly questions: ReadonlyArray<OrchestrationV2UserInputQuestion>;
}
export interface AcpAdapterV2ExtensionContext {
readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"];
readonly reportProviderRetry: (input: {
readonly sessionId: string;
readonly failure: OrchestrationV2ProviderFailure;
}) => Effect.Effect<void>;
readonly finishSubagent: (notice: {
readonly sessionId: string;
readonly childSessionId: string;
readonly status: "completed" | "failed" | "cancelled";
readonly result: string | null;
}) => Effect.Effect<void>;
readonly applyBackgroundTaskMutation: (mutation: {
readonly sessionId: string;
readonly taskId: string;
readonly status: "running" | "completed" | "failed";
readonly output?: string;
readonly report?: BackgroundWork;
}) => Effect.Effect<void>;
readonly requestUserInput: (
input: AcpAdapterV2UserInputRequest,
requestContext: EffectAcpProtocol.AcpRequestContext,
) => Effect.Effect<
{
readonly acknowledgeNativeResponse: Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly answers: ProviderUserInputAnswers | null;
},
EffectAcpErrors.AcpError
>;
readonly captureProposedPlan: (input: { readonly planMarkdown: string }) => Effect.Effect<void>;
readonly lastProposedPlanMarkdown: Effect.Effect<string | undefined>;
}
/**
* Raised when an agent does not accept the session's model selection: the
* session's model option does not offer it, or the agent answers the write
* with invalid params. `makeProviderFailure` shows its message to the user;
* the agent's reply stays on `cause`.
*/
class AcpModelSelectionError extends Schema.TaggedError<AcpModelSelectionError>()(
"AcpModelSelectionError",
{
model: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `The agent did not accept the model "${this.model}". Choose another model for this provider, then retry.`;
}
}
/**
* Maps one per-turn usage sample (flavors with reportsPerTurnPromptUsage)
* directly onto TurnTokenUsage: the response's counters already cover exactly
* this prompt.
*/
export function acpPerTurnPromptUsage(
usage: EffectAcpSchema.Usage | null | undefined,
hasSubagents: boolean,
terminalStatus: OrchestrationV2ProviderTurn["status"],
geminiUsage = false,
): TurnTokenUsage {
if (usage == null) {
return { usageScope: "main_agent", usageStatus: "unavailable", hasSubagents };
}
const inputTokens = geminiUsage
? usage.inputTokens + (usage.cachedReadTokens ?? 0)
: usage.inputTokens;
const outputTokens = geminiUsage
? usage.outputTokens + (usage.thoughtTokens ?? 0)
: usage.outputTokens;
// TurnTokenUsage contract: input includes cache read + write and reasoning
// is a subset of output, so clamp counters that exceed their parent and
// drop the ones the agent left unset. Cache writes are capped at whatever
// cache reads leave of input, so the pair cannot exceed it.
const clampSubset = (value: number | null | undefined, parent: number) =>
value == null ? undefined : Math.min(value, parent);
const cachedInputTokens = clampSubset(usage.cachedReadTokens, inputTokens);
const cacheCreationTokens = clampSubset(
usage.cachedWriteTokens,
inputTokens - (cachedInputTokens ?? 0),
);
const reasoningTokens = clampSubset(usage.thoughtTokens, outputTokens);
return {
usageScope: "main_agent",
usageStatus: terminalStatus === "completed" ? "complete" : "partial",
hasSubagents,
inputTokens,
outputTokens,
...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),
...(cacheCreationTokens === undefined ? {} : { cacheCreationTokens }),
...(reasoningTokens === undefined ? {} : { reasoningTokens }),
};
}
export interface AcpAdapterV2Flavor {
readonly buildPrompt?: (input: {
readonly text: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];
readonly agentVersion: string | undefined;
/** The session's model after selection, with its display name when the agent lists it. */
readonly currentModel: { readonly id: string; readonly name: string | undefined } | undefined;
}) => Effect.Effect<ReadonlyArray<EffectAcpSchema.ContentBlock>, EffectAcpErrors.AcpError>;
readonly promptFailure?: (cause: unknown) => OrchestrationV2ProviderFailure;
/**
* Runs before `session/prompt`. The returned check sees a prompt the agent ended
* without an error or cancel, and reports a failure its stop reason hid. A reported
* failure restarts the runtime before the next turn.
*/
readonly watchPromptOutcome?: (
sessionId: string,
) => Effect.Effect<
(
result: EffectAcpSchema.PromptResponse,
) => Effect.Effect<OrchestrationV2ProviderFailure | undefined>
>;
readonly requiresSignIn?: (cause: unknown) => boolean;
/**
* Runs before attachment paths, T3 instructions and native slash-command detection,
* so a rewrite can turn the user's text into a native command.
*/
readonly rewriteUserText?: (
text: string,
turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
) => Effect.Effect<string, never, ChildProcessSpawner.ChildProcessSpawner>;
readonly driver: ProviderDriverKind;
readonly capabilities: OrchestrationV2ProviderCapabilities;
readonly clientCapabilitiesMeta?: NonNullable<
EffectAcpSchema.InitializeRequest["clientCapabilities"]
>["_meta"];
readonly mcpOverHttp?: boolean;
readonly normalizeSessionUpdate?: (
notification: EffectAcpSchema.SessionNotification,
) => EffectAcpSchema.SessionNotification;
/**
* Agent updates that belong to no turn (Kiro's own cloud-config fetch). They
* are dropped before anything reads them, so they neither show in the turn
* nor count as it starting.
*/
readonly ignoreSessionUpdate?: (notification: EffectAcpSchema.SessionNotification) => boolean;
readonly onAvailableCommandsUpdate?: (
commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
) => Effect.Effect<void>;
readonly onSessionConfigurationUpdate?: (
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
modeState: AcpSessionModeState | undefined,
modelState: EffectAcpSchema.SessionModelState | null | undefined,
) => Effect.Effect<void>;
readonly onUrlElicitation?: (input: {
readonly elicitationId: string;
readonly url: string;
readonly message: string;
}) => Effect.Effect<boolean>;
readonly extractElicitationForm?: (request: EffectAcpSchema.CreateElicitationRequest) =>
| {
readonly questions: ReadonlyArray<OrchestrationV2UserInputQuestion>;
readonly respond: (
answers: ProviderUserInputAnswers,
) => EffectAcpSchema.CreateElicitationResponse;
}
| undefined;
readonly withRuntimeStartup?: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
readonly makeRuntime: (
input: AcpAdapterV2RuntimeInput,
) => Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope
>;
readonly customModels?: ReadonlyArray<string>;
readonly resolveModelId?: (selection: ModelSelection) => string | undefined;
/**
* The agent advertises its model option only after `session/new` returns
* (Kiro sends it in a `config_option_update`), so in-session model switching
* is not inferred from the setup result.
*/
readonly modelOptionArrivesLate?: boolean;
readonly getModelContextWindow?: (
selection: ModelSelection,
session: AcpSessionRuntime.AcpSessionRuntimeStartResult,
) => number | undefined;
readonly applyModelSelection?: (input: {
readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"];
readonly startResult: AcpSessionRuntime.AcpSessionRuntimeStartResult;
readonly modelSelection: ModelSelection;
}) => Effect.Effect<string | undefined, EffectAcpErrors.AcpError>;
/**
* Model-selection option ids `applyModelSelection` sets itself under a
* native id, which the generic option loop then skips (Kiro's
* `reasoningEffort` is its `effortLevel`).
*/
readonly ownedModelOptionIds?: ReadonlyArray<string>;
readonly sessionModeForPolicy?: (
policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
) => string | undefined;
/**
* Native select-option values to apply for a runtime policy (e.g. Kiro's
* `autopilot`), set on every session configure. A value the session does
* not advertise is skipped; an agent rejecting it fails the session.
*/
readonly sessionConfigForPolicy?: (
policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
) => ReadonlyArray<{ readonly id: string; readonly value: string }>;
/**
* The runtime mode a native session mode grants, for flavors whose modes are permission levels.
* Under a policy ceiling, a mode the user picks that this does not place under it is not applied.
*/
readonly runtimeModeForSessionMode?: (modeId: string) => RuntimeMode | undefined;
readonly clientFileSystem?: {
readonly readTextFile: (
request: EffectAcpSchema.ReadTextFileRequest,
cwd: string | null,
) => Effect.Effect<EffectAcpSchema.ReadTextFileResponse, EffectAcpErrors.AcpError>;
readonly writeTextFile?: (
request: EffectAcpSchema.WriteTextFileRequest,
cwd: string | null,
) => Effect.Effect<EffectAcpSchema.WriteTextFileResponse, EffectAcpErrors.AcpError>;
};
readonly extractPermissionQuestion?: (request: EffectAcpSchema.RequestPermissionRequest) =>
| {
readonly question: OrchestrationV2UserInputQuestion;
readonly respond: (
answers: ProviderUserInputAnswers,
) => EffectAcpSchema.RequestPermissionResponse | undefined;
}
| undefined;
/** Grok Auto asks only about classifier refusals; T3 policy must not auto-approve them. */
readonly permissionDisposition?: (
policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
request: EffectAcpSchema.RequestPermissionRequest,
) => AcpPermissionDisposition;
readonly approvalOptions?: (
request: EffectAcpSchema.RequestPermissionRequest,
) => ReadonlyArray<ProviderApprovalOption>;
readonly onSessionEvent?: (
event: AcpSessionRuntime.AcpSessionRuntimeEvent,
) => Effect.Effect<void>;
readonly subagentsIdleOnTurnCompletion?: boolean;
readonly supportsCompaction?: boolean;
/**
* Native steering: `send` queues a message into the running turn and returns the
* agent's id for it, which `injectedSteerId` reads from the update that delivers it.
*/
readonly steering?: {
readonly send: (
runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
sessionId: string,
text: string,
) => Effect.Effect<string, EffectAcpErrors.AcpError>;
readonly injectedSteerId: (
notification: EffectAcpSchema.SessionNotification,
) => string | undefined;
};
/**
* Native fork from an earlier turn. `nativeTurnId` reads the agent's id for a running
* turn's prompt, which the turn keeps as its native ref; forking from that turn sends
* `forkMeta(id)` as the `session/fork` `_meta`.
*/
readonly forkFromTurn?: {
readonly supported: (
initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"],
) => boolean;
readonly nativeTurnId: (
notification: EffectAcpSchema.SessionNotification,
) => string | undefined;
readonly forkMeta: (
nativeTurnId: string,
) => NonNullable<EffectAcpSchema.ForkSessionRequest["_meta"]>;
};
/** Compacts with the agent's own request, for agents that answer a `/compact` prompt as chat. */
readonly compactSession?: (
runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
sessionId: string,
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly runtimeHarness?: string;
readonly registerExtensions?: (
context: AcpAdapterV2ExtensionContext,
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly extractSubagentSessionEvent?: (
notification: EffectAcpSchema.SessionNotification,
) => AcpSubagentSessionEvent | undefined;
readonly extractSubagentUpdate?: (
toolCall: AcpToolCallState,
) => AcpAdapterV2SubagentUpdate | undefined;
readonly isProvisionalSubagentTool?: (toolCall: AcpToolCallState) => boolean;
readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState;
readonly extractProposedPlanMarkdown?: (toolCall: AcpToolCallState) => string | undefined;
readonly extractBackgroundTaskId?: (toolCall: AcpToolCallState) => string | undefined;
/** Distinguishes commands from monitors when lifecycle notifications omit their kind. */
readonly isBackgroundCommandTool?: (toolCall: AcpToolCallState) => boolean;
readonly extractBackgroundToolMutation?: (text: string) => ReadonlyArray<{
readonly taskId: string;
readonly status: "running" | "completed" | "failed";
readonly appendOutput: string;
}>;
readonly extractSubagentEndNotice?: (text: string) =>
| {
readonly childSessionId: string;
readonly status: "completed" | "failed";
}
| undefined;
readonly extractBackgroundTaskCompletion?: (toolCall: AcpToolCallState) => ReadonlyArray<{
readonly taskId: string;
readonly status: "running" | "completed" | "failed";
readonly appendOutput: string;
}>;
readonly isPersistentBackgroundTool?: (toolCall: AcpToolCallState) => boolean;
readonly isProviderWakeNotification?: (
notification: EffectAcpSchema.SessionNotification,
) => boolean;
readonly deferFinalizeForBackgroundWork?: boolean;
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
/** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */
readonly interruptPromptOnCancel?: boolean;
/**
* Hold `session/cancel` until an update after `session/prompt` matches `isStart`,
* or `bound` has passed; skip it if the prompt settles first. Kiro 2.27.1 can
* drop a cancel sent just after the prompt and run the turn to completion.
*/
readonly cancelAfterPromptStarts?: {
readonly isStart: (update: EffectAcpSchema.SessionUpdate) => boolean;
readonly bound: Duration.Input;
};
/**
* The agent's PromptResponse.usage counters read per-turn. The ACP spec
* leaves usage semantics open, so this stays unset until proven live.
*/
readonly reportsPerTurnPromptUsage?: boolean;
/** Gemini-style usage: inputTokens leaves out cachedReadTokens, outputTokens leaves out thoughtTokens. */
readonly geminiPromptUsage?: boolean;
/**
* Fails a dispatched prompt after this long with no update for its session while no
* agent request, tool or subagent is open, and replaces the agent before the next turn.
*/
readonly promptInactivityTimeout?: Duration.Input;
/** Grok can retain task_already_running until process exit. */
readonly restartRuntimeAfterInterrupt?: boolean;
/** Prompt failures after which the agent process keeps failing until replaced. */
readonly restartRuntimeAfterPromptError?: (error: unknown) => boolean;
readonly restartRuntimeOnEveryInterrupt?: boolean;
readonly terminateRuntimeProcessGroupOnInterrupt?: boolean;
readonly preserveRuntimeOnSettledInterrupt?: boolean;
readonly enablePostSettleContinuation?: boolean;
/** Settle on native idle after the accepted user echo, only on negotiated ACP v2. */
readonly followAgentWorkState?: boolean;
/**
* Grok CLI currently accepts and vision-processes image blocks while still
* reporting the capability as false; without this override, screenshot turns
* fail before `session/prompt`.
*/
readonly supportsImagePrompts?: boolean;
/**
* True when this session's native system prompt carries T3's PR-linking instructions, so
* turns omit them. Must use the same negotiated check that sent them on session setup.
*/
readonly sessionCarriesPullRequestLinking?: (
initializeResult: EffectAcpSchema.InitializeResponse,
) => boolean;
}
function acpSupportsImagePrompts(input: {
readonly flavorSupportsImagePrompts?: boolean | undefined;
readonly negotiatedImage?: boolean | undefined;
}): boolean {
return input.flavorSupportsImagePrompts === true || input.negotiatedImage === true;
}
export function acpScopedNativeId(instanceId: ProviderInstanceId, nativeId: string): string {
return `provider-instance:${encodeURIComponent(instanceId)}:${nativeId}`;
}
function acpProviderItemNativeId(input: {
readonly instanceId: ProviderInstanceId;
readonly itemIdentityVersion: 2 | undefined;
readonly nativeId: string;
}): string {
return input.itemIdentityVersion === 2
? acpScopedNativeId(input.instanceId, input.nativeId)
: input.nativeId;
}
export type AcpSubagentSessionEvent =
| {
readonly type: "state";
readonly childSessionId: string;
readonly parentSessionId: string;
readonly status: "running" | "completed" | "failed" | "cancelled";
readonly result: string | null;
}
| {
readonly type: "delegation";
readonly childSessionId: string;
readonly parentSessionId: string | null;
readonly delegationId: string;
readonly prompt: string;
};
export interface AcpAdapterV2SubagentUpdate {
readonly nativeTaskId: string;
readonly prompt: string;
readonly title: string | null;
readonly model: string | null;
readonly status:
| "pending"
| "running"
| "idle"
| "completed"
| "failed"
| "interrupted"
| "cancelled";
readonly childSessionId: string | null;
readonly result: string | null;
readonly suppressNormalTool?: boolean;
}
export interface AcpAdapterV2Options {
readonly instanceId: ProviderInstanceId;
readonly flavor: AcpAdapterV2Flavor;
readonly selfInvocation: SelfInvocation;
readonly clientTerminals?: {
readonly environment?: NodeJS.ProcessEnv;
readonly shellCommands?: boolean;
};
readonly nativeLogging?: (threadId: ThreadId) => AcpAdapterV2NativeLogging;
readonly continuationRequests?: {
readonly offer: (
request: ProviderContinuationRequests.ProviderContinuationRequest,
) => Effect.Effect<void>;
};
readonly testHooks?: {
readonly onDeferredFinalizeScheduled?: (debounce: Duration.Input) => Effect.Effect<void>;
/** `cancelAfterPromptStarts`: Stop is holding `session/cancel` until the prompt starts. */
readonly onCancelHeld?: () => Effect.Effect<void>;
readonly afterPromptWireSettled?: () => Effect.Effect<void>;
readonly afterPromptSettledWithBackgroundWork?: () => Effect.Effect<void>;
readonly onNativeResponseLifecycle?: (event: {
readonly generation?: number;
readonly requestId?: string;
readonly type:
| "admission_rejected"
| "failed"
| "late_noop"
| "registered"
| "removed"
| "timer_exited"
| "timer_started"
| "watcher_exited"
| "watcher_started";
}) => Effect.Effect<void>;
};
}
export const AcpProviderCapabilitiesV2 = {
sessions: {
supportsMultipleProviderThreadsPerSession: false,
supportsModelSwitchInSession: false,
supportsProviderSwitchingViaHandoff: true,
supportsRuntimeModeSwitchInSession: false,
pendingRequestsSurviveRestart: false,
},
threads: {
canCreateEmptyThread: true,
canReadThreadSnapshot: false,
canRollbackThread: true,
canForkThread: false,
canForkFromTurn: false,
canForkFromSubagentThread: false,
exposesNativeThreadId: true,
},
turns: {
exposesNativeTurnId: false,
emitsTurnStarted: true,
emitsTurnCompleted: true,
supportsInterrupt: true,
supportsActiveSteering: false,
supportsSteeringByInterruptRestart: true,
supportsQueuedMessages: true,
terminalStatusQuality: "strong",
},
streaming: {
streamsAssistantText: true,
streamsReasoning: true,
streamsToolOutput: true,
streamsPlanText: false,
emitsMessageCompleted: true,
},
tools: {
exposesToolItemIds: true,
emitsToolStarted: true,
emitsToolCompleted: true,
emitsToolOutput: true,
supportsMcpTools: false,
supportsDynamicToolCallbacks: false,
},
approvals: {
supportsCommandApproval: true,
supportsFileReadApproval: true,
supportsFileChangeApproval: true,
supportsApplyPatchApproval: false,
approvalsHaveNativeRequestIds: false,
approvalCallbacksAreLiveOnly: true,
approvalsCanOriginateFromSubagents: false,
},
planning: {
emitsPlanUpdated: true,
emitsTodoList: true,
emitsProposedPlan: false,
supportsStructuredQuestions: true,
planDeltasHaveItemIds: false,
},
subagents: {
supportsSubagents: false,
exposesSubagentThreadIds: false,
emitsSubagentLifecycle: false,
canWaitForSubagents: false,
canCloseSubagents: false,
canForkSubagentThread: false,
},
context: {
acceptsSystemContext: false,
acceptsDeveloperContext: false,
acceptsSyntheticUserContext: true,
canGenerateSummaries: true,
canConsumeHandoffSummaries: true,
supportsDeltaHandoff: true,
supportsFullThreadHandoff: true,
maxRecommendedHandoffChars: null,
},
checkpointing: {
appCanCheckpointFilesystem: true,
supportsNestedCheckpointScopes: true,
// ACP lacks truncation; rollback restores T3 checkpoints and starts a fresh agent session.
providerCanRollbackConversation: true,
providerRollbackReturnsSnapshot: true,
providerCanReadConversationSnapshot: false,
},
identity: {
nativeThreadIds: "strong",
nativeTurnIds: "weak",
nativeItemIds: "weak",
nativeRequestIds: "weak",
},
runtimePolicy: {
enforcement: "client-boundary",
},
} satisfies OrchestrationV2ProviderCapabilities;
const STEER_DELIVERY_BOUND = "2 seconds";
/**
* `session/fork` `_meta` for a fork from `providerTurnId`: none for the session head,
* the flavor's meta for a turn the agent named, or `null` when the agent can't fork there.
*/
function forkFromTurnMetaFor(input: {
readonly driver: ProviderDriverKind;
readonly flavor: Pick<AcpAdapterV2Flavor, "forkFromTurn">;
readonly canForkFromTurn: boolean;
readonly forkInput: ProviderAdapter.ProviderAdapterV2ForkThreadInput;
}): NonNullable<EffectAcpSchema.ForkSessionRequest["_meta"]> | undefined | null {
const { forkInput } = input;
if (forkInput.providerTurnId === undefined) return undefined;
const turns = (forkInput.sourceProviderTurns ?? []).filter(
(turn) => turn.providerThreadId === forkInput.sourceProviderThread.id,
);
const target = turns.find((turn) => turn.id === forkInput.providerTurnId);
if (target === undefined) return null;
if (turns.every((turn) => turn.ordinal <= target.ordinal)) return undefined;
const ref = target.nativeTurnRef;
if (
input.flavor.forkFromTurn === undefined ||
!input.canForkFromTurn ||
ref === null ||
ref.driver !== input.driver ||
ref.strength !== "strong" ||
ref.nativeId === null
) {
return null;
}
return input.flavor.forkFromTurn.forkMeta(ref.nativeId);
}
function isCompactionMessage(message: ProviderAdapter.ProviderAdapterV2TurnMessage): boolean {
return message.text.trim() === "/compact" && message.attachments.length === 0;
}
function negotiatedCapabilities(
base: OrchestrationV2ProviderCapabilities,
started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
modelOptionArrivesLate: boolean,
forksFromTurn: boolean,
): OrchestrationV2ProviderCapabilities {
const agent = started.initializeResult.agentCapabilities ?? {};
const session = agent.sessionCapabilities;
const setup = started.sessionSetupResult;
const canSwitchModel =
modelOptionArrivesLate ||
findModelConfigOption(setup.configOptions) !== undefined ||
setup.models != null;
const canLoad = agent.loadSession === true;
const canFork = session?.fork != null;
return {
...base,
sessions: {
...base.sessions,
supportsModelSwitchInSession: canSwitchModel,
},
threads: {
...base.threads,
canReadThreadSnapshot: canLoad,
canForkThread: canFork,
canForkFromTurn: canFork && forksFromTurn,
},
tools: {
...base.tools,
supportsMcpTools: true,
},
checkpointing: {
...base.checkpointing,
providerCanReadConversationSnapshot: canLoad,
},
};
}
interface AcpMcpContext {
readonly servers: ReadonlyArray<EffectAcpSchema.McpServer>;
readonly acpServers: ReadonlyArray<EffectAcpSchema.McpServer>;
readonly httpServers: ReadonlyArray<EffectAcpSchema.McpServer>;
readonly processEnvironment?: NodeJS.ProcessEnv;
readonly endpoint?: string;
readonly authorization?: string;
}
function acpMcpContext(
session: McpProviderSession.McpProviderSessionConfig | undefined,
self: SelfInvocation,
mcpOverHttp: boolean | undefined,
): AcpMcpContext {
if (session === undefined) {
return { servers: [], acpServers: [], httpServers: [] };
}
// codex-acp 1.2.0 and pi-acp drop injected HTTP servers, so HTTP is opt-in per flavor.
return {
servers: [
{
name: "t3-code",
command: self.command,
args: [...selfInvocationArgs(self, ["acp-mcp-bridge"])],
env: [
{ name: "ELECTRON_RUN_AS_NODE", value: "1" },
{ name: "T3_ACP_MCP_ENDPOINT", value: session.endpoint },
{ name: "T3_ACP_MCP_AUTHORIZATION", value: session.authorizationHeader },
],
},
],
acpServers: [{ type: "acp", name: "t3-code", serverId: "t3-code" }],
httpServers:
mcpOverHttp === true
? [
{
type: "http",
name: "t3-code",
url: session.endpoint,
headers: [{ name: "Authorization", value: session.authorizationHeader }],
},
]
: [],
endpoint: session.endpoint,
authorization: session.authorizationHeader,
processEnvironment: {
// The thread id every process the agent starts inherits, so a tool run
// from its shell can find its T3 thread. Claude and Codex sessions set
// the same variable (PortScanner.AGENT_THREAD_ENV; a string literal here
// because this package cannot reach apps/server).
T3CODE_THREAD_ID: session.threadId,
T3_ACP_MCP_ENDPOINT: session.endpoint,
T3_ACP_MCP_AUTHORIZATION: session.authorizationHeader,
T3_ACP_MCP_NODE: self.command,
...(self.entrypoint === undefined ? {} : { T3_ACP_MCP_ENTRYPOINT: self.entrypoint }),
},
};
}
function acpMcpActivation(context: AcpMcpContext) {
return {
mcpServers: context.servers,
acpMcpServers: context.acpServers,
httpMcpServers: context.httpServers,
};
}
function nativeThreadId(
driver: ProviderDriverKind,
thread: OrchestrationV2ProviderThread,
): Effect.Effect<string, ProviderAdapter.ProviderAdapterProtocolError> {
const id = thread.nativeThreadRef?.nativeId;
if (id === null || id === undefined || id.trim().length === 0) {
return Effect.fail(
new ProviderAdapter.ProviderAdapterProtocolError({
driver,
detail: `Provider thread ${thread.id} is missing its ACP session id`,
}),
);
}
return Effect.succeed(id);
}
function makeProviderThread(input: {
readonly driver: ProviderDriverKind;
readonly providerInstanceId: ProviderInstanceId;
readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"];
readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
readonly nativeThreadId: string;
readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"];
readonly forkedFrom?: OrchestrationV2ProviderThread["forkedFrom"];
readonly itemIdentityVersion?: 2;
readonly now: DateTime.Utc;
}): OrchestrationV2ProviderThread {
return {
id: input.idAllocator.derive.providerThread({
driver: input.driver,
providerInstanceId: input.providerInstanceId,
nativeThreadId: input.nativeThreadId,
}),
driver: input.driver,
providerInstanceId: input.providerInstanceId,
providerSessionId: input.providerSessionId,
appThreadId: input.appThreadId,
ownerNodeId: input.ownerNodeId ?? null,
nativeThreadRef: {
driver: input.driver,
nativeId: input.nativeThreadId,
strength: "strong",
},
nativeConversationHeadRef: null,
status: "idle",
firstRunOrdinal: null,
lastRunOrdinal: null,
handoffIds: [],
forkedFrom: input.forkedFrom ?? null,
contextUsage: null,
nativeMetadata:
input.itemIdentityVersion === undefined
? null
: { itemIdentityVersion: input.itemIdentityVersion },
createdAt: input.now,
updatedAt: input.now,
};
}
function acpMcpToolCallOutput(rawOutput: unknown): unknown {
const record = unknownRecord(rawOutput);
if (record === undefined) return rawOutput;
if (!("result" in record) && !("error" in record)) return rawOutput;
const result = unknownRecord(record.result);
const resultOutput = result === undefined ? undefined : mcpToolResultOutput(result);
const errorMessage = unknownRecord(record.error)?.message;
if (typeof errorMessage !== "string") {
return resultOutput ?? rawOutput;
}
return resultOutput === undefined
? { error: errorMessage }
: { error: errorMessage, result: resultOutput };
}
function nonEmptyText(value: unknown, fallback: string): string {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : fallback;
}
function decodeByteText(value: unknown): string | undefined {
if (!Array.isArray(value) || value.length === 0) return undefined;
if (!value.every((entry) => typeof entry === "number" && Number.isInteger(entry))) {
return undefined;
}
try {
const text = new TextDecoder().decode(Uint8Array.from(value as number[]));
return text.length > 0 ? text : undefined;
} catch {
return undefined;
}
}
function textFromUnknown(value: unknown): string | undefined {
if (typeof value === "string") {
return value;
}
const fromBytes = decodeByteText(value);
if (fromBytes !== undefined) {
return fromBytes;
}
if (Array.isArray(value)) {
const parts = value.flatMap((entry) => {
const text = textFromUnknown(entry);
return text === undefined || text.length === 0 ? [] : [text];
});
return parts.length === 0 ? undefined : parts.join("\n");
}