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

adapter.ts

641 lines25.2 KB

1import * as HostProcess from "@t3tools/shared/HostProcess";
2import { resolveSelfInvocation, type SelfInvocation } from "@t3tools/shared/nodeRuntime";
3import {
4 type ModelSelection,
5 ProviderDriverKind,
6 type OrchestrationV2ProviderCapabilities,
7} from "@t3tools/contracts";
8import { KiroSettings } from "../settings.ts";
9import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
10import type * as SecureRandom from "effect/crypto/SecureRandom";
11import * as Effect from "effect/Effect";
12import type * as FileSystem from "effect/FileSystem";
13import * as Option from "effect/Option";
14import type * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import type * as Scope from "effect/Scope";
17import * as Stream from "effect/Stream";
18import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19import type * as EffectAcpSchema from "effect-acp/compat";
20import * as EffectAcpErrors from "effect-acp/errors";
21​
22import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
23import {
24 AcpProviderCapabilitiesV2,
25 makeAcpAdapterV2,
26 type AcpAdapterV2Flavor,
27 type AcpAdapterV2RuntimeInput,
28 type AcpAdapterV2SubagentUpdate,
29} from "@t3tools/provider-acp/server/adapter";
30import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
31import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
32import {
33 ProviderAdapterDriverCreateError,
34 type ProviderAdapterDriver,
35 type ProviderAdapterDriverCreateInput,
36} from "@t3tools/provider-core/server/adapterDriver";
37import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
38import type * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
39import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
40import type * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
41import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
42import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
43import {
44 KIRO_AGENT_CONFIG_ID,
45 KIRO_AUTOPILOT_CONFIG_ID,
46 KIRO_EFFORT_CONFIG_ID,
47 KIRO_MODEL_CONFIG_ID,
48 kiroApprovalOptions,
49 kiroAutopilotValue,
50 kiroPermissionDisposition,
51 makeKiroAcpRuntime,
52} from "./acpSupport.ts";
53​
54export const KIRO_PROVIDER = ProviderDriverKind.make("kiro");
55/** T3's slug for "Kiro default", and Kiro's documented default model id. */
56const KIRO_DEFAULT_MODEL = "default";
57const KIRO_COMPACT_METHOD = "_kiro/session/compact";
58const KIRO_STEER_METHOD = "_session/steer";
59const KIRO_FALLBACK_DEFAULT_MODEL = "auto";
60const DEFAULT_KIRO_SETTINGS = Schema.decodeSync(KiroSettings)({});
61​
62const KiroProviderCapabilitiesV2 = {
63 ...AcpProviderCapabilitiesV2,
64 sessions: {
65 ...AcpProviderCapabilitiesV2.sessions,
66 supportsModelSwitchInSession: true,
67 },
68 // Kiro 2.27 and later fork at a turn's prompt (`_meta.kiro.messageId`); see kiroForkFromTurn.
69 threads: {
70 ...AcpProviderCapabilitiesV2.threads,
71 canForkThread: true,
72 canForkFromTurn: true,
73 },
74 // `_session/steer` waits for the running tool, then Kiro reads the message at its next step.
75 turns: {
76 ...AcpProviderCapabilitiesV2.turns,
77 supportsActiveSteering: true,
78 activeSteeringInterruptsTools: false,
79 // `_session/steer` takes a string, so a message with images restarts the turn.
80 activeSteeringAcceptsAttachments: false,
81 },
82 tools: {
83 ...AcpProviderCapabilitiesV2.tools,
84 supportsMcpTools: true,
85 },
86 subagents: {
87 ...AcpProviderCapabilitiesV2.subagents,
88 supportsSubagents: true,
89 emitsSubagentLifecycle: true,
90 },
91} satisfies OrchestrationV2ProviderCapabilities;
92​
93const KiroCompactResult = Schema.Struct({ success: Schema.Boolean });
94const decodeKiroCompactResult = Schema.decodeUnknownOption(KiroCompactResult);
95​
96/** Kiro answers a `/compact` prompt as chat, so T3 compacts with Kiro's own request. */
97const compactKiroSession = (
98 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
99 sessionId: string,
100) =>
101 runtime.request(KIRO_COMPACT_METHOD, { sessionId }).pipe(
102 Effect.flatMap((result) =>
103 Option.exists(decodeKiroCompactResult(result), (decoded) => decoded.success)
104 ? Effect.void
105 : Effect.fail(
106 new EffectAcpErrors.AcpRequestError({
107 code: -32603,
108 errorMessage: "Kiro could not compact the conversation.",
109 method: KIRO_COMPACT_METHOD,
110 data: result,
111 }),
112 ),
113 ),
114 );
115​
116const KiroSteerResult = Schema.Struct({ queued: Schema.Literal(true), messageId: Schema.String });
117const decodeKiroSteerResult = Schema.decodeUnknownOption(KiroSteerResult);
118const KiroSteeringInjected = Schema.Struct({
119 kiro: Schema.Struct({ kind: Schema.Literal("steering_injected"), messageId: Schema.String }),
120});
121const decodeKiroSteeringInjected = Schema.decodeUnknownOption(KiroSteeringInjected);
122​
123/** Kiro queues a steer, then reports `steering_injected` with its id once the model reads it. */
124const kiroSteering = {
125 send: (
126 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
127 sessionId: string,
128 text: string,
129 ) =>
130 runtime.request(KIRO_STEER_METHOD, { sessionId, message: text }).pipe(
131 Effect.flatMap((result) =>
132 Option.match(decodeKiroSteerResult(result), {
133 onSome: (decoded) => Effect.succeed(decoded.messageId),
134 onNone: () =>
135 Effect.fail(
136 new EffectAcpErrors.AcpRequestError({
137 code: -32603,
138 errorMessage: "Kiro did not queue the steering message.",
139 method: KIRO_STEER_METHOD,
140 data: result,
141 }),
142 ),
143 }),
144 ),
145 ),
146 injectedSteerId: (notification: EffectAcpSchema.SessionNotification) =>
147 notification.update.sessionUpdate === "session_info_update"
148 ? Option.getOrUndefined(decodeKiroSteeringInjected(notification.update._meta))?.kiro.messageId
149 : undefined,
150};
151​
152const decodeKiroForkCapability = Schema.decodeUnknownOption(
153 Schema.Struct({ kiro: Schema.Struct({ messageId: Schema.Literal(true) }) }),
154);
155const decodeKiroUserMessageId = Schema.decodeUnknownOption(
156 Schema.Struct({
157 kiro: Schema.Struct({
158 kind: Schema.Literal("user_message_id_assigned"),
159 userMessageId: Schema.String,
160 }),
161 }),
162);
163​
164/**
165 * Kiro assigns each prompt a `userMessageId`, and `session/fork` with that id keeps the
166 * session up to and including the reply to that prompt.
167 */
168const kiroForkFromTurn = {
169 supported: (
170 initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"],
171 ) =>
172 Option.isSome(
173 decodeKiroForkCapability(
174 initializeResult.agentCapabilities?.sessionCapabilities?.fork?._meta,
175 ),
176 ),
177 nativeTurnId: (notification: EffectAcpSchema.SessionNotification) =>
178 notification.update.sessionUpdate === "session_info_update"
179 ? Option.getOrUndefined(decodeKiroUserMessageId(notification.update._meta))?.kiro
180 .userMessageId
181 : undefined,
182 forkMeta: (messageId: string) => ({ kiro: { messageId } }),
183};
184​
185export interface KiroAdapterV2Options {
186 readonly instanceId: Parameters<typeof makeAcpAdapterV2>[0]["instanceId"];
187 readonly settings: KiroSettings;
188 readonly environment: NodeJS.ProcessEnv;
189 readonly selfInvocation: SelfInvocation;
190 readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
191 /**
192 * Kiro's id for "Kiro default" (the provider snapshot's `--list-models`
193 * default). Absent, it is `auto`.
194 */
195 readonly defaultModel?: Effect.Effect<string>;
196 /** Replaces the `kiro-cli` launch (replay tests). Kiro's session setup still applies. */
197 readonly makeRuntime?: (
198 input: AcpAdapterV2RuntimeInput,
199 ) => Effect.Effect<
200 AcpSessionRuntime.AcpSessionRuntime["Service"],
201 EffectAcpErrors.AcpError,
202 ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope
203 >;
204 readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
205 readonly testHooks?: Parameters<typeof makeAcpAdapterV2>[0]["testHooks"];
207​
208/** Kiro's `model` option once it advertises one. */
209const findKiroModelOption = (configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>) =>
210 configOptions.find((option) => option.id === KIRO_MODEL_CONFIG_ID || option.category === "model");
211​
212/**
213 * Kiro selects models only through its `model` config option; "default" is
214 * Kiro's own default. The write goes to `model` even before Kiro advertises it,
215 * and for unlisted ids: Kiro fails the next prompt on a model it can't use.
216 */
217const applyKiroModel = Effect.fn("KiroAdapterV2.applyKiroModel")(function* (
218 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
219 modelSelection: ModelSelection,
220 defaultModel: Effect.Effect<string>,
221 agentSwitched: boolean,
222) {
223 const modelOption = findKiroModelOption(yield* runtime.getConfigOptions);
224 const current = modelOption?.type === "select" ? modelOption.currentValue : undefined;
225 const selected = modelSelection.model.trim();
226 const isDefault = selected.length === 0 || selected === KIRO_DEFAULT_MODEL;
227 // Before Kiro advertises `model` the session is new, so it already runs
228 // Kiro's default, unless an agent switch just moved it to the agent's model.
229 if (isDefault && modelOption?.type !== "select" && !agentSwitched) {
230 return current;
231 }
232 const requested = isDefault ? yield* defaultModel : selected;
233 if (requested === current) {
234 return current;
235 }
236 yield* runtime.setConfigOption(modelOption?.id ?? KIRO_MODEL_CONFIG_ID, requested, {
237 allowUnlistedValue: true,
238 });
239 return requested;
240});
241​
242/**
243 * Bound on waiting for Kiro to advertise the model T3 just wrote. Kiro 2.27.0
244 * sent it 40-90 ms after the write's result.
245 */
246const KIRO_MODEL_ADVERT_BOUND = "2 seconds";
247​
248/**
249 * Writes the thread's effort to Kiro's `effortLevel` once Kiro advertises the
250 * written model, since Kiro ignores the option before then and resets it on a
251 * model change. Levels the model doesn't offer are not sent. A rejected write
252 * or no advert within the bound keeps Kiro's level rather than failing the turn.
253 */
254const applyKiroEffort = Effect.fn("KiroAdapterV2.applyKiroEffort")(function* (
255 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
256 modelSelection: ModelSelection,
257 appliedModel: string | undefined,
258) {
259 const requested = getModelSelectionStringOptionValue(modelSelection, "reasoningEffort");
260 if (requested === undefined) return;
261 const advertised = yield* runtime.configOptionChanges.pipe(
262 Stream.filter((configOptions) => {
263 const modelOption = findKiroModelOption(configOptions);
264 return (
265 appliedModel === undefined ||
266 (modelOption?.type === "select" && modelOption.currentValue === appliedModel)
267 );
268 }),
269 Stream.runHead,
270 Effect.timeoutOption(KIRO_MODEL_ADVERT_BOUND),
271 Effect.map(Option.flatten),
272 );
273 if (Option.isNone(advertised)) {
274 return yield* Effect.logWarning("Kiro did not advertise the model's reasoning effort", {
275 waitedForWrittenModel: appliedModel !== undefined,
276 });
277 }
278 const effortOption = advertised.value.find((option) => option.id === KIRO_EFFORT_CONFIG_ID);
279 if (effortOption?.type !== "select" || !selectValues(effortOption).includes(requested)) {
280 return;
281 }
282 yield* runtime.setConfigOption(KIRO_EFFORT_CONFIG_ID, requested).pipe(
283 Effect.catchTags({
284 // `requested` is one of the levels Kiro just advertised, so it is safe to log.
285 AcpRequestError: (error) =>
286 Effect.logWarning("Kiro rejected the reasoning effort", {
287 value: requested,
288 code: error.code,
289 }),
290 }),
291 );
292});
293​
294/**
295 * Selects the thread's Kiro agent and reports whether a switch went out. It runs
296 * before the model write, because switching applies the agent's own model. An
297 * agent the session doesn't list is skipped: Kiro would accept it and not switch.
298 */
299const applyKiroAgent = Effect.fn("KiroAdapterV2.applyKiroAgent")(function* (
300 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
301 modelSelection: ModelSelection,
302) {
303 const requested = getModelSelectionStringOptionValue(modelSelection, KIRO_AGENT_CONFIG_ID);
304 if (requested === undefined) return false;
305 const agentOption = (yield* runtime.getConfigOptions).find(
306 (option) => option.id === KIRO_AGENT_CONFIG_ID,
307 );
308 if (agentOption?.type !== "select" || agentOption.currentValue === requested) return false;
309 if (!selectValues(agentOption).includes(requested)) {
310 yield* Effect.logWarning("Kiro does not list the thread's agent", {
311 listedAgents: selectValues(agentOption).length,
312 });
313 return false;
314 }
315 yield* runtime.setConfigOption(KIRO_AGENT_CONFIG_ID, requested);
316 return true;
317});
318​
319const applyKiroModelSelection =
320 (defaultModel: Effect.Effect<string>): NonNullable<AcpAdapterV2Flavor["applyModelSelection"]> =>
321 ({ runtime, modelSelection }) =>
322 applyKiroAgent(runtime, modelSelection).pipe(
323 Effect.flatMap((agentSwitched) =>
324 applyKiroModel(runtime, modelSelection, defaultModel, agentSwitched),
325 ),
326 Effect.tap((appliedModel) => applyKiroEffort(runtime, modelSelection, appliedModel)),
327 );
328​
329function selectValues(
330 option: Extract<EffectAcpSchema.SessionConfigOption, { readonly type: "select" }>,
331): ReadonlyArray<string> {
332 return option.options.flatMap((entry) =>
333 "value" in entry ? [entry.value] : entry.options.map((choice) => choice.value),
334 );
336​
337const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);
338​
339/**
340 * Evidence that Kiro started the current prompt, so Stop's `session/cancel` is
341 * honored: a `turn_start` info update or output only a running prompt produces.
342 * Kiro doesn't promise `turn_start`, so Stop gives up after KIRO_CANCEL_HOLD_BOUND.
343 */
344function isKiroPromptActivity(update: EffectAcpSchema.SessionUpdate): boolean {
345 switch (update.sessionUpdate) {
346 case "agent_message_chunk":
347 case "agent_message":
348 case "agent_thought_chunk":
349 case "agent_thought":
350 case "tool_call":
351 case "tool_call_update":
352 case "tool_call_content_chunk":
353 case "plan_update":
354 return true;
355 case "session_info_update": {
356 const kiro = update._meta?.kiro;
357 return (
358 typeof kiro === "object" && kiro !== null && "kind" in kiro && kiro.kind === "turn_start"
359 );
360 }
361 default:
362 return false;
363 }
365​
366/** Past the 0-0.5 s window where TinBane saw cancels dropped, and the 1.5 s cancel they saw honored. */
367const KIRO_CANCEL_HOLD_BOUND = "2 seconds";
368​
369/**
370 * Kiro 2.31 fetches an Identity Center account's cloud config as a tool call
371 * of its own around session start (reported by @hstern), which can land inside
372 * the user's turn. Only the call carries this id; its updates name the call.
373 */
374const KIRO_CLOUD_CONFIG_TOOL_ID = "fetch_cloud_config";
375​
376/** Drops Kiro's cloud-config tool call and every update that follows it. */
377function makeKiroCloudConfigFilter() {
378 const running = new Set<string>();
379 return (notification: EffectAcpSchema.SessionNotification): boolean => {
380 const { update } = notification;
381 if (
382 update.sessionUpdate !== "tool_call" &&
383 update.sessionUpdate !== "tool_call_update" &&
384 update.sessionUpdate !== "tool_call_content_chunk"
385 ) {
386 return false;
387 }
388 const key = `${notification.sessionId}\n${update.toolCallId}`;
389 const kiro = update._meta?.kiro;
390 const toolId =
391 typeof kiro === "object" && kiro !== null && "toolId" in kiro ? kiro.toolId : null;
392 if (toolId === KIRO_CLOUD_CONFIG_TOOL_ID) running.add(key);
393 else if (!running.has(key)) return false;
394 if ("status" in update && (update.status === "completed" || update.status === "failed")) {
395 running.delete(key);
396 }
397 return true;
398 };
400​
401const KIRO_STEERING_NOTE = "[STEERING steer-";
402const decodeKiroSteeringInfo = Schema.decodeUnknownOption(
403 Schema.Struct({ kiro: Schema.Struct({ kind: Schema.String }) }),
404);
405​
406/** Length of the longest end of `text` that could still grow into the steering note. */
407function steeringNotePrefixLength(text: string): number {
408 for (let length = Math.min(text.length, KIRO_STEERING_NOTE.length - 1); length > 0; length -= 1) {
409 if (KIRO_STEERING_NOTE.startsWith(text.slice(-length))) return length;
410 }
411 return 0;
413​
414/**
415 * After an injected steer, Kiro's model ends its reply with a `[STEERING steer-…: …]`
416 * note meant for Kiro's own UI. This drops it from the streamed text, holding back a
417 * chunk end that may be the start of the note until the next chunk shows otherwise.
418 */
419function makeKiroSteeringNoteFilter() {
420 const sessions = new Map<string, { held: string; inNote: boolean }>();
421 return (
422 notification: EffectAcpSchema.SessionNotification,
423 ): EffectAcpSchema.SessionNotification => {
424 const { update } = notification;
425 if (update.sessionUpdate === "session_info_update") {
426 const kind = Option.getOrUndefined(decodeKiroSteeringInfo(update._meta))?.kiro.kind;
427 if (kind === "steering_injected") {
428 sessions.set(notification.sessionId, { held: "", inNote: false });
429 } else if (kind === "steering_cleared") sessions.delete(notification.sessionId);
430 return notification;
431 }
432 const state = sessions.get(notification.sessionId);
433 if (
434 state === undefined ||
435 update.sessionUpdate !== "agent_message_chunk" ||
436 update.content.type !== "text"
437 ) {
438 return notification;
439 }
440 let pending = state.held + update.content.text;
441 let visible = "";
442 state.held = "";
443 while (pending.length > 0) {
444 if (state.inNote) {
445 const end = pending.indexOf("]");
446 if (end < 0) break;
447 pending = pending.slice(end + 1);
448 state.inNote = false;
449 continue;
450 }
451 const start = pending.indexOf(KIRO_STEERING_NOTE);
452 if (start >= 0) {
453 visible += pending.slice(0, start).trimEnd();
454 pending = pending.slice(start + KIRO_STEERING_NOTE.length);
455 state.inNote = true;
456 continue;
457 }
458 const held = steeringNotePrefixLength(pending);
459 visible += pending.slice(0, pending.length - held);
460 state.held = pending.slice(pending.length - held);
461 break;
462 }
463 return {
464 ...notification,
465 update: { ...update, content: { ...update.content, text: visible } },
466 };
467 };
469​
470const decodeKiroAgentSubtask = Schema.decodeUnknownOption(
471 Schema.Struct({
472 kiro: Schema.Struct({ agentSubtaskId: Schema.String, kind: Schema.optionalKey(Schema.String) }),
473 }),
474);
475const decodeKiroSubagentInput = Schema.decodeUnknownOption(
476 Schema.Struct({ name: Schema.String, prompt: Schema.String }),
477);
478​
479/**
480 * Kiro runs sub-agents inside the parent's session: frames from an
481 * `invoke_sub_agent` call carry `_meta.kiro.agentSubtaskId`, and routing them
482 * to that id as their session gives the shared adapter the child to project.
483 */
484function normalizeKiroSessionUpdate(
485 notification: EffectAcpSchema.SessionNotification,
486): EffectAcpSchema.SessionNotification {
487 const { update } = notification;
488 const subtask = decodeKiroAgentSubtask("_meta" in update ? update._meta : undefined);
489 return Option.isSome(subtask) && subtask.value.kiro.kind !== "agent-subtask"
490 ? { ...notification, sessionId: subtask.value.kiro.agentSubtaskId }
491 : notification;
493​
494/** The `invoke_sub_agent` call; it completes with the sub-agent's final response. */
495function extractKiroSubagentUpdate(tool: AcpToolCallState): AcpAdapterV2SubagentUpdate | undefined {
496 const subtask = decodeKiroAgentSubtask(tool.data.meta);
497 if (Option.isNone(subtask) || subtask.value.kiro.kind !== "agent-subtask") return undefined;
498 const input = decodeKiroSubagentInput(tool.data.rawInput);
499 const status =
500 tool.status === "failed" ? "failed" : tool.status === "completed" ? "completed" : "running";
501 return {
502 nativeTaskId: tool.toolCallId,
503 childSessionId: subtask.value.kiro.agentSubtaskId,
504 prompt: Option.isSome(input) ? input.value.prompt : (tool.title ?? "Kiro sub-agent"),
505 title: Option.isSome(input) ? input.value.name : null,
506 model: null,
507 status,
508 result: typeof tool.data.rawOutput === "string" ? tool.data.rawOutput : null,
509 };
511​
512/**
513 * Kiro's prompt errors carry a message meant for the user (live 2.27: -32000
514 * "The model 'x' is not available. Please select a different model and try
515 * again. (Request ID: …)"). Show it instead of the generic failure text;
516 * makeProviderFailure bounds and redacts it.
517 */
518function kiroPromptFailure(cause: unknown) {
519 return makeProviderFailure({
520 cause,
521 ...(isAcpRequestError(cause) ? { message: cause.errorMessage, code: String(cause.code) } : {}),
522 class: "provider_error",
523 });
525​
526function makeKiroAcpAdapterFlavor(options: KiroAdapterV2Options): AcpAdapterV2Flavor {
527 const makeRuntime =
528 options.makeRuntime ??
529 ((input: AcpAdapterV2RuntimeInput) => {
530 const { runtimePolicy: _runtimePolicy, processEnvironment, ...runtimeInput } = input;
531 return makeKiroAcpRuntime({
532 ...runtimeInput,
533 settings: options.settings,
534 environment: { ...options.environment, ...processEnvironment },
535 });
536 });
537 const stripSteeringNote = makeKiroSteeringNoteFilter();
538 return {
539 driver: KIRO_PROVIDER,
540 runtimeHarness: "Kiro",
541 capabilities: KiroProviderCapabilitiesV2,
542 // Kiro V3 loads the user's hooks only when the client opts in. `v2` makes
543 // Kiro run them itself; `enabled` alone hands them to the client as
544 // `_kiro/hooks/*` requests, which T3 does not answer.
545 clientCapabilitiesMeta: { kiro: { hooks: { enabled: true, v2: true } } },
546 makeRuntime,
547 promptFailure: kiroPromptFailure,
548 ignoreSessionUpdate: makeKiroCloudConfigFilter(),
549 normalizeSessionUpdate: (notification) =>
550 stripSteeringNote(normalizeKiroSessionUpdate(notification)),
551 extractSubagentUpdate: extractKiroSubagentUpdate,
552 // See applyKiroModelSelection: `model` arrives after session/new.
553 modelOptionArrivesLate: true,
554 applyModelSelection: applyKiroModelSelection(
555 options.defaultModel ?? Effect.succeed(KIRO_FALLBACK_DEFAULT_MODEL),
556 ),
557 // The generic option loop runs after the model write, and an agent write
558 // there would put the agent's own model back.
559 ownedModelOptionIds: ["reasoningEffort", KIRO_AGENT_CONFIG_ID],
560 // With Autopilot off (Supervised) Kiro asks the user to accept a turn's
561 // changes before it ends. T3's runtime policy answers its per-tool prompts
562 // either way, and a runtime-mode change reopens the session to reapply it.
563 sessionConfigForPolicy: (policy) => [
564 { id: KIRO_AUTOPILOT_CONFIG_ID, value: kiroAutopilotValue(policy) },
565 ],
566 // See isKiroPromptActivity: Kiro 2.27.1 can drop a cancel sent just after
567 // `session/prompt` and run the turn to completion.
568 cancelAfterPromptStarts: { isStart: isKiroPromptActivity, bound: KIRO_CANCEL_HOLD_BOUND },
569 permissionDisposition: kiroPermissionDisposition,
570 approvalOptions: kiroApprovalOptions,
571 compactSession: compactKiroSession,
572 steering: kiroSteering,
573 forkFromTurn: kiroForkFromTurn,
574 // Kiro V3 advertises `promptCapabilities.image`; the shared adapter reads it.
575 ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
576 };
578​
579export const makeKiroAdapterV2 = Effect.fn("makeKiroAdapterV2")(function* (
580 options: KiroAdapterV2Options,
581) {
582 return yield* makeAcpAdapterV2({
583 instanceId: options.instanceId,
584 flavor: makeKiroAcpAdapterFlavor(options),
585 selfInvocation: options.selfInvocation,
586 ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
587 ...(options.testHooks === undefined ? {} : { testHooks: options.testHooks }),
588 });
589});
590​
591export type KiroAdapterV2DriverEnv =
592 | ChildProcessSpawner.ChildProcessSpawner
593 | SecureRandom.SecureRandom
594 | FileSystem.FileSystem
595 | IdAllocator.IdAllocatorV2
596 | Path.Path
597 | McpProviderSessions.McpProviderSessions
598 | ProviderEventLoggers.ProviderEventLoggers
599 | ProviderHost.ProviderHost;
600​
601/** `defaultModel` reads Kiro's id for "Kiro default" from the provider snapshot. */
602export const makeKiroAdapterV2Driver = (
603 defaultModel: Effect.Effect<string>,
604): ProviderAdapterDriver<KiroSettings, KiroAdapterV2DriverEnv> => ({
605 driverKind: KIRO_PROVIDER,
606 configSchema: KiroSettings,
607 defaultConfig: (): KiroSettings => DEFAULT_KIRO_SETTINGS,
608 create: Effect.fn("KiroAdapterV2Driver.create")(
609 function* (input: ProviderAdapterDriverCreateInput<KiroSettings>) {
610 const hostEnvironment = yield* HostProcess.Environment;
611 const selfInvocation = yield* resolveSelfInvocation();
612 const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
613 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
614 return yield* makeKiroAdapterV2({
615 instanceId: input.instanceId,
616 settings: { ...input.config, enabled: input.enabled },
617 environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
618 selfInvocation,
619 defaultModel,
620 nativeLogging: (threadId) =>
621 makeNativeLogger({
622 nativeEventLogger: providerEventLoggers.native,
623 provider: KIRO_PROVIDER,
624 threadId,
625 }),
626 });
627 },
628 (effect, input) =>
629 effect.pipe(
630 Effect.mapError(
631 (cause) =>
632 new ProviderAdapterDriverCreateError({
633 driver: KIRO_PROVIDER,
634 instanceId: input.instanceId,
635 detail: "Failed to create Kiro ACP adapter.",
636 cause,
637 }),
638 ),
639 ),
640 ),
641});