Repository navigation
Expand file tree
/
Copy pathcli.test.ts
More file actions
549 lines (473 loc) · 21.6 KB
/
Copy pathcli.test.ts
File metadata and controls
549 lines (473 loc) · 21.6 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
/* @effect-diagnostics nodeBuiltinImport:off -- this suite spawns the CLI as a child process. */
/* @effect-diagnostics cryptoRandomUUID:off -- fixtures only need a distinct temp path. */
import { spawnSync } from "node:child_process";
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { DatabaseSync } from "node:sqlite";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it, onTestFinished } from "vite-plus/test";
import { runCli, serveCli, streaming, toolCalls, truncating, writeSettings } from "./fixtures/cli.ts";
const cli = fileURLToPath(new URL("../src/index.ts", import.meta.url));
const models = fileURLToPath(new URL("../../../models.gen.json", import.meta.url));
/**
* The CLI discovers project settings from the directory it runs in, and searches upward, so a
* child spawned in this repository would read the repository's own file. Every spawn below runs
* in a temp directory instead, which is what "isolated" has to mean once discovery walks up.
*/
const run = (...args: ReadonlyArray<string>) => {
const cwd = mkdtempSync(join(tmpdir(), "codework-cli-cwd-"));
try {
return spawnSync(process.execPath, ["--conditions=development", cli, ...args], { encoding: "utf8", cwd });
} finally {
rmSync(cwd, { recursive: true, force: true });
}
};
const runIsolated = (env: NodeJS.ProcessEnv, ...args: ReadonlyArray<string>) => {
const home = mkdtempSync(join(tmpdir(), "codework-cli-"));
try {
return runIn(home, env, ...args);
} finally {
rmSync(home, { recursive: true, force: true });
}
};
/** `runIsolated` against a home the caller owns, for commands whose effect outlives one spawn. */
const runIn = (home: string, env: NodeJS.ProcessEnv, ...args: ReadonlyArray<string>) => {
{
// HOME too: provider SDKs cache credentials under it (e.g. Vercel's OIDC
// token in ~/Library/Application Support), so "isolated" must hide them.
// The catalog is pinned to the workspace's unless a case says otherwise, so no
// spawn downloads one into its throwaway home.
const childEnv: NodeJS.ProcessEnv = { ...process.env, HOME: home, CODEWORK_MODELS_FILE: models, ...env };
for (const [key, value] of Object.entries(env)) {
if (value === undefined) delete childEnv[key];
}
return spawnSync(
process.execPath,
["--conditions=development", cli, "--home", home, "--database", ":memory:", ...args],
{
encoding: "utf8",
env: childEnv,
cwd: home,
timeout: 20_000,
},
);
}
};
/** A catalog file that is not JSON. */
const invalidCatalog = () => {
const path = join(tmpdir(), `invalid-models-${crypto.randomUUID()}.json`);
writeFileSync(path, "{");
return path;
};
describe("codework CLI", () => {
it("reads custom settings from --user-config-dir without requiring model flags", () => {
const dir = mkdtempSync(join(tmpdir(), "codework-cli-settings-"));
try {
writeFileSync(
join(dir, "settings.jsonc"),
JSON.stringify({ model: { provider: "settings-test-provider", id: "settings-test-model" } }),
);
const result = runIsolated({ CODEWORK_MODELS_FILE: models }, "--user-config-dir", dir, "run", "test");
expect(result.status).toBe(1);
expect(result.stderr).toContain("settings-test-provider");
expect(result.stderr).toContain("settings-test-model");
expect(result.stderr).toContain("error[model-not-found-error]");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("rereads --user-config-dir settings on every invocation, including a revert", () => {
const dir = mkdtempSync(join(tmpdir(), "codework-cli-settings-cycle-"));
const write = (settings: object) => writeFileSync(join(dir, "settings.jsonc"), JSON.stringify(settings));
const select = (stderr: string) => [/provider[^a-z0-9]+([a-z0-9-]+)/i.exec(stderr)?.[1] ?? "", stderr];
try {
// A: a selection plus a key that only A carries.
write({ model: { provider: "cycle-a-provider", id: "cycle-a-model", options: { maxRetries: 7 } } });
const first = runIsolated({ CODEWORK_MODELS_FILE: models }, "--user-config-dir", dir, "run", "test");
expect(first.stderr).toContain("cycle-a-provider");
expect(first.stderr).toContain("cycle-a-model");
// B: a different selection, and A's extra key is absent from the file.
write({ model: { provider: "cycle-b-provider", id: "cycle-b-model" } });
const second = runIsolated({ CODEWORK_MODELS_FILE: models }, "--user-config-dir", dir, "run", "test");
expect(second.stderr).toContain("cycle-b-provider");
expect(second.stderr).toContain("cycle-b-model");
expect(second.stderr).not.toContain("cycle-a-model");
// Back to A: the earlier selection returns rather than sticking on B.
write({ model: { provider: "cycle-a-provider", id: "cycle-a-model", options: { maxRetries: 7 } } });
const third = runIsolated({ CODEWORK_MODELS_FILE: models }, "--user-config-dir", dir, "run", "test");
expect(third.stderr).toContain("cycle-a-provider");
expect(third.stderr).toContain("cycle-a-model");
expect(third.stderr).not.toContain("cycle-b-model");
expect(select(third.stderr)[0]).toBe(select(first.stderr)[0]);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("documents local as the default and exposes remote sandbox flags", () => {
const result = run("run", "--help");
expect(result.status).toBe(0);
expect(result.stdout).toContain("--sandbox-driver string");
expect(result.stdout).toContain("default: local");
expect(result.stdout).toContain("Sandbox driver for a new session");
expect(result.stdout).toContain("--sandbox-provider-id string");
});
it("validates sandbox names against the harness registry", () => {
const result = runIsolated({}, "run", "--sandbox-driver", "missing", "test");
expect(result.status).toBe(1);
expect(result.stderr).toContain('sandbox driver "missing" is not registered');
expect(result.stderr).toContain("available: local, daytona, memory, sqldb, vercel");
});
it("requires a provider sandbox ID to name its driver", () => {
const result = run("run", "--sandbox-provider-id", "existing-id", "test");
expect(result.status).toBe(1);
expect(result.stderr).toBe("error: --sandbox-provider-id requires a remote --sandbox-driver\n");
});
it("reports an invalid model catalog without an Effect stack", () => {
const result = runIsolated(
{ CODEWORK_MODELS_FILE: invalidCatalog() },
"run",
"--provider",
"openrouter",
"--model",
"stealth/ox-alpha",
"test",
);
expect(result.status).toBe(1);
expect(result.stderr).toContain("error[model-catalog-invalid]: model catalog contains invalid json");
expect(result.stderr).toContain("hint: run `codework models refresh`");
expect(result.stderr).not.toContain("Runner.TurnError");
expect(result.stderr).not.toContain("at Loop.runTurn");
});
it("reports a missing provider API key with its taxonomy and remedy", () => {
const result = runIsolated(
{ CODEWORK_MODELS_FILE: models, OPENROUTER_API_KEY: undefined },
"run",
"--provider",
"openrouter",
"--model",
"z-ai/glm-5.3-flash",
"test",
);
expect(result.status).toBe(1);
expect(result.stderr).toContain("error[provider-authentication-error]");
expect(result.stderr).toContain("openrouter API key is missing");
expect(result.stderr).toContain("hint: set OPENROUTER_API_KEY and retry");
expect(result.stderr).not.toContain("Runner.TurnError");
expect(result.stderr).not.toContain("at Loop.runTurn");
expect(result.stderr).not.toContain("requestBodyValues");
expect(result.stderr).not.toContain("AI_LoadAPIKeyError");
});
it("reports the sanitized remote sandbox provider failure", () => {
const result = runIsolated({ VERCEL_OIDC_TOKEN: undefined }, "run", "--sandbox-driver", "vercel", "test");
expect(result.status).toBe(1);
expect(result.stderr).toContain("error: SandboxProviderError - Could not get credentials from OIDC context.");
expect(result.stderr).toContain("driver: vercel");
expect(result.stderr).toContain("operation: create");
expect(result.stderr).toContain("traceback:\nSandboxProviderError: The vercel sandbox failed to create:");
});
it("documents remote runs and rejects server-owned flags on the client", () => {
expect(run("run", "--help").stdout).toContain("--server");
const result = run("run", "--server", "ws://127.0.0.1:1/rpc/v1", "--database", ":memory:", "hello");
expect(result.status).toBe(1);
expect(result.stderr).toBe(
"error: --database and --user-config-dir belong on codework serve when using --server\n",
);
});
it("rejects out-of-range listening ports", () => {
const result = run("serve", "--port", "65536");
expect(result.status).toBe(1);
});
it("documents serve --host and --port", () => {
const result = run("serve", "--help");
expect(result.status).toBe(0);
expect(result.stdout).toContain("--host");
expect(result.stdout).toContain("--port");
});
it("documents models --provider and subcommands", () => {
const result = run("models", "--help");
expect(result.status).toBe(0);
expect(result.stdout).toContain("--provider");
expect(result.stdout).toContain("Model catalog provider ID");
expect(result.stdout).toContain("providers");
expect(result.stdout).toContain("refresh");
});
it("documents OAuth management as subcommands", () => {
const result = run("auth", "--help");
expect(result.status).toBe(0);
for (const command of ["login", "status", "refresh", "logout"]) {
expect(result.stdout).toContain(command);
}
const login = run("auth", "login", "--help");
expect(login.stdout).toContain("--openai-codex");
expect(login.stdout).toContain("--github-copilot");
expect(login.stdout).toContain("--device");
// Login-only options stay off the read commands.
const status = run("auth", "status", "--help");
expect(status.stdout).not.toContain("--device");
expect(status.stdout).not.toContain("--enable-models");
});
it("requires exactly one auth provider", () => {
expect(run("auth", "login").status).toBe(1);
expect(run("auth", "login", "--openai-codex", "--github-copilot").stderr).toContain(
"choose exactly one provider",
);
});
it("rejects Copilot-only flags on the Codex login", () => {
const result = run("auth", "login", "--openai-codex", "--enterprise", "github.acme.com");
expect(result.status).toBe(1);
expect(result.stderr).toContain("only apply to --github-copilot");
});
it("reads GitHub Copilot status without exposing the token", () => {
const dir = mkdtempSync(join(tmpdir(), "codework-auth-copilot-"));
const authFile = join(dir, "auth.json");
try {
writeFileSync(
authFile,
JSON.stringify({
"github-copilot": {
access: "ghu_secret",
refresh: "ghu_secret",
expires: 0,
apiEndpoint: "https://api.individual.githubcopilot.com",
availableModelIds: ["gpt-5.4", "claude-opus-5"],
},
}),
);
const result = run("auth", "status", "--github-copilot", "--auth-file", authFile);
expect(result.status).toBe(0);
expect(result.stdout).toContain("API endpoint: https://api.individual.githubcopilot.com");
expect(result.stdout).toContain("Available models: 2");
expect(result.stdout).toContain("Expires: never");
expect(result.stdout).not.toContain("ghu_secret");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("reads an expired login without refreshing it", () => {
const dir = mkdtempSync(join(tmpdir(), "codework-auth-expired-"));
const authFile = join(dir, "auth.json");
try {
writeFileSync(
authFile,
JSON.stringify({
"openai-codex": {
access: "stale-access",
refresh: "stale-refresh",
expires: 1,
accountId: "acct_stale",
},
}),
);
// --status is a read: it must not reach the network to renew this.
const result = run("auth", "status", "--openai-codex", "--auth-file", authFile);
expect(result.status).toBe(0);
expect(result.stdout).toContain("Account: acct_stale");
expect(result.stdout).not.toContain("stale-access");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("keeps --json stdout parseable", () => {
const dir = mkdtempSync(join(tmpdir(), "codework-auth-json-"));
const authFile = join(dir, "auth.json");
try {
writeFileSync(
authFile,
JSON.stringify({
"github-copilot": {
access: "ghu_secret",
refresh: "ghu_secret",
expires: 0,
apiEndpoint: "https://api.individual.githubcopilot.com",
},
}),
);
const result = run("auth", "status", "--github-copilot", "--json", "--auth-file", authFile);
expect(result.status).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
provider: "github-copilot",
apiEndpoint: "https://api.individual.githubcopilot.com",
});
expect(result.stdout).not.toContain("ghu_secret");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("offers a device-code login for Codex only", () => {
// Copilot has no other flow, so the flag would be meaningless there.
const result = run("auth", "login", "--github-copilot", "--device");
expect(result.status).toBe(1);
expect(result.stderr).toContain("always uses the device-code flow");
});
it("has no refresh path for GitHub Copilot", () => {
const result = run("auth", "refresh", "--github-copilot");
expect(result.status).toBe(1);
expect(result.stderr).toContain("do not expire");
});
it("reads OAuth status without exposing stored tokens", () => {
const dir = mkdtempSync(join(tmpdir(), "codework-auth-"));
const authFile = join(dir, "auth.json");
try {
writeFileSync(
authFile,
JSON.stringify({
"openai-codex": {
access: "access-secret",
refresh: "refresh-secret",
expires: 4_102_444_800_000,
accountId: "acct_cli",
},
}),
);
const result = run("auth", "status", "--openai-codex", "--auth-file", authFile);
expect(result.status).toBe(0);
expect(result.stdout).toContain("Account: acct_cli");
expect(result.stdout).not.toContain("access-secret");
expect(result.stdout).not.toContain("refresh-secret");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("reports the selected home when OAuth credentials are missing", () => {
const home = mkdtempSync(join(tmpdir(), "codework-auth-home-"));
try {
const result = run("--home", home, "auth", "status", "--openai-codex");
expect(result.status).toBe(1);
expect(result.stderr).toContain(`no OpenAI Codex credentials found at ${join(home, "aikit/auth.json")}`);
} finally {
rmSync(home, { recursive: true, force: true });
}
});
it("lists all models with models command", () => {
const result = runIsolated({ CODEWORK_MODELS_FILE: models }, "models");
expect(result.status).toBe(0);
expect(result.stdout).toContain("openai/gpt-4o\n");
expect(result.stdout).toContain("anthropic/claude-sonnet-5-5\n");
});
it("filters models by provider with models --provider", () => {
const result = runIsolated({ CODEWORK_MODELS_FILE: models }, "models", "--provider", "openai");
expect(result.status).toBe(0);
expect(result.stdout).toContain("openai/gpt-4o\n");
expect(result.stdout).not.toContain("anthropic/");
});
it("lists available model providers with models providers", () => {
const result = runIsolated({ CODEWORK_MODELS_FILE: models }, "models", "providers");
expect(result.status).toBe(0);
expect(result.stdout).toContain("openai\n");
expect(result.stdout).toContain("anthropic\n");
expect(result.stdout).toContain("openrouter\n");
});
it("rejects an unknown models --provider", () => {
const result = runIsolated({ CODEWORK_MODELS_FILE: models }, "models", "--provider", "not-a-provider");
expect(result.status).toBe(1);
expect(result.stderr).toContain('provider "not-a-provider" is not in the catalog');
expect(result.stderr).toContain("hint: run `codework models providers`");
});
it("reports an invalid model catalog from models without an Effect stack", () => {
const result = runIsolated({ CODEWORK_MODELS_FILE: invalidCatalog() }, "models");
expect(result.status).toBe(1);
expect(result.stderr).toContain("error[model-catalog-invalid]: model catalog contains invalid json");
expect(result.stderr).toContain("hint: run `codework models refresh`");
expect(result.stderr).not.toContain("Runner.TurnError");
expect(result.stderr).not.toContain("at Loop.runTurn");
});
it("refreshes the catalog in the home only when it is stale or forced", () => {
const home = mkdtempSync(join(tmpdir(), "codework-refresh-"));
const catalog = join(home, "models.gen.json");
// aikit's recorded catalog stands in for the published one.
const published = new URL("../../aikit/test/__artifacts__/modelgen.json", import.meta.url).href;
const env = { CODEWORK_MODELS_FILE: undefined, CODEWORK_CATALOG_URL: published };
try {
const first = runIn(home, env, "models", "refresh");
expect(first.status).toBe(0);
expect(first.stdout).toBe(`${catalog}\n`);
expect(first.stderr).toContain(`Refreshed model catalog at ${catalog}`);
expect(existsSync(catalog)).toBe(true);
const second = runIn(home, env, "models", "refresh");
expect(second.status).toBe(0);
expect(second.stderr).toContain("is fresh; pass --force");
const forced = runIn(home, env, "models", "refresh", "--force");
expect(forced.status).toBe(0);
expect(forced.stderr).toContain(`Refreshed model catalog at ${catalog}`);
const listed = runIn(home, env, "models", "providers");
expect(listed.status).toBe(0);
expect(listed.stdout).toContain("openai-codex\n");
} finally {
rmSync(home, { recursive: true, force: true });
}
});
it("prints a response cut off at the output token limit, warns, and exits 1", async () => {
const home = mkdtempSync(join(tmpdir(), "codework-cli-truncated-"));
onTestFinished(() => rmSync(home, { recursive: true, force: true }));
const fake = await truncating("The answer starts here and");
writeSettings(home, fake.url);
const result = await runCli(
["--home", home, "--database", ":memory:", "--user-config-dir", home, "run", "Answer at length."],
{ cwd: home, env: { ...process.env, HOME: home, CODEWORK_MODELS_FILE: models } },
);
expect(result.status, result.stderr).toBe(1);
expect(result.stdout, result.stderr).toBe("The answer starts here and\n");
const warning = "Response was truncated: the model reached its output token limit.\n";
expect(result.stderr.endsWith(warning), result.stderr).toBe(true);
await expect(
`${JSON.stringify({ status: result.status, stdout: result.stdout, warning }, null, "\t")}\n`,
).toMatchFileSnapshot("./__artifacts__/cli.truncated.json");
}, 60_000);
// A run ends with `session.run.failed`, never a success: a remote run must take that as its end.
it("reports a remote run ended by replies cut off with tool calls, and exits 1", async () => {
const home = mkdtempSync(join(tmpdir(), "codework-cli-run-failed-"));
onTestFinished(() => rmSync(home, { recursive: true, force: true }));
const fake = await streaming((_body, response) => {
response.send(toolCalls([{ name: "bash", arguments: { command: "echo cut" } }]));
response.finish("length");
});
writeSettings(home, fake.url);
// The CLI finds the server's token in the home it resolves, here through CODEWORK_HOME_DIR.
const env = { ...process.env, HOME: home, CODEWORK_HOME_DIR: home, CODEWORK_MODELS_FILE: models };
const server = await serveCli(["--home", home, "--user-config-dir", home], { cwd: home, env });
const result = await runCli(["run", "--server", server.url, "Run a long command."], { cwd: home, env });
expect(result.status, result.stderr).toBe(1);
expect(fake.requests).toHaveLength(2);
const message = "The response hit the output token limit with tool calls 2 times in a row; the run is ended";
expect(result.stderr, result.stderr).toContain(message);
await expect(
`${JSON.stringify({ status: result.status, stderr: result.stderr.slice(result.stderr.indexOf("error")) }, null, "\t")}\n`,
).toMatchFileSnapshot("./__artifacts__/cli.run-failed.json");
}, 60_000);
// `head` and `tail` were folded into the applied `init` migration, so the migrator never adds them.
it("refuses a database created before folded columns, naming the file, and exits 1", async () => {
const home = mkdtempSync(join(tmpdir(), "codework-cli-old-database-"));
onTestFinished(() => rmSync(home, { recursive: true, force: true }));
const fake = await streaming((_body, response) => {
response.send({ role: "assistant", content: "hello" });
response.finish("stop");
});
writeSettings(home, fake.url);
const options = { cwd: home, env: { ...process.env, HOME: home, CODEWORK_MODELS_FILE: models } };
const args = ["--home", home, "--user-config-dir", home, "run", "Say hello."];
const created = await runCli(args, options);
expect(created.status, created.stderr).toBe(0);
const file = join(home, "data", "codework.db");
const db = new DatabaseSync(file);
db.exec("ALTER TABLE thread DROP COLUMN head; ALTER TABLE inbox DROP COLUMN tail;");
db.close();
const result = await runCli(args, options);
expect(result.status, result.stderr).toBe(1);
expect(fake.requests).toHaveLength(1);
expect(result.stderr).toContain(file);
await expect(
`${JSON.stringify({ status: result.status, stderr: result.stderr.replaceAll(home, "<home>") }, null, "\t")}\n`,
).toMatchFileSnapshot("./__artifacts__/cli.old-database.json");
}, 60_000);
it("reports a failed refresh", () => {
const result = runIsolated(
{ CODEWORK_MODELS_FILE: undefined, CODEWORK_CATALOG_URL: "http://127.0.0.1:1/v1/models.json" },
"models",
"refresh",
);
expect(result.status).toBe(1);
expect(result.stderr).toContain("error[catalog-refresh-failed]: failed to refresh the model catalog at");
expect(result.stderr).toContain("hint: check the network connection and retry");
});
});