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

status.ts

458 lines16.1 KB

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