Open History to see the last commit
1import {
2 type ModelCapabilities,
3 ProviderDriverKind,
4 type ProviderOptionDescriptor,
5 type ServerProviderAuth,
6 type ServerProviderModel,
7} from "@t3tools/contracts";
8import type { KiroSettings } from "../settings.ts";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import { createModelCapabilities } from "@t3tools/shared/model";
11import { resolveSpawnCommand } from "@t3tools/shared/shell";
12import type * as SecureRandom from "effect/crypto/SecureRandom";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import * as Result from "effect/Result";
17import * as Schema from "effect/Schema";
18import { ChildProcess, type ChildProcessSpawner } from "effect/process";
19
20import {
21 KIRO_AGENT_CONFIG_ID,
22 KIRO_SUPPORTED_RUNTIME_MODES,
23 makeKiroAcpRuntime,
24} from "./acpSupport.ts";
25import {
26 AUTH_PROBE_TIMEOUT_MS,
27 buildServerProvider,
28 COMPACT_SLASH_COMMAND,
29 isCommandMissingCause,
30 parseCliVersionResult,
31 buildSelectOptionDescriptor,
32 type ProviderProbeResult,
33 providerModelsFromSettings,
34 type ServerProviderDraft,
35 providerProbeEnvironment,
36 spawnAndCollect,
37} from "@t3tools/provider-core/server/snapshotProbe";
38
39const KIRO_DRIVER_KIND = ProviderDriverKind.make("kiro");
40const KIRO_PRESENTATION = {
41 displayName: "Kiro",
42 showInteractionModeToggle: false,
43 supportedRuntimeModes: KIRO_SUPPORTED_RUNTIME_MODES,
44} as const;
45const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({ optionDescriptors: [] });
46const KIRO_DEFAULT_MODEL_SLUG = "default";
47const KIRO_FALLBACK_DEFAULT_MODEL = "auto";
48const KIRO_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
49 {
50 slug: KIRO_DEFAULT_MODEL_SLUG,
51 name: "Kiro default",
52 isCustom: false,
53 capabilities: EMPTY_CAPABILITIES,
54 },
55];
56const KIRO_API_KEY_ENV = "KIRO_API_KEY";
57const VERSION_PROBE_TIMEOUT_MS = 10_000;
58
59/**
60 * The agent picker is not a model trait, but the composer reads options per
61 * model, so every model, custom ones included, carries it.
62 */
63const kiroModels = (
64 settings: KiroSettings,
65 listed: ReadonlyArray<ServerProviderModel> = KIRO_BUILT_IN_MODELS,
66 agents?: ProviderOptionDescriptor,
67) =>
68 providerModelsFromSettings(listed, settings.customModels, EMPTY_CAPABILITIES).map((model) => {
69 const descriptors = model.capabilities?.optionDescriptors ?? [];
70 return agents === undefined || descriptors.some((descriptor) => descriptor.id === agents.id)
71 ? model
72 : {
73 ...model,
74 capabilities: createModelCapabilities({ optionDescriptors: [...descriptors, agents] }),
75 };
76 });
77
78const snapshot = (
79 settings: KiroSettings,
80 checkedAt: string,
81 probe: ProviderProbeResult,
82 listed?: ReadonlyArray<ServerProviderModel>,
83 agents?: ProviderOptionDescriptor,
84) =>
85 buildServerProvider({
86 // Gives the snapshot its version advisory; Kiro runs no enrichment pass.
87 driver: KIRO_DRIVER_KIND,
88 presentation: KIRO_PRESENTATION,
89 enabled: settings.enabled,
90 checkedAt,
91 models: kiroModels(settings, listed, agents),
92 // `/compact` runs `_kiro/session/compact`; see compactKiroSession.
93 slashCommands: [COMPACT_SLASH_COMMAND],
94 probe,
95 });
96
97export const buildInitialKiroProviderSnapshot = Effect.fn(
98 "KiroProvider.buildInitialKiroProviderSnapshot",
99)(function* (settings: KiroSettings): Effect.fn.Return<ServerProviderDraft> {
100 const now = yield* DateTime.now;
101 return snapshot(settings, DateTime.formatIso(now), {
102 installed: settings.enabled,
103 version: null,
104 status: "warning",
105 auth: { status: "unknown" },
106 message: settings.enabled
107 ? "Checking Kiro CLI availability..."
108 : "Kiro is disabled in T3 Code settings.",
109 });
110});
111
112const runKiroCli = Effect.fn("KiroProvider.runKiroCli")(function* (
113 settings: KiroSettings,
114 args: ReadonlyArray<string>,
115 environment: NodeJS.ProcessEnv,
116) {
117 const command = settings.binaryPath || "kiro-cli";
118 const spawnCommand = yield* resolveSpawnCommand(command, args, { env: environment });
119 return yield* spawnAndCollect(
120 command,
121 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
122 env: environment,
123 shell: spawnCommand.shell,
124 }),
125 );
126});
127
128const KiroWhoami = Schema.fromJsonString(
129 Schema.Struct({
130 accountType: Schema.optional(Schema.NullOr(Schema.String)),
131 email: Schema.optional(Schema.NullOr(Schema.String)),
132 }),
133);
134const decodeKiroWhoami = Schema.decodeUnknownOption(KiroWhoami);
135
136/**
137 * Reads `kiro-cli whoami --format json`: `{"account":null}` with exit 1 means
138 * signed out. Only the first line is decoded, since an Identity Center login
139 * follows it with a plain-text `Profile:` block.
140 */
141export function kiroAuthFromWhoami(
142 output: { readonly code: number; readonly stdout: string } | undefined,
143 environment: NodeJS.ProcessEnv,
144): ServerProviderAuth {
145 if (output === undefined) return { status: "unknown" };
146 if (output.code !== 0) {
147 return output.stdout.includes('"account":null')
148 ? { status: "unauthenticated" }
149 : { status: "unknown" };
150 }
151 const firstLine = output.stdout.trimStart().split("\n", 1)[0] ?? "";
152 const account = Option.getOrUndefined(decodeKiroWhoami(firstLine.trim()));
153 if (account?.accountType === "ApiKey" || environment[KIRO_API_KEY_ENV]?.trim()) {
154 return { status: "authenticated", type: "api_key", label: "Kiro API key" };
155 }
156 return {
157 status: "authenticated",
158 label: "Kiro account",
159 ...(account?.email ? { email: account.email } : {}),
160 };
161}
162
163const CLAUDE_EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"];
164const CLAUDE_4_6_EFFORT_LEVELS = ["low", "medium", "high", "max"];
165const GPT_5_6_EFFORT_LEVELS = ["none", ...CLAUDE_EFFORT_LEVELS];
166const KIMI_K3_EFFORT_LEVELS = ["low", "high", "max"];
167
168/**
169 * Reasoning levels per Kiro model id and its default level, copied from what
170 * Kiro 2.32.0 advertises, since `--list-models` names none. Unlisted models take
171 * no effort; the adapter sends only a level the live session offers.
172 */
173const KIRO_MODEL_EFFORT: Readonly<
174 Record<string, { readonly levels: ReadonlyArray<string>; readonly defaultLevel: string }>
175> = {
176 "claude-fable-5.1": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "high" },
177 "claude-opus-5.5": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "medium" },
178 "claude-opus-5": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "high" },
179 "claude-opus-4.8": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "high" },
180 "claude-opus-4.7": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "xhigh" },
181 "claude-opus-4.6": { levels: CLAUDE_4_6_EFFORT_LEVELS, defaultLevel: "high" },
182 "claude-sonnet-5.5": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "high" },
183 "claude-sonnet-5": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "high" },
184 "claude-sonnet-4.6": { levels: CLAUDE_4_6_EFFORT_LEVELS, defaultLevel: "high" },
185 "gpt-5.6-sol": { levels: GPT_5_6_EFFORT_LEVELS, defaultLevel: "high" },
186 "gpt-5.6-terra": { levels: GPT_5_6_EFFORT_LEVELS, defaultLevel: "high" },
187 "gpt-5.6-luna": { levels: GPT_5_6_EFFORT_LEVELS, defaultLevel: "high" },
188 "kimi-k3": { levels: KIMI_K3_EFFORT_LEVELS, defaultLevel: "max" },
189};
190const KIRO_EFFORT_LABELS: Readonly<Record<string, string>> = {
191 none: "None",
192 low: "Low",
193 medium: "Medium",
194 high: "High",
195 xhigh: "Extra High",
196 max: "Max",
197};
198
199function kiroModelCapabilities(modelId: string): ModelCapabilities {
200 const effort = KIRO_MODEL_EFFORT[modelId];
201 if (effort === undefined) return EMPTY_CAPABILITIES;
202 return createModelCapabilities({
203 optionDescriptors: [
204 buildSelectOptionDescriptor({
205 id: "reasoningEffort",
206 label: "Reasoning",
207 options: effort.levels.map((level) => ({
208 value: level,
209 label: KIRO_EFFORT_LABELS[level] ?? level,
210 isDefault: level === effort.defaultLevel,
211 })),
212 }),
213 ],
214 });
215}
216
217const KiroModelList = Schema.fromJsonString(
218 Schema.Struct({
219 models: Schema.Array(
220 Schema.Struct({
221 model_id: Schema.String,
222 model_name: Schema.optional(Schema.String),
223 }),
224 ),
225 default_model: Schema.optional(Schema.String),
226 }),
227);
228const decodeKiroModelList = Schema.decodeUnknownOption(KiroModelList);
229
230/**
231 * Reads `kiro-cli chat --list-models --format json`, the account's models. The
232 * default entry keeps its name but takes the "default" slug, with Kiro's id as its
233 * alias. Sessions advertise models only after they start; anything unparsable
234 * keeps the built-in list.
235 */
236function kiroModelsFromList(
237 output: { readonly code: number; readonly stdout: string } | undefined,
238): ReadonlyArray<ServerProviderModel> | undefined {
239 if (output === undefined || output.code !== 0) return undefined;
240 const list = Option.getOrUndefined(decodeKiroModelList(output.stdout.trim()));
241 if (list === undefined || list.models.length === 0) return undefined;
242 const defaultId = list.default_model ?? KIRO_FALLBACK_DEFAULT_MODEL;
243 const listedDefault = list.models.find((model) => model.model_id === defaultId);
244 const defaultModel: ServerProviderModel = {
245 slug: KIRO_DEFAULT_MODEL_SLUG,
246 // Named after the model it runs, so a named default isn't hidden behind "Kiro default".
247 name: listedDefault ? (listedDefault.model_name ?? listedDefault.model_id) : "Kiro default",
248 aliases: [defaultId],
249 isCustom: false,
250 isDefault: true,
251 // A new session on Kiro's default gets no model write, so Kiro never
252 // advertises its effort option and a level could not be applied.
253 capabilities: EMPTY_CAPABILITIES,
254 };
255 const models = list.models.map((model) =>
256 model === listedDefault
257 ? defaultModel
258 : {
259 slug: model.model_id,
260 name: model.model_name ?? model.model_id,
261 isCustom: false,
262 capabilities: kiroModelCapabilities(model.model_id),
263 },
264 );
265 // New threads select "default", so it is listed even when Kiro's list leaves its default out.
266 return models.includes(defaultModel) ? models : [defaultModel, ...models];
267}
268
269/**
270 * Kiro's own id for "Kiro default": the alias the model list gave it, else
271 * `auto`, Kiro's documented default.
272 */
273export function kiroDefaultModelId(models: ReadonlyArray<ServerProviderModel>): string {
274 return (
275 models.find((model) => model.slug === KIRO_DEFAULT_MODEL_SLUG)?.aliases?.[0] ??
276 KIRO_FALLBACK_DEFAULT_MODEL
277 );
278}
279
280const KiroConfigTemplate = Schema.Struct({
281 configOptions: Schema.Array(
282 Schema.Struct({
283 id: Schema.String,
284 type: Schema.String,
285 currentValue: Schema.optional(Schema.Unknown),
286 options: Schema.optional(
287 Schema.Array(
288 Schema.Struct({
289 value: Schema.String,
290 name: Schema.String,
291 description: Schema.optional(Schema.NullOr(Schema.String)),
292 }),
293 ),
294 ),
295 }),
296 ),
297});
298const decodeKiroConfigTemplate = Schema.decodeUnknownOption(KiroConfigTemplate);
299
300/**
301 * The thread's agent picker, from Kiro's `_kiro/config/template` result, without
302 * opening a session. The template reads no workspace, so a project's
303 * `.kiro/agents` are not offered.
304 */
305export function kiroAgentDescriptor(template: unknown): ProviderOptionDescriptor | undefined {
306 const decoded = Option.getOrUndefined(decodeKiroConfigTemplate(template));
307 const mode = decoded?.configOptions.find(
308 (option) => option.id === KIRO_AGENT_CONFIG_ID && option.type === "select",
309 );
310 const defaultAgent = typeof mode?.currentValue === "string" ? mode.currentValue : undefined;
311 const choices = (mode?.options ?? []).flatMap((choice) => {
312 const id = choice.value.trim();
313 const label = choice.name.trim() || id;
314 const description = choice.description?.trim();
315 return id.length === 0
316 ? []
317 : [
318 {
319 id,
320 label,
321 ...(description ? { description } : {}),
322 ...(id === defaultAgent ? { isDefault: true } : {}),
323 },
324 ];
325 });
326 // One agent is nothing to choose between.
327 if (choices.length < 2) return undefined;
328 return {
329 id: KIRO_AGENT_CONFIG_ID,
330 label: "Agent",
331 type: "select",
332 options: choices,
333 ...(defaultAgent !== undefined && choices.some((choice) => choice.isDefault)
334 ? { currentValue: defaultAgent }
335 : {}),
336 };
337}
338
339/**
340 * Asks Kiro for its agents with `initialize` and `_kiro/config/template` and
341 * nothing more: no `session/new`, so no MCP server starts and no session is
342 * stored. The process runs in the server's working directory.
343 */
344const probeKiroAgents = Effect.fn("KiroProvider.probeKiroAgents")(function* (
345 settings: KiroSettings,
346 environment: NodeJS.ProcessEnv,
347) {
348 const runtime = yield* makeKiroAcpRuntime({
349 settings,
350 environment,
351 cwd: yield* HostProcess.WorkingDirectory,
352 clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
353 });
354 yield* runtime.initialize();
355 return kiroAgentDescriptor(yield* runtime.request("_kiro/config/template", {}));
356}, Effect.scoped);
357
358export const checkKiroProviderStatus = Effect.fn("checkKiroProviderStatus")(function* (
359 settings: KiroSettings,
360 environment: NodeJS.ProcessEnv,
361): Effect.fn.Return<
362 ServerProviderDraft,
363 never,
364 ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom
365> {
366 const checkedAt = DateTime.formatIso(yield* DateTime.now);
367 if (!settings.enabled) {
368 return snapshot(settings, checkedAt, {
369 installed: false,
370 version: null,
371 status: "warning",
372 auth: { status: "unknown" },
373 message: "Kiro is disabled in T3 Code settings.",
374 });
375 }
376
377 const probeEnvironment = providerProbeEnvironment(environment);
378 const versionResult = yield* runKiroCli(settings, ["--version"], probeEnvironment).pipe(
379 Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
380 Effect.result,
381 );
382 if (Result.isFailure(versionResult) || Option.isNone(versionResult.success)) {
383 const missing = Result.isFailure(versionResult) && isCommandMissingCause(versionResult.failure);
384 return snapshot(settings, checkedAt, {
385 installed: !missing,
386 version: null,
387 status: "error",
388 auth: { status: "unknown" },
389 message: missing
390 ? "Kiro CLI (`kiro-cli`) is not installed or not on PATH."
391 : "Failed to run `kiro-cli --version`.",
392 });
393 }
394 const versionOutput = versionResult.success.value;
395 const version = parseCliVersionResult(versionOutput);
396 if (versionOutput.code !== 0) {
397 return snapshot(settings, checkedAt, {
398 installed: true,
399 version,
400 status: "error",
401 auth: { status: "unknown" },
402 message: "Kiro CLI is installed but failed to run.",
403 });
404 }
405
406 const whoamiResult = yield* runKiroCli(
407 settings,
408 ["whoami", "--format", "json"],
409 probeEnvironment,
410 ).pipe(Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS), Effect.result);
411 const auth = kiroAuthFromWhoami(
412 Result.isSuccess(whoamiResult) ? Option.getOrUndefined(whoamiResult.success) : undefined,
413 environment,
414 );
415 if (auth.status === "unauthenticated") {
416 return snapshot(settings, checkedAt, {
417 installed: true,
418 version,
419 status: "error",
420 auth,
421 message: "Kiro CLI is installed but not signed in. Run `kiro-cli login`.",
422 });
423 }
424 // Signed out, `--list-models` starts a browser login instead, and the agent
425 // probe fails to start, so both run only once `whoami` has confirmed the
426 // account. Without an agent list the composer shows no agent picker.
427 const [listed, agents] =
428 auth.status === "authenticated"
429 ? yield* Effect.all(
430 [
431 runKiroCli(
432 settings,
433 ["chat", "--list-models", "--format", "json"],
434 probeEnvironment,
435 ).pipe(
436 Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),
437 Effect.map((output) => kiroModelsFromList(Option.getOrUndefined(output))),
438 Effect.orElseSucceed(() => undefined),
439 ),
440 probeKiroAgents(settings, probeEnvironment).pipe(
441 Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),
442 Effect.map(Option.getOrUndefined),
443 Effect.orElseSucceed(() => undefined),
444 ),
445 ],
446 { concurrency: "unbounded" },
447 )
448 : [undefined, undefined];
449 return snapshot(
450 settings,
451 checkedAt,
452 {
453 installed: true,
454 version,
455 status: auth.status === "authenticated" ? "ready" : "warning",
456 auth,
457 ...(auth.status === "authenticated"
458 ? {}
459 : { message: "Could not confirm the Kiro sign-in. Run `kiro-cli whoami` to check." }),
460 },
461 listed,
462 agents,
463 );
464});