Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, describe, it } from "@effect/vitest";
4import { KiroSettings } from "@t3tools/provider-kiro/settings";
5import * as Deferred from "effect/Deferred";
6import type * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Layer from "effect/Layer";
10import * as Queue from "effect/Queue";
11import * as Schema from "effect/Schema";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14import { ChildProcess, ChildProcessSpawner } from "effect/process";
15import * as TestClock from "effect/testing/TestClock";
16
17import {
18 checkKiroProviderStatus,
19 kiroAgentDescriptor,
20 kiroDefaultModelId,
21} from "@t3tools/provider-kiro/testing";
22
23const encoder = new TextEncoder();
24const settings = Schema.decodeSync(KiroSettings)({ enabled: true });
25
26interface CliOutput {
27 readonly stdout: string;
28 readonly code: number;
29 /** Holds stdout and the exit back this long, like a CLI slow to answer. */
30 readonly delay?: Duration.Input;
31}
32
33function processHandle(output: CliOutput) {
34 const answered = Effect.sleep(output.delay ?? 0);
35 return ChildProcessSpawner.makeHandle({
36 pid: ChildProcessSpawner.ProcessId(900_000_002),
37 exitCode: Effect.as(answered, ChildProcessSpawner.ExitCode(output.code)),
38 exitStatus: Effect.as(answered, {
39 _tag: "Exited",
40 code: ChildProcessSpawner.ExitCode(output.code),
41 }),
42 isRunning: Effect.succeed(false),
43 kill: () => Effect.void,
44 unref: Effect.succeed(Effect.void),
45 stdin: Sink.drain,
46 stdout: Stream.unwrap(
47 Effect.as(
48 answered,
49 output.stdout.length === 0 ? Stream.empty : Stream.succeed(encoder.encode(output.stdout)),
50 ),
51 ),
52 stderr: Stream.empty,
53 all: Stream.empty,
54 getInputFd: () => Sink.drain,
55 getOutputFd: () => Stream.empty,
56 });
57}
58
59const KIRO_ACP_ARGS = "acp --agent-engine=v3 --auth-method=cli";
60const decodeRequest = Schema.decodeUnknownSync(
61 Schema.fromJsonString(
62 Schema.Struct({ id: Schema.Union([Schema.String, Schema.Number]), method: Schema.String }),
63 ),
64);
65
66/**
67 * A `kiro-cli acp` that answers `initialize` and `_kiro/config/template` and
68 * fails anything else, so a probe that opened a session would fail.
69 */
70const acpProcess = (template: unknown) =>
71 Effect.gen(function* () {
72 const output = yield* Queue.unbounded<Uint8Array>();
73 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
74 const terminate = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
75 Effect.andThen(Queue.shutdown(output)),
76 Effect.asVoid,
77 );
78 const reply = (line: string) => {
79 const request = decodeRequest(line);
80 const response =
81 request.method === "initialize"
82 ? { result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] } }
83 : request.method === "_kiro/config/template"
84 ? { result: template }
85 : { error: { code: -32601, message: `${request.method} is not scripted` } };
86 return Queue.offer(
87 output,
88 encoder.encode(`${JSON.stringify({ jsonrpc: "2.0", id: request.id, ...response })}\n`),
89 );
90 };
91 return ChildProcessSpawner.makeHandle({
92 pid: ChildProcessSpawner.ProcessId(900_000_003),
93 exitCode: Deferred.await(exited),
94 exitStatus: Effect.map(Deferred.await(exited), (code) => ({ _tag: "Exited", code })),
95 isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
96 kill: () => terminate,
97 unref: Effect.succeed(Effect.void),
98 stdin: Sink.forEach((bytes: Uint8Array) =>
99 Effect.forEach(
100 new TextDecoder()
101 .decode(bytes)
102 .split("\n")
103 .filter((line) => line.trim().length > 0),
104 reply,
105 ),
106 ),
107 stdout: Stream.fromQueue(output),
108 stderr: Stream.empty,
109 all: Stream.empty,
110 getInputFd: () => Sink.drain,
111 getOutputFd: () => Stream.empty,
112 });
113 });
114
115/** Answers `kiro-cli` invocations by their arguments and records which ran. */
116function kiroCli(outputs: Record<string, CliOutput>, template?: unknown) {
117 const invoked: Array<string> = [];
118 const spawner = ChildProcessSpawner.make((command) => {
119 const args = ChildProcess.isStandardCommand(command) ? command.args.join(" ") : "";
120 invoked.push(args);
121 return args === KIRO_ACP_ARGS && template !== undefined
122 ? acpProcess(template)
123 : Effect.succeed(processHandle(outputs[args] ?? { stdout: "", code: 127 }));
124 });
125 return { invoked, spawner };
126}
127
128const check = (
129 outputs: Record<string, CliOutput>,
130 options: { readonly template?: unknown; readonly settings?: KiroSettings } = {},
131) =>
132 Effect.gen(function* () {
133 const cli = kiroCli(outputs, options.template);
134 const snapshot = yield* checkKiroProviderStatus(options.settings ?? settings, {}).pipe(
135 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, cli.spawner),
136 );
137 return { snapshot, invoked: cli.invoked };
138 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
139
140describe("KiroProvider", () => {
141 it.effect.each([
142 {
143 label: "answers after 6 s",
144 delay: "6 seconds",
145 status: "ready",
146 version: "2.27.0",
147 message: undefined,
148 },
149 {
150 label: "never answers",
151 delay: "Infinity",
152 status: "error",
153 version: null,
154 message: "Failed to run `kiro-cli --version`.",
155 },
156 ] as const)("gives `kiro-cli --version` 10 s when it $label", (row) =>
157 Effect.gen(function* () {
158 const fiber = yield* check({
159 "--version": { stdout: "kiro-cli 2.27.0\n", code: 0, delay: row.delay },
160 "whoami --format json": { stdout: '{"accountType":"ApiKey","email":null}\n', code: 0 },
161 }).pipe(Effect.forkChild);
162 yield* TestClock.adjust("10 seconds");
163 const { snapshot } = yield* Fiber.join(fiber);
164 assert.equal(snapshot.status, row.status);
165 assert.equal(snapshot.version, row.version);
166 assert.equal(snapshot.message, row.message);
167 }),
168 );
169
170 it.effect("reports a CLI whose version probe exits nonzero as failing to run", () =>
171 Effect.gen(function* () {
172 const { snapshot, invoked } = yield* check({
173 "--version": { stdout: "kiro-cli 2.27.0\n", code: 1 },
174 });
175 assert.equal(snapshot.status, "error");
176 assert.isTrue(snapshot.installed);
177 assert.equal(snapshot.message, "Kiro CLI is installed but failed to run.");
178 // A broken CLI is not asked for its sign-in.
179 assert.deepEqual(invoked, ["--version"]);
180 }),
181 );
182
183 // `whoami` outputs recorded from Kiro CLI 2.27.0.
184 it.effect("asks for kiro-cli login when Kiro is signed out", () =>
185 Effect.gen(function* () {
186 const { snapshot } = yield* check({
187 "--version": { stdout: "kiro-cli 2.27.0\n", code: 0 },
188 "whoami --format json": { stdout: '{"account":null}\n', code: 1 },
189 });
190 assert.equal(snapshot.status, "error");
191 assert.equal(snapshot.version, "2.27.0");
192 assert.equal(snapshot.auth.status, "unauthenticated");
193 assert.include(snapshot.message ?? "", "kiro-cli login");
194 }),
195 );
196
197 it.effect("is ready once Kiro reports a signed-in account", () =>
198 Effect.gen(function* () {
199 const { snapshot } = yield* check({
200 "--version": { stdout: "kiro-cli 2.27.0\n", code: 0 },
201 "whoami --format json": { stdout: '{"accountType":"ApiKey","email":null}\n', code: 0 },
202 });
203 assert.equal(snapshot.status, "ready");
204 assert.equal(snapshot.auth.status, "authenticated");
205 // The version advisory is what the compatibility check and update UI read.
206 assert.equal(snapshot.versionAdvisory?.currentVersion, "2.27.0");
207 assert.isFalse(snapshot.versionAdvisory?.canUpdate);
208 }),
209 );
210
211 // Shape of `kiro-cli chat --list-models --format json` on Kiro CLI 2.27.0, trimmed to three models.
212 const KIRO_MODEL_LIST = JSON.stringify({
213 models: [
214 { model_name: "auto", model_id: "auto", description: "Models chosen by task" },
215 { model_name: "claude-sonnet-4.5", model_id: "claude-sonnet-4.5" },
216 { model_name: "claude-haiku-4.5", model_id: "claude-haiku-4.5" },
217 ],
218 default_model: "auto",
219 });
220
221 it.effect("lists the signed-in account's models with auto as the Kiro default", () =>
222 Effect.gen(function* () {
223 const { snapshot } = yield* check({
224 "--version": { stdout: "kiro-cli 2.27.0\n", code: 0 },
225 "whoami --format json": { stdout: '{"accountType":"SocialGitHub"}\n', code: 0 },
226 "chat --list-models --format json": { stdout: `${KIRO_MODEL_LIST}\n`, code: 0 },
227 });
228 assert.deepEqual(
229 snapshot.models.map((model) => [model.slug, model.name, model.isDefault === true]),
230 [
231 ["default", "auto", true],
232 ["claude-sonnet-4.5", "claude-sonnet-4.5", false],
233 ["claude-haiku-4.5", "claude-haiku-4.5", false],
234 ],
235 );
236 }),
237 );
238
239 it.effect("names Kiro default after the model Kiro's list names as its default", () =>
240 Effect.gen(function* () {
241 const signedIn = {
242 "--version": { stdout: "kiro-cli 2.27.0\n", code: 0 },
243 "whoami --format json": { stdout: '{"accountType":"SocialGitHub"}\n', code: 0 },
244 };
245 const listed = yield* check({
246 ...signedIn,
247 "chat --list-models --format json": {
248 stdout: KIRO_MODEL_LIST.replace(
249 '"default_model":"auto"',
250 '"default_model":"claude-sonnet-4.5"',
251 ),
252 code: 0,
253 },
254 });
255 assert.deepEqual(
256 listed.snapshot.models.map((model) => [model.slug, model.name]),
257 [
258 ["auto", "auto"],
259 ["default", "claude-sonnet-4.5"],
260 ["claude-haiku-4.5", "claude-haiku-4.5"],
261 ],
262 );
263 assert.equal(kiroDefaultModelId(listed.snapshot.models), "claude-sonnet-4.5");
264 // An unparsable list keeps the built-in entry, which falls back to `auto`.
265 const unlisted = yield* check({
266 ...signedIn,
267 "chat --list-models --format json": { stdout: "not json\n", code: 0 },
268 });
269 assert.equal(unlisted.snapshot.models[0]?.name, "Kiro default");
270 assert.equal(kiroDefaultModelId(unlisted.snapshot.models), "auto");
271 }),
272 );
273
274 it.effect("lists Kiro default even when Kiro's model list leaves its default out", () =>
275 Effect.gen(function* () {
276 const { snapshot } = yield* check({
277 "--version": { stdout: "kiro-cli 2.27.0\n", code: 0 },
278 "whoami --format json": { stdout: '{"accountType":"SocialGitHub"}\n', code: 0 },
279 "chat --list-models --format json": {
280 stdout: JSON.stringify({ models: [{ model_id: "claude-sonnet-4.5" }] }),
281 code: 0,
282 },
283 });
284 assert.deepEqual(
285 snapshot.models.map((model) => [model.slug, model.name, model.isDefault === true]),
286 [
287 ["default", "Kiro default", true],
288 ["claude-sonnet-4.5", "claude-sonnet-4.5", false],
289 ],
290 );
291 assert.equal(kiroDefaultModelId(snapshot.models), "auto");
292 }),
293 );
294
295 // `--list-models` names no effort levels, so the picker's come from Kiro's ids.
296 const KIRO_EFFORT_MODEL_LIST = JSON.stringify({
297 models: [
298 "auto",
299 "claude-fable-5.1",
300 "claude-opus-5.5",
301 "claude-opus-4.6",
302 "kimi-k3",
303 "claude-sonnet-4.5",
304 ].map((id) => ({
305 model_name: id,
306 model_id: id,
307 })),
308 default_model: "auto",
309 });
310
311 it.effect("offers each model only the reasoning levels Kiro takes for it", () =>
312 Effect.gen(function* () {
313 const { snapshot } = yield* check({
314 "--version": { stdout: "kiro-cli 2.27.0\n", code: 0 },
315 "whoami --format json": { stdout: '{"accountType":"SocialGitHub"}\n', code: 0 },
316 "chat --list-models --format json": { stdout: KIRO_EFFORT_MODEL_LIST, code: 0 },
317 });
318 const reasoning = snapshot.models.map((model) => {
319 const descriptors = model.capabilities?.optionDescriptors ?? [];
320 const select = descriptors.find((descriptor) => descriptor.id === "reasoningEffort");
321 return select?.type === "select"
322 ? {
323 slug: model.slug,
324 label: select.label,
325 levels: select.options.map((choice) => choice.id),
326 defaults: select.options.filter((choice) => choice.isDefault).map((c) => c.id),
327 currentValue: select.currentValue,
328 }
329 : { slug: model.slug, descriptors: descriptors.length };
330 });
331 assert.deepEqual(reasoning, [
332 // Kiro default and models without effort get no Reasoning select.
333 { slug: "default", descriptors: 0 },
334 {
335 slug: "claude-fable-5.1",
336 label: "Reasoning",
337 levels: ["low", "medium", "high", "xhigh", "max"],
338 defaults: ["high"],
339 currentValue: "high",
340 },
341 {
342 slug: "claude-opus-5.5",
343 label: "Reasoning",
344 levels: ["low", "medium", "high", "xhigh", "max"],
345 defaults: ["medium"],
346 currentValue: "medium",
347 },
348 // Opus 4.6 has no xhigh, and Kiro runs it at high by default.
349 {
350 slug: "claude-opus-4.6",
351 label: "Reasoning",
352 levels: ["low", "medium", "high", "max"],
353 defaults: ["high"],
354 currentValue: "high",
355 },
356 // Kimi K3 skips medium and runs at max by default.
357 {
358 slug: "kimi-k3",
359 label: "Reasoning",
360 levels: ["low", "high", "max"],
361 defaults: ["max"],
362 currentValue: "max",
363 },
364 { slug: "claude-sonnet-4.5", descriptors: 0 },
365 ]);
366 }),
367 );
368
369 it.effect("gives every model, custom ones too, the agent picker Kiro's template lists", () =>
370 Effect.gen(function* () {
371 const { snapshot } = yield* check(
372 {
373 "--version": { stdout: "kiro-cli 2.27.0\n", code: 0 },
374 "whoami --format json": { stdout: '{"accountType":"SocialGitHub"}\n', code: 0 },
375 "chat --list-models --format json": { stdout: KIRO_MODEL_LIST, code: 0 },
376 },
377 {
378 template: {
379 configOptions: [
380 {
381 type: "select",
382 id: "mode",
383 name: "Mode",
384 currentValue: "vibe",
385 options: [
386 { value: "vibe", name: "Default" },
387 { value: "reviewer", name: "reviewer" },
388 ],
389 },
390 ],
391 },
392 settings: { ...settings, customModels: ["my-model"] },
393 },
394 );
395 assert.deepEqual(
396 snapshot.models.map((model) => [
397 model.slug,
398 model.capabilities?.optionDescriptors?.flatMap((descriptor) =>
399 descriptor.type === "select" && descriptor.id === "mode"
400 ? descriptor.options.map((choice) => choice.id)
401 : [],
402 ),
403 ]),
404 [
405 ["default", ["vibe", "reviewer"]],
406 ["claude-sonnet-4.5", ["vibe", "reviewer"]],
407 ["claude-haiku-4.5", ["vibe", "reviewer"]],
408 ["my-model", ["vibe", "reviewer"]],
409 ],
410 );
411 }),
412 );
413
414 it("offers Kiro's agents from its config template, Default first", () => {
415 // `_kiro/config/template` from kiro-cli 2.27.0 with two user agents in
416 // `~/.kiro/agents`, trimmed to three bundled agents and the `mode` option.
417 const template = {
418 modes: { currentModeId: "vibe", availableModes: [] },
419 configOptions: [
420 {
421 type: "select",
422 id: "mode",
423 name: "Mode",
424 category: "mode",
425 currentValue: "vibe",
426 options: [
427 { value: "vibe", name: "Default", description: "General coding assistance" },
428 { value: "spec", name: "Spec", description: "Structured feature development" },
429 { value: "plan", name: "Plan", description: "Plan-only mode" },
430 { value: "global-probe", name: "global-probe", description: "Global probe agent" },
431 { value: "planner", name: "planner", description: null },
432 ],
433 },
434 {
435 type: "select",
436 id: "autopilot",
437 name: "Autopilot",
438 currentValue: "on",
439 options: [{ value: "on", name: "Autopilot" }],
440 },
441 ],
442 };
443 const descriptor = kiroAgentDescriptor(template);
444 assert.deepEqual(descriptor, {
445 id: "mode",
446 label: "Agent",
447 type: "select",
448 currentValue: "vibe",
449 options: [
450 { id: "vibe", label: "Default", description: "General coding assistance", isDefault: true },
451 { id: "spec", label: "Spec", description: "Structured feature development" },
452 { id: "plan", label: "Plan", description: "Plan-only mode" },
453 { id: "global-probe", label: "global-probe", description: "Global probe agent" },
454 { id: "planner", label: "planner" },
455 ],
456 });
457 // The default follows the agent Kiro starts sessions on.
458 const onSpec = kiroAgentDescriptor({
459 configOptions: [{ ...template.configOptions[0], currentValue: "spec" }],
460 });
461 assert.equal(onSpec?.type === "select" ? onSpec.currentValue : undefined, "spec");
462 assert.deepEqual(
463 onSpec?.type === "select" ? onSpec.options.filter((choice) => choice.isDefault) : [],
464 [
465 {
466 id: "spec",
467 label: "Spec",
468 description: "Structured feature development",
469 isDefault: true,
470 },
471 ],
472 );
473 // A template without agents to choose between gives no picker.
474 assert.isUndefined(kiroAgentDescriptor({ configOptions: [] }));
475 assert.isUndefined(kiroAgentDescriptor("not a template"));
476 });
477
478 it.effect("never lists models while signed out, where listing would start a browser login", () =>
479 Effect.gen(function* () {
480 const { snapshot, invoked } = yield* check({
481 "--version": { stdout: "kiro-cli 2.27.0\n", code: 0 },
482 "whoami --format json": { stdout: '{"account":null}\n', code: 1 },
483 "chat --list-models --format json": { stdout: `${KIRO_MODEL_LIST}\n`, code: 0 },
484 });
485 assert.notInclude(invoked, "chat --list-models --format json");
486 assert.deepEqual(
487 snapshot.models.map((model) => model.slug),
488 ["default"],
489 );
490 }),
491 );
492});