@akanjs/devkit 3.3.0-rc.69 → 3.3.0-rc.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.ko.md +2 -1
  2. package/README.md +2 -1
  3. package/akanApp/akanApp.host.ts +15 -2
  4. package/akanApp/akanApp.host.wiring.test.ts +111 -0
  5. package/akanApp/devHostPolicy.ts +5 -0
  6. package/akanApp/devMetadataRestart.ts +93 -0
  7. package/akanApp/devRecycler.test.ts +2 -0
  8. package/akanApp/devRecycler.ts +9 -0
  9. package/codeAgent/index.ts +1 -34
  10. package/codeAgent/skills/akan-page/SKILL.md +9 -4
  11. package/codeAgent/skills/akan-service/SKILL.md +11 -9
  12. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  13. package/executors/executors.test.ts +15 -0
  14. package/executors/pkgExecutor.ts +2 -1
  15. package/frontendBuild/csrDevPatcher.test.ts +3 -4
  16. package/frontendBuild/csrDevPatcher.ts +4 -4
  17. package/frontendBuild/devChangePlanner.ts +0 -1
  18. package/frontendBuild/frontendBuild.test.ts +5 -3
  19. package/frontendBuild/ssrBaseArtifactBuilder.ts +12 -7
  20. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  21. package/frontendBuild/vendorNarrowing.ts +10 -2
  22. package/incrementalBuilder/buildBatch.proc.ts +27 -1
  23. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  24. package/incrementalBuilder/builderWatch.ts +11 -1
  25. package/incrementalBuilder/incrementalBuilder.proc.test.ts +80 -0
  26. package/incrementalBuilder/incrementalBuilder.proc.ts +11 -2
  27. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  28. package/incrementalBuilder/pendingMetadata.ts +19 -0
  29. package/integration/devStability.integration.test.ts +46 -21
  30. package/package.json +5 -10
  31. package/packageExports.test.ts +3 -2
  32. package/test/fakeTerminal.ts +45 -0
  33. package/tunnel/ssh2Module.ts +2 -6
  34. package/util/devInstallCommand.ts +7 -0
  35. package/workspace/slicePlanner.ts +1 -0
  36. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  37. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  38. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  39. package/codeAgent/agent/CodeAgent.ts +0 -626
  40. package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
  41. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  42. package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
  43. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  44. package/codeAgent/agent/CodeAgentGate.ts +0 -258
  45. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  46. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  47. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  48. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  49. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  50. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  51. package/codeAgent/agent/CodeMailbox.ts +0 -148
  52. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  53. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  54. package/codeAgent/agent/SubagentPool.ts +0 -219
  55. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  56. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  57. package/codeAgent/agent/akanCodeModel.ts +0 -47
  58. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  59. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  60. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  61. package/codeAgent/agent/codeAgent.test.ts +0 -337
  62. package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
  63. package/codeAgent/agent/codeAgentContract.test.ts +0 -755
  64. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  65. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  66. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  67. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  68. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  69. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  70. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  71. package/codeAgent/agent/consoleToStderr.ts +0 -8
  72. package/codeAgent/agent/jsonLines.ts +0 -29
  73. package/codeAgent/agent/stringArg.ts +0 -5
  74. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  75. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  76. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  77. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  78. package/codeAgent/tools/AkanCli.ts +0 -51
  79. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  80. package/codeAgent/tools/AkanEditScope.ts +0 -53
  81. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  82. package/codeAgent/tools/AkanToolPack.ts +0 -86
  83. package/codeAgent/tools/AkanVerifier.ts +0 -30
  84. package/codeAgent/tools/AskToolPack.ts +0 -99
  85. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  86. package/codeAgent/tools/MailToolPack.ts +0 -76
  87. package/codeAgent/tools/McpClient.ts +0 -209
  88. package/codeAgent/tools/McpOAuth.ts +0 -233
  89. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  90. package/codeAgent/tools/McpServerConfig.ts +0 -131
  91. package/codeAgent/tools/McpSignIn.ts +0 -158
  92. package/codeAgent/tools/McpTokenStore.ts +0 -128
  93. package/codeAgent/tools/McpToolPack.ts +0 -206
  94. package/codeAgent/tools/SessionToolPack.ts +0 -91
  95. package/codeAgent/tools/WebToolPack.ts +0 -315
  96. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  97. package/codeAgent/tools/askToolPack.test.ts +0 -116
  98. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  99. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  100. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  101. package/piDependencyPins.test.ts +0 -45
@@ -1,755 +0,0 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import path from "node:path";
5
- import {
6
- CodeAgentClient,
7
- type CodeAgentEvent,
8
- type CodeAgentQuestion,
9
- type CodeAgentToolSummary,
10
- type CodeAgentTransport,
11
- codeAgentEventLabel,
12
- codeAgentEventPersistence,
13
- codeAgentPresets,
14
- codeAgentShouldPersist,
15
- isCodeAgentPresetName,
16
- } from "akanjs/common";
17
- import { akanCodeModelWarnings } from "./akanCodeModel";
18
- import { CodeAgentAsks } from "./CodeAgentAsks";
19
- import { CodeAgentCommandLine } from "./CodeAgentCommandLine";
20
- import { CodeAgentEventMapper } from "./CodeAgentEventMapper";
21
- import { CodeAgentGate } from "./CodeAgentGate";
22
- import { CodeAgentStreamPrinter } from "./CodeAgentStreamPrinter";
23
-
24
- const root = "/tmp/akan-code-test";
25
-
26
- class FakeTransport implements CodeAgentTransport {
27
- sent: string[] = [];
28
- #handler: (line: string) => void = () => {};
29
- send(line: string) {
30
- this.sent.push(line);
31
- }
32
- onLine(handler: (line: string) => void) {
33
- this.#handler = handler;
34
- }
35
- deliver(frame: unknown) {
36
- this.#handler(JSON.stringify(frame));
37
- }
38
- }
39
-
40
- const event = (seq: number, body: Partial<CodeAgentEvent> = {}) => ({ type: "idle", seq, ...body }) as CodeAgentEvent;
41
- const start = { type: "agent_start" } as never;
42
- const finished = (stopReason: string) => ({ type: "agent_end", messages: [{ stopReason }], willRetry: false }) as never;
43
-
44
- describe("CodeAgentClient", () => {
45
- test("correlates a reply with the command that asked for it", async () => {
46
- const transport = new FakeTransport();
47
- const client = new CodeAgentClient(transport);
48
- const promise = client.send({ type: "get_state" });
49
- const request = JSON.parse(transport.sent[0] ?? "{}") as { id: string };
50
- transport.deliver({ type: "reply", id: request.id, ok: true, data: { sessionId: "s1" } });
51
- expect(await promise).toEqual({ sessionId: "s1" });
52
- });
53
-
54
- test("rejects when the core reports the command failed", async () => {
55
- const transport = new FakeTransport();
56
- const client = new CodeAgentClient(transport);
57
- const promise = client.send({ type: "abort" });
58
- const request = JSON.parse(transport.sent[0] ?? "{}") as { id: string };
59
- transport.deliver({ type: "reply", id: request.id, ok: false, error: "nothing running" });
60
- await expect(promise).rejects.toThrow("nothing running");
61
- });
62
-
63
- test("drops a replayed frame and keeps the watermark monotonic", () => {
64
- const transport = new FakeTransport();
65
- const client = new CodeAgentClient(transport);
66
- const seen: number[] = [];
67
- client.on((e) => seen.push(e.seq));
68
- for (const seq of [1, 2, 2, 1, 3]) transport.deliver({ type: "event", event: event(seq) });
69
- expect(seen).toEqual([1, 2, 3]);
70
- expect(client.lastSeq).toBe(3);
71
- });
72
-
73
- test("a new session resets the watermark, or its first frames read as duplicates", () => {
74
- const transport = new FakeTransport();
75
- const client = new CodeAgentClient(transport);
76
- const seen: number[] = [];
77
- client.on((e) => seen.push(e.seq));
78
- transport.deliver({ type: "event", event: event(7) });
79
- client.resetSeq();
80
- transport.deliver({ type: "event", event: event(1) });
81
- expect(seen).toEqual([7, 1]);
82
- });
83
-
84
- test("ignores a line that is not a frame instead of tearing the stream down", () => {
85
- const transport = new FakeTransport();
86
- const client = new CodeAgentClient(transport);
87
- const seen: number[] = [];
88
- client.on((e) => seen.push(e.seq));
89
- transport.deliver("not json" as unknown);
90
- client.push('{"type":"event","event":{"type":"idle","seq":1}}\n');
91
- expect(seen).toEqual([1]);
92
- });
93
- });
94
-
95
- describe("codeAgentPresets", () => {
96
- test("review gives no write, bash or web tools", () => {
97
- const profile = codeAgentPresets.review(root);
98
- expect(profile.tools.builtin).toEqual(["read", "ls", "grep", "find"]);
99
- expect(profile.tools.web).toEqual({ fetch: false, search: false });
100
- expect(profile.context.projectFiles).toBe(false);
101
- });
102
-
103
- test("a pod cannot prompt and therefore suspends both interactions", () => {
104
- const profile = codeAgentPresets.pod(root);
105
- expect(profile.ui.canPrompt).toBe(false);
106
- expect(profile.interaction).toEqual({ question: "suspend", approval: "suspend" });
107
- });
108
-
109
- test("web asks before writing even though the runner is isolated", () => {
110
- expect(codeAgentPresets.web(root).approval).toBe("writes");
111
- });
112
-
113
- test("local asks before a shell command and nothing else, and a pod asks about neither", () => {
114
- const local = new CodeAgentGate(codeAgentPresets.local(root));
115
- expect(local.verdict("bash", { command: "git status" }).approval).toBe("run: git status");
116
- expect(local.verdict("bash", { command: "curl https://example.com" }).strict).toBe(true);
117
- expect(local.verdict("write", { path: "a.ts" })).toEqual({});
118
- expect(local.verdict("read", { path: "a.ts" })).toEqual({});
119
- expect(new CodeAgentGate(codeAgentPresets.pod(root)).verdict("bash", { command: "git status" })).toEqual({});
120
- });
121
-
122
- test("every preset denies env files and secrets", () => {
123
- for (const name of ["local", "pod", "review", "web"] as const)
124
- expect(codeAgentPresets[name](root).paths.deny).toContain("**/.env");
125
- });
126
-
127
- test("MCP discovery is on where a person is driving and off where nobody vetted the server", () => {
128
- expect(codeAgentPresets.local(root).tools.mcp).toEqual([]);
129
- expect(codeAgentPresets.web(root).tools.mcp).toEqual([]);
130
- expect(codeAgentPresets.review(root).tools.mcp).toBe("off");
131
- expect(codeAgentPresets.pod(root).tools.mcp).toBe("off");
132
- });
133
-
134
- test("only the local profile asks before reaching a host off its list", () => {
135
- expect(codeAgentPresets.local(root).network.askOutside).toContain("github.com");
136
- for (const name of ["pod", "review", "web"] as const)
137
- expect(codeAgentPresets[name](root).network.askOutside).toBeUndefined();
138
- });
139
-
140
- test("isCodeAgentPresetName refuses an unknown name", () => {
141
- expect(isCodeAgentPresetName("local")).toBe(true);
142
- expect(isCodeAgentPresetName("prod")).toBe(false);
143
- });
144
- });
145
-
146
- const localUnasked = () => ({ ...codeAgentPresets.local(root), approval: "never" as const });
147
-
148
- describe("CodeAgentGate", () => {
149
- test("blocks a path on the deny list", () => {
150
- const gate = new CodeAgentGate(codeAgentPresets.local(root));
151
- expect(gate.verdict("read", { path: ".env" }).block).toContain("deny list");
152
- expect(gate.verdict("read", { path: "apps/a/secrets/token.json" }).block).toContain("deny list");
153
- });
154
-
155
- test("blocks a path that escapes the agent root", () => {
156
- const gate = new CodeAgentGate(codeAgentPresets.local(root));
157
- expect(gate.verdict("read", { path: "../../etc/passwd" }).block).toContain("outside the agent root");
158
- expect(gate.verdict("read", { path: "/etc/passwd" }).block).toContain("outside the agent root");
159
- });
160
-
161
- test("lets an ordinary path through", () => {
162
- const gate = new CodeAgentGate(codeAgentPresets.local(root));
163
- expect(gate.verdict("read", { path: "apps/a/lib/post/post.service.ts" })).toEqual({});
164
- });
165
-
166
- test("approval:writes asks for write and edit only", () => {
167
- const gate = new CodeAgentGate(codeAgentPresets.web(root));
168
- expect(gate.verdict("write", { path: "a.ts" }).approval).toBe("write a.ts");
169
- expect(gate.verdict("edit", { path: "a.ts" }).approval).toBe("edit a.ts");
170
- expect(gate.verdict("read", { path: "a.ts" }).approval).toBeUndefined();
171
- expect(gate.verdict("bash", { command: "ls" }).approval).toBeUndefined();
172
- });
173
-
174
- test("approval:commands summarises the command it is asking about", () => {
175
- const profile = { ...codeAgentPresets.local(root), approval: "commands" as const };
176
- const gate = new CodeAgentGate(profile);
177
- expect(gate.verdict("bash", { command: "rm -rf build" }).approval).toBe("run: rm -rf build");
178
- });
179
-
180
- test("an allow list narrows further than the root", () => {
181
- const profile = codeAgentPresets.local(root);
182
- const gate = new CodeAgentGate({ ...profile, paths: { ...profile.paths, allow: ["apps/**"] } });
183
- expect(gate.verdict("read", { path: "apps/a/x.ts" }).block).toBeUndefined();
184
- expect(gate.verdict("read", { path: "libs/b/x.ts" }).block).toContain("allow list");
185
- });
186
- });
187
-
188
- describe("CodeAgentGate allow for this session", () => {
189
- const gate = () => new CodeAgentGate(codeAgentPresets.local(root));
190
- const allow = (target: CodeAgentGate, names: string[]) => {
191
- target.allowed.offer("a0", names);
192
- target.allowed.settle("a0", true);
193
- };
194
-
195
- test("a command asks with the name a session answer would remember", () => {
196
- expect(gate().verdict("bash", { command: "git status --short" })).toEqual({
197
- approval: "run: git status --short",
198
- remember: ["git status"],
199
- });
200
- });
201
-
202
- test("an allowed command runs unasked, and another sub-command of its program still asks", () => {
203
- const local = gate();
204
- allow(local, ["git status", "bun test"]);
205
- expect(local.verdict("bash", { command: "git status" })).toEqual({});
206
- expect(local.verdict("bash", { command: "bun test --isolate ./a.test.ts" })).toEqual({});
207
- expect(local.verdict("bash", { command: "git diff" }).remember).toEqual(["git diff"]);
208
- expect(local.verdict("bash", { command: "bun x cowsay" }).remember).toEqual(["bun x"]);
209
- });
210
-
211
- test("a compound line runs unasked only once every command in it is allowed, and offers the ones that are not", () => {
212
- const local = gate();
213
- allow(local, ["bun test"]);
214
- const line = { command: "cd apps && bun test 2>&1 | tail -20" };
215
- expect(local.verdict("bash", line).remember).toEqual(["cd", "tail"]);
216
- allow(local, ["cd"]);
217
- expect(local.verdict("bash", line).remember).toEqual(["tail"]);
218
- allow(local, ["tail"]);
219
- expect(local.verdict("bash", line)).toEqual({});
220
- expect(local.verdict("bash", { command: "bun test && echo $(git log -1)" }).remember).toEqual(["git log", "echo"]);
221
- });
222
-
223
- test("a networking command, git push, rm and a command that runs another are asked every time with no session answer", () => {
224
- const local = gate();
225
- allow(local, [...CodeAgentCommandLine.alwaysAsked, "git", "ls", "echo"]);
226
- for (const command of [
227
- "curl https://example.com",
228
- "curl http://127.0.0.1:3000/health",
229
- "ls && ssh deploy@host",
230
- "git push",
231
- "git push origin main",
232
- "ls; rm -rf build",
233
- "sudo ls",
234
- "timeout 5 ls",
235
- "sh -c 'ls'",
236
- "ls | xargs echo",
237
- "source ./x.sh",
238
- "npm publish",
239
- "gh api user",
240
- "PATH=/tmp/bin ls",
241
- "ls </dev/tcp/host/80",
242
- ]) {
243
- const verdict = local.verdict("bash", { command });
244
- expect(verdict.approval).toBeDefined();
245
- expect(verdict.remember).toBeUndefined();
246
- }
247
- });
248
-
249
- test("a networking command stays asked every time where network requests are not asked about", () => {
250
- const { askOutside: _ask, ...network } = codeAgentPresets.local(root).network;
251
- const quiet = new CodeAgentGate({ ...codeAgentPresets.local(root), network });
252
- expect(quiet.verdict("bash", { command: "curl https://example.com" })).toEqual({
253
- approval: "run: curl https://example.com",
254
- });
255
- });
256
-
257
- test("a line that cannot be split with confidence, or that writes a file by redirection, asks with no session answer", () => {
258
- const local = gate();
259
- allow(local, ["echo", "ls", "wc"]);
260
- for (const command of ["echo `ls`", "for f in a b; do wc -l $f; done", "echo hi > ~/.zshrc", "ls | wc -l > n.txt"])
261
- expect(local.verdict("bash", { command })).toEqual({ approval: `run: ${command}` });
262
- });
263
-
264
- test("forgetting what was allowed asks again", () => {
265
- const local = gate();
266
- allow(local, ["ls"]);
267
- expect(local.allowed.names).toEqual(["ls"]);
268
- expect(local.allowed.clear()).toBe(1);
269
- expect(local.verdict("bash", { command: "ls" }).remember).toEqual(["ls"]);
270
- });
271
-
272
- test("a file write that waits for approval has no session answer", () => {
273
- const web = new CodeAgentGate(codeAgentPresets.web(root));
274
- expect(web.verdict("write", { path: "a.ts" })).toEqual({ approval: "write a.ts" });
275
- });
276
-
277
- test("an approval still waiting is covered once the names it offered are all allowed", () => {
278
- const local = gate();
279
- local.allowed.offer("a1", ["bun test"]);
280
- local.allowed.offer("a2", ["bun test"]);
281
- local.allowed.offer("a3", ["bun test", "cd"]);
282
- expect(local.allowed.settle("a1", true)).toEqual(["bun test"]);
283
- expect(local.allowed.covered()).toEqual(["a2"]);
284
- expect(local.allowed.settle("a2", false)).toEqual([]);
285
- expect(local.allowed.covered()).toEqual([]);
286
- });
287
- });
288
-
289
- describe("CodeAgentAsks", () => {
290
- const questionOf = (questionId: string): CodeAgentQuestion => ({
291
- questionId,
292
- prompt: "which colour?",
293
- kind: "select",
294
- options: [
295
- { key: "teal", label: "Teal" },
296
- { key: "rose", label: "Rose" },
297
- ],
298
- });
299
-
300
- test("answers the pending question and ignores a stale id", async () => {
301
- const asks = new CodeAgentAsks();
302
- const id = asks.nextId("q");
303
- const promise = asks.openQuestion(questionOf(id));
304
- expect(asks.answer("q99", "wrong")).toBe(false);
305
- expect(asks.answer(id, "teal")).toBe(true);
306
- expect(await promise).toBe("teal");
307
- expect(asks.answer(id, "again")).toBe(false);
308
- });
309
-
310
- test("approvals are a queue, so two in a row both resolve", async () => {
311
- const asks = new CodeAgentAsks();
312
- const first = asks.nextId("a");
313
- const second = asks.nextId("a");
314
- const promises = [asks.openApproval(first), asks.openApproval(second)];
315
- asks.resolveApproval(second, false);
316
- asks.resolveApproval(first, true);
317
- expect(await Promise.all(promises)).toEqual([true, false]);
318
- });
319
-
320
- test("clearing resolves everything so no caller is stranded", async () => {
321
- const asks = new CodeAgentAsks();
322
- const question = asks.openQuestion(questionOf(asks.nextId("q")));
323
- const approval = asks.openApproval(asks.nextId("a"));
324
- asks.clear();
325
- expect(await question).toBe("");
326
- expect(await approval).toBe(false);
327
- expect(asks.pendingQuestionId).toBeUndefined();
328
- expect(asks.hasPendingApproval).toBe(false);
329
- });
330
- });
331
-
332
- describe("CodeAgentEventMapper", () => {
333
- test("a run becomes one turn, not one turn per round trip", () => {
334
- const mapper = new CodeAgentEventMapper();
335
- expect(mapper.map(start)).toEqual([{ type: "turn_start", turnId: "t1" }]);
336
- expect(mapper.map({ type: "turn_start" } as never)).toEqual([]);
337
- expect(mapper.map(start)).toEqual([{ type: "turn_start", turnId: "t2" }]);
338
- });
339
-
340
- test("streams text and thinking deltas apart", () => {
341
- const mapper = new CodeAgentEventMapper();
342
- mapper.map(start);
343
- const text = mapper.map({
344
- type: "message_update",
345
- assistantMessageEvent: { type: "text_delta", delta: "hi" },
346
- } as never);
347
- const think = mapper.map({
348
- type: "message_update",
349
- assistantMessageEvent: { type: "thinking_delta", delta: "hmm" },
350
- } as never);
351
- expect(text).toEqual([{ type: "text_delta", turnId: "t1", text: "hi" }]);
352
- expect(think).toEqual([{ type: "thinking_delta", turnId: "t1", text: "hmm" }]);
353
- });
354
-
355
- test("a structured argument is described by its shape, not stringified", () => {
356
- const mapper = new CodeAgentEventMapper();
357
- mapper.map(start);
358
- const [event] = mapper.map({
359
- type: "tool_execution_start",
360
- toolCallId: "c1",
361
- toolName: "edit",
362
- args: { path: "/repo/a.ts", edits: [{ old: "x" }, { old: "y" }], options: { dryRun: false } },
363
- } as never);
364
- const title = event?.type === "tool_start" ? event.tool.title : "";
365
- expect(title).not.toContain("[object Object]");
366
- expect(title).toContain("edits=2 items");
367
- expect(title).toContain("options={1 key}");
368
- expect(title).toContain("path=/repo/a.ts");
369
- });
370
-
371
- test("a blocked call gets a start frame and the engine's end frame is relabelled once", () => {
372
- const mapper = new CodeAgentEventMapper();
373
- mapper.map(start);
374
- const tool: CodeAgentToolSummary = {
375
- toolCallId: "c1",
376
- name: "read",
377
- op: "read",
378
- path: ".env",
379
- title: "read(path=.env)",
380
- };
381
- expect(mapper.markBlocked("c1", "read", { path: ".env" }, "denied")).toEqual([
382
- { type: "tool_start", turnId: "t1", tool },
383
- ]);
384
- const ended = mapper.map({
385
- type: "tool_execution_end",
386
- toolCallId: "c1",
387
- toolName: "read",
388
- result: {},
389
- isError: true,
390
- } as never);
391
- expect(ended).toEqual([
392
- { type: "tool_end", turnId: "t1", tool, outcome: "blocked", output: "denied", truncated: false },
393
- ]);
394
- expect(mapper.flushBlocked()).toEqual([]);
395
- });
396
-
397
- test("a refusal the engine never closes is swept at the turn boundary", () => {
398
- const mapper = new CodeAgentEventMapper();
399
- mapper.map(start);
400
- mapper.markBlocked("c2", "bash", { command: "rm" }, "denied");
401
- const frames = mapper.map({ type: "agent_end", messages: [], willRetry: false } as never);
402
- expect(frames.map((f) => f.type)).toEqual(["tool_end", "turn_end"]);
403
- });
404
-
405
- test("reports an aborted run as aborted rather than done", () => {
406
- const mapper = new CodeAgentEventMapper();
407
- mapper.map(start);
408
- expect(mapper.map(finished("aborted"))).toEqual([{ type: "turn_end", turnId: "t1", stopReason: "aborted" }]);
409
- });
410
-
411
- test("a compaction that failed or was cancelled carries that, not just its reason", () => {
412
- const mapper = new CodeAgentEventMapper();
413
- const end = (fields: object) =>
414
- mapper.map({
415
- type: "compaction_end",
416
- reason: "threshold",
417
- result: undefined,
418
- willRetry: false,
419
- ...fields,
420
- } as never);
421
- expect(end({ aborted: false, errorMessage: "Auto-compaction failed: 529" })).toEqual([
422
- { type: "compaction", phase: "end", reason: "threshold", error: "Auto-compaction failed: 529" },
423
- ]);
424
- expect(end({ aborted: true })).toEqual([{ type: "compaction", phase: "end", reason: "threshold", aborted: true }]);
425
- expect(end({ aborted: false })).toEqual([{ type: "compaction", phase: "end", reason: "threshold" }]);
426
- });
427
- });
428
-
429
- describe("CodeAgentStreamPrinter", () => {
430
- const collect = (events: CodeAgentEvent[], json = false) => {
431
- const lines: string[] = [];
432
- const printer = new CodeAgentStreamPrinter({ json, write: (text) => lines.push(text) });
433
- for (const e of events) printer.print(e);
434
- printer.finish();
435
- return lines.join("");
436
- };
437
-
438
- test("closes a streamed line before printing a tool row", () => {
439
- const output = collect([
440
- { type: "text_delta", turnId: "t1", text: "working", seq: 1 },
441
- { type: "tool_start", turnId: "t1", tool: { toolCallId: "c1", name: "ls", op: "list", title: "ls" }, seq: 2 },
442
- ]);
443
- expect(output.split("\n")[0]).toBe("working");
444
- expect(output).toContain("ls");
445
- });
446
-
447
- test("json mode prints the event verbatim, one per line", () => {
448
- const output = collect([{ type: "idle", seq: 4 }], true);
449
- expect(JSON.parse(output)).toEqual({ type: "idle", seq: 4 });
450
- });
451
-
452
- test("hides thinking unless it was asked for", () => {
453
- const lines: string[] = [];
454
- const printer = new CodeAgentStreamPrinter({ write: (t) => lines.push(t) });
455
- printer.print({ type: "thinking_delta", turnId: "t1", text: "secret", seq: 1 });
456
- expect(lines.join("")).toBe("");
457
- });
458
- });
459
-
460
- describe("codeAgentEventLabel", () => {
461
- test("renders every event kind without throwing", () => {
462
- const events: CodeAgentEvent[] = [
463
- {
464
- type: "session",
465
- info: {
466
- sessionId: "s",
467
- cwd: root,
468
- profile: "local",
469
- model: undefined,
470
- tools: [],
471
- contextTokens: undefined,
472
- effort: undefined,
473
- autoCompactAt: undefined,
474
- name: undefined,
475
- interaction: { question: "await", approval: "await" },
476
- },
477
- seq: 1,
478
- },
479
- { type: "turn_start", turnId: "t1", seq: 2 },
480
- { type: "turn_end", turnId: "t1", stopReason: "done", seq: 3 },
481
- { type: "message", turnId: "t1", role: "assistant", text: "hi", seq: 4 },
482
- {
483
- type: "tool_end",
484
- turnId: "t1",
485
- tool: { toolCallId: "c", name: "ls", op: "list", title: "ls" },
486
- outcome: "blocked",
487
- output: "no",
488
- truncated: false,
489
- seq: 5,
490
- },
491
- { type: "question", question: { questionId: "q1", prompt: "which?", kind: "text" }, seq: 6 },
492
- { type: "host", kind: "preview", id: "p1", payload: { url: "http://localhost:8282" }, seq: 14 },
493
- {
494
- type: "approval",
495
- request: {
496
- approvalId: "a1",
497
- toolCallId: "c",
498
- name: "write",
499
- summary: "write a.ts",
500
- policy: "writes",
501
- },
502
- seq: 7,
503
- },
504
- { type: "compaction", phase: "start", reason: "threshold", seq: 8 },
505
- { type: "retry", attempt: 1, maxAttempts: 3, delayMs: 100, message: "overloaded", seq: 9 },
506
- { type: "queue", steering: [], followUp: ["x"], seq: 10 },
507
- { type: "notice", level: "warning", message: "careful", seq: 11 },
508
- { type: "error", message: "boom", fatal: true, seq: 12 },
509
- { type: "idle", seq: 13 },
510
- ];
511
- for (const e of events) expect(codeAgentEventLabel(e).length).toBeGreaterThan(0);
512
- });
513
- });
514
-
515
- describe("CodeAgentGate bash", () => {
516
- test("refuses a shell command that names a denied file", () => {
517
- const gate = new CodeAgentGate(codeAgentPresets.local(root));
518
- expect(gate.verdict("bash", { command: "cat .env" }).block).toContain(".env");
519
- expect(gate.verdict("bash", { command: "cat ../../.env" }).block).toContain(".env");
520
- expect(gate.verdict("bash", { command: "ls secrets/" }).block).toContain("secrets/");
521
- expect(gate.verdict("bash", { command: "openssl x509 -in server.pem" }).block).toContain(".pem");
522
- });
523
-
524
- test("leaves an ordinary command alone where commands are not asked about", () => {
525
- const gate = new CodeAgentGate(localUnasked());
526
- expect(gate.verdict("bash", { command: "bun test --isolate" })).toEqual({});
527
- expect(gate.verdict("bash", { command: "grep -r TODO ." })).toEqual({});
528
- });
529
- });
530
-
531
- describe("CodeAgentGate secrets", () => {
532
- const gate = () => new CodeAgentGate(localUnasked());
533
-
534
- test("a per-environment server env file is refused for read, write and shell, and its loader is not", () => {
535
- const file = "apps/a/env/env.server.main.ts";
536
- expect(gate().verdict("read", { path: file }).block).toContain("deny list");
537
- expect(gate().verdict("write", { path: file }).block).toContain("deny list");
538
- expect(gate().verdict("bash", { command: `cat ${file}` }).block).toBeDefined();
539
- expect(gate().verdict("read", { path: "apps/a/env/env.server.ts" })).toEqual({});
540
- expect(gate().verdict("read", { path: "apps/a/env/env.server.type.ts" })).toEqual({});
541
- });
542
-
543
- test("the engine's own spellings of a path are read as the path they name", () => {
544
- expect(gate().verdict("read", { path: "@.env" }).block).toContain("deny list");
545
- expect(gate().verdict("read", { path: `file://${root}/apps/a/.env` }).block).toContain("deny list");
546
- expect(gate().verdict("read", { path: "~/notes.md" }).block).toContain("outside the agent root");
547
- });
548
-
549
- test("a shell command naming the home credential stores or a wildcard for a secret file is refused", () => {
550
- expect(gate().verdict("bash", { command: "cat ~/.akan/code/auth.json" }).block).toBeDefined();
551
- expect(gate().verdict("bash", { command: "cat $HOME/.ssh/id_ed25519" }).block).toBeDefined();
552
- expect(gate().verdict("bash", { command: "cat .e?v" }).block).toBeDefined();
553
- expect(gate().verdict("bash", { command: "cat .akan/code/mcp.json" }).block).toBeDefined();
554
- expect(gate().verdict("bash", { command: "grep -r TODO --include=*.ts ." })).toEqual({});
555
- });
556
-
557
- test("a link inside the root is judged by the file it points at", () => {
558
- const linked = mkdtempSync(path.join(tmpdir(), "akan-gate-"));
559
- try {
560
- mkdirSync(path.join(linked, "secrets"));
561
- writeFileSync(path.join(linked, "secrets", "token.json"), "{}");
562
- symlinkSync(path.join(linked, "secrets", "token.json"), path.join(linked, "notes.json"));
563
- const linkedGate = new CodeAgentGate(codeAgentPresets.local(linked));
564
- expect(linkedGate.verdict("read", { path: "notes.json" }).block).toContain("deny list");
565
- } finally {
566
- rmSync(linked, { recursive: true, force: true });
567
- }
568
- });
569
-
570
- test("a link inside the root that leads out of it is read, and a denied file through it is not", () => {
571
- const repo = mkdtempSync(path.join(tmpdir(), "akan-gate-"));
572
- const linkedLib = mkdtempSync(path.join(tmpdir(), "akan-gate-lib-"));
573
- try {
574
- writeFileSync(path.join(linkedLib, "index.ts"), "export {};");
575
- writeFileSync(path.join(linkedLib, ".env"), "");
576
- mkdirSync(path.join(repo, "node_modules"));
577
- symlinkSync(linkedLib, path.join(repo, "node_modules", "lib"));
578
- const linkedGate = new CodeAgentGate(codeAgentPresets.local(repo));
579
- expect(linkedGate.verdict("read", { path: "node_modules/lib/index.ts" })).toEqual({});
580
- expect(linkedGate.verdict("read", { path: "node_modules/lib/.env" }).block).toContain("deny list");
581
- expect(linkedGate.verdict("read", { path: path.join(linkedLib, "index.ts") }).block).toContain(
582
- "outside the agent root",
583
- );
584
- } finally {
585
- rmSync(repo, { recursive: true, force: true });
586
- rmSync(linkedLib, { recursive: true, force: true });
587
- }
588
- });
589
- });
590
-
591
- describe("CodeAgentGate network", () => {
592
- const gate = () => new CodeAgentGate(localUnasked());
593
-
594
- test("the local profile asks before fetching a host off its list, and not for a listed one or loopback", () => {
595
- expect(gate().verdict("web_fetch", { url: "https://example.com/x" })).toEqual({
596
- approval: "fetch https://example.com/x",
597
- strict: true,
598
- });
599
- expect(gate().verdict("web_fetch", { url: "https://docs.github.com/en" })).toEqual({});
600
- expect(gate().verdict("web_fetch", { url: "http://localhost:3000/" })).toEqual({});
601
- });
602
-
603
- test("a networking shell command asks, unless it only reaches loopback over http", () => {
604
- expect(gate().verdict("bash", { command: "curl -s https://example.com" }).strict).toBe(true);
605
- expect(gate().verdict("bash", { command: "curl -X POST https://github.com/x" }).strict).toBe(true);
606
- expect(gate().verdict("bash", { command: "ssh deploy@host" }).strict).toBe(true);
607
- expect(gate().verdict("bash", { command: "curl http://127.0.0.1:8080/health" })).toEqual({});
608
- expect(gate().verdict("bash", { command: "git status && bun test" })).toEqual({});
609
- });
610
-
611
- test("a loopback host:port without a scheme is loopback, and any other host still asks", () => {
612
- expect(gate().verdict("bash", { command: "curl -s localhost:4200/health" })).toEqual({});
613
- expect(gate().verdict("bash", { command: 'wget -qO- "127.0.0.1:8080"' })).toEqual({});
614
- expect(gate().verdict("bash", { command: "curl [::1]:3000/x" })).toEqual({});
615
- expect(gate().verdict("bash", { command: "curl -s example.com:443/x" }).strict).toBe(true);
616
- expect(gate().verdict("bash", { command: "curl -s localhost:4200 example.com:80" }).strict).toBe(true);
617
- });
618
-
619
- test("a client name asks only where it runs as a command, not as another command's argument", () => {
620
- for (const command of ["grep -rn curl src", "echo ssh", "git log --grep=wget", "cat docs/rsync.md"])
621
- expect(gate().verdict("bash", { command })).toEqual({});
622
- for (const command of [
623
- "ls && curl https://example.com",
624
- "cat body | curl -d @- https://example.com",
625
- "echo $(curl https://example.com)",
626
- "FOO=1 sudo -E /usr/bin/curl https://example.com",
627
- "timeout 5 wget https://example.com",
628
- "sh -c 'curl https://example.com'",
629
- "bun test\nssh deploy@host",
630
- ])
631
- expect(gate().verdict("bash", { command }).strict).toBe(true);
632
- });
633
-
634
- test("a profile without a list never asks", () => {
635
- const pod = new CodeAgentGate(codeAgentPresets.pod(root));
636
- expect(pod.verdict("web_fetch", { url: "https://example.com/x" })).toEqual({});
637
- expect(pod.verdict("bash", { command: "curl https://example.com" })).toEqual({});
638
- });
639
- });
640
-
641
- describe("codeAgentShouldPersist", () => {
642
- test("follows the table for engine frames", () => {
643
- expect(codeAgentShouldPersist({ type: "message", turnId: "t1", role: "assistant", text: "hi" })).toBe(true);
644
- expect(codeAgentShouldPersist({ type: "text_delta", turnId: "t1", text: "hi" })).toBe(false);
645
- expect(codeAgentShouldPersist({ type: "thinking_delta", turnId: "t1", text: "hm" })).toBe(false);
646
- expect(codeAgentShouldPersist({ type: "error", message: "boom", fatal: false })).toBe(true);
647
- });
648
-
649
- test("a host frame decides per frame, not per kind", () => {
650
- const running = { type: "host" as const, kind: "step", id: "s1", payload: { status: "pending" } };
651
- const done = { type: "host" as const, kind: "step", id: "s1", persist: true, payload: { status: "done" } };
652
- expect(codeAgentShouldPersist(running)).toBe(false);
653
- expect(codeAgentShouldPersist(done)).toBe(true);
654
- });
655
-
656
- test("the table answers every event type", () => {
657
- const types = Object.keys(codeAgentEventPersistence);
658
- expect(types).toContain("host");
659
- expect(types.every((type) => ["live", "persist"].includes(codeAgentEventPersistence[type as never]))).toBe(true);
660
- });
661
- });
662
-
663
- describe("turn outcome", () => {
664
- test("an abort is reported even though the engine calls it a normal stop", () => {
665
- const mapper = new CodeAgentEventMapper();
666
- mapper.map(start);
667
- mapper.noteOutcome("aborted");
668
- expect(mapper.map(finished("stop"))).toEqual([{ type: "turn_end", turnId: "t1", stopReason: "aborted" }]);
669
- });
670
-
671
- test("suspending to ask a person ends the turn as awaiting", () => {
672
- const mapper = new CodeAgentEventMapper();
673
- mapper.map(start);
674
- mapper.noteOutcome("awaiting");
675
- expect(mapper.map(finished("stop"))).toEqual([{ type: "turn_end", turnId: "t1", stopReason: "awaiting" }]);
676
- });
677
-
678
- test("the note is consumed once and never colours the next turn", () => {
679
- const mapper = new CodeAgentEventMapper();
680
- mapper.map(start);
681
- mapper.noteOutcome("aborted");
682
- mapper.map(finished("stop"));
683
- mapper.map(start);
684
- expect(mapper.map(finished("stop"))).toEqual([{ type: "turn_end", turnId: "t2", stopReason: "done" }]);
685
- });
686
-
687
- test("a note left by an abort that hit an idle session is dropped at the next turn", () => {
688
- const mapper = new CodeAgentEventMapper();
689
- mapper.noteOutcome("aborted");
690
- mapper.map(start);
691
- expect(mapper.map(finished("stop"))).toEqual([{ type: "turn_end", turnId: "t1", stopReason: "done" }]);
692
- });
693
-
694
- test("falls back to the engine when the core noted nothing", () => {
695
- const mapper = new CodeAgentEventMapper();
696
- mapper.map(start);
697
- expect(mapper.map(finished("error"))).toEqual([{ type: "turn_end", turnId: "t1", stopReason: "error" }]);
698
- });
699
- });
700
-
701
- describe("truncation", () => {
702
- test("the engine's `length` is a partial success, not a completed turn", () => {
703
- const mapper = new CodeAgentEventMapper();
704
- mapper.map(start);
705
- expect(mapper.map(finished("length"))).toEqual([{ type: "turn_end", turnId: "t1", stopReason: "truncated" }]);
706
- });
707
-
708
- test("an abort still wins over the engine's report", () => {
709
- const mapper = new CodeAgentEventMapper();
710
- mapper.map(start);
711
- mapper.noteOutcome("aborted");
712
- expect(mapper.map(finished("length"))).toEqual([{ type: "turn_end", turnId: "t1", stopReason: "aborted" }]);
713
- });
714
-
715
- test("the terminal says so, because a cut answer looks like a finished one", () => {
716
- const lines: string[] = [];
717
- const printer = new CodeAgentStreamPrinter({ write: (text) => lines.push(text) });
718
- printer.print({ type: "turn_end", turnId: "t1", stopReason: "done", seq: 1 });
719
- expect(lines.join("")).toBe("");
720
- printer.print({ type: "turn_end", turnId: "t1", stopReason: "truncated", seq: 2 });
721
- expect(lines.join("")).toContain("cut off");
722
- });
723
- });
724
-
725
- describe("akanCodeModelWarnings", () => {
726
- const model = (contextWindow: number) =>
727
- ({ provider: "custom", id: "m", contextWindow }) as unknown as Parameters<typeof akanCodeModelWarnings>[0];
728
-
729
- test("says so when the window cannot hold the compaction policy", () => {
730
- expect(akanCodeModelWarnings(model(8_192), 36_384)[0]).toContain("compact immediately");
731
- });
732
-
733
- test("stays quiet for an ordinary small-output model", () => {
734
- expect(akanCodeModelWarnings(model(128_000), 36_384)).toEqual([]);
735
- });
736
-
737
- test("no model is not a warning", () => {
738
- expect(akanCodeModelWarnings(undefined, 36_384)).toEqual([]);
739
- });
740
- });
741
-
742
- describe("wire coverage", () => {
743
- test("every event type either has a producer in the core or is documented as host-supplied", async () => {
744
- const dir = import.meta.dir;
745
- const sources = await Promise.all(
746
- ["CodeAgent.ts", "CodeAgentEventMapper.ts"].map(async (file) => await Bun.file(`${dir}/${file}`).text()),
747
- );
748
- const core = sources.join("\n");
749
- const hostSupplied = new Set(["host"]);
750
- const missing = Object.keys(codeAgentEventPersistence).filter(
751
- (type) => !hostSupplied.has(type) && !core.includes(`type: "${type}"`),
752
- );
753
- expect(missing).toEqual([]);
754
- });
755
- });