@akanjs/code 0.0.0 → 3.3.0-rc.71

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 (109) hide show
  1. package/README.ko.md +31 -0
  2. package/README.md +26 -4
  3. package/agent/AkanCodeCompaction.ts +49 -0
  4. package/agent/AkanCodeServices.ts +122 -0
  5. package/agent/AkanContextFiles.ts +94 -0
  6. package/agent/CodeAgent.ts +598 -0
  7. package/agent/CodeAgentAllowed.ts +35 -0
  8. package/agent/CodeAgentAsks.ts +66 -0
  9. package/agent/CodeAgentCommandLine.ts +372 -0
  10. package/agent/CodeAgentEventMapper.ts +225 -0
  11. package/agent/CodeAgentFrames.ts +57 -0
  12. package/agent/CodeAgentGate.ts +258 -0
  13. package/agent/CodeAgentProxy.ts +83 -0
  14. package/agent/CodeAgentRpcHost.ts +109 -0
  15. package/agent/CodeAgentRpcListener.ts +195 -0
  16. package/agent/CodeAgentStreamPrinter.ts +86 -0
  17. package/agent/CodeAgentSuspended.ts +85 -0
  18. package/agent/CodeAgentUi.ts +47 -0
  19. package/agent/CodeMailbox.ts +148 -0
  20. package/agent/CodeSessionFork.ts +56 -0
  21. package/agent/CodeSessionIndex.ts +78 -0
  22. package/agent/SubagentPool.ts +222 -0
  23. package/agent/WorkspaceTrust.ts +200 -0
  24. package/agent/akanCodeCompaction.test.ts +36 -0
  25. package/agent/akanCodeModel.ts +47 -0
  26. package/agent/akanCodeServices.test.ts +54 -0
  27. package/agent/akanContextFiles.test.ts +116 -0
  28. package/agent/akanSystemPrompt.ts +50 -0
  29. package/agent/codeAgent.test.ts +337 -0
  30. package/agent/codeAgentCommandLine.test.ts +212 -0
  31. package/agent/codeAgentContract.test.ts +757 -0
  32. package/agent/codeAgentHosts.ts +30 -0
  33. package/agent/codeAgentProxy.test.ts +125 -0
  34. package/agent/codeAgentRpcListener.test.ts +215 -0
  35. package/agent/codeAgentSuspended.test.ts +47 -0
  36. package/agent/codeMailbox.test.ts +76 -0
  37. package/agent/codeSessionFork.test.ts +58 -0
  38. package/agent/codeSessionIndex.test.ts +77 -0
  39. package/agent/consoleToStderr.ts +8 -0
  40. package/agent/jsonLines.ts +29 -0
  41. package/agent/stringArg.ts +5 -0
  42. package/bunfig.toml +2 -0
  43. package/feedback/DevLogFeedback.ts +82 -0
  44. package/feedback/PreviewFeedback.ts +46 -0
  45. package/feedback/TurnFeedback.ts +98 -0
  46. package/feedback/VerifyFeedback.ts +39 -0
  47. package/host/AkanCodeRunner.ts +297 -0
  48. package/host/CodeTrustPrompt.ts +57 -0
  49. package/host/codeRunnerPrompt.test.ts +181 -0
  50. package/host/hostGraph.test.ts +33 -0
  51. package/host/index.ts +2 -0
  52. package/index.ts +49 -0
  53. package/package.json +43 -9
  54. package/piDependencyPins.test.ts +45 -0
  55. package/test/preload.ts +3 -0
  56. package/tools/AkanCli.ts +56 -0
  57. package/tools/AkanCodePlugins.ts +145 -0
  58. package/tools/AkanEditScope.ts +53 -0
  59. package/tools/AkanEnvKeys.ts +50 -0
  60. package/tools/AkanToolPack.ts +87 -0
  61. package/tools/AkanVerifier.ts +30 -0
  62. package/tools/AskToolPack.ts +99 -0
  63. package/tools/DeepSeekWeb.ts +127 -0
  64. package/tools/MailToolPack.ts +76 -0
  65. package/tools/McpClient.ts +209 -0
  66. package/tools/McpOAuth.ts +233 -0
  67. package/tools/McpOAuthLoopback.ts +64 -0
  68. package/tools/McpServerConfig.ts +131 -0
  69. package/tools/McpSignIn.ts +158 -0
  70. package/tools/McpTokenStore.ts +128 -0
  71. package/tools/McpToolPack.ts +206 -0
  72. package/tools/SessionToolPack.ts +91 -0
  73. package/tools/WebToolPack.ts +315 -0
  74. package/tools/akanCodePlugins.test.ts +954 -0
  75. package/tools/askToolPack.test.ts +116 -0
  76. package/tools/deepSeekWeb.test.ts +113 -0
  77. package/tools/mcpOAuth.test.ts +648 -0
  78. package/tools/mcpServerConfig.test.ts +341 -0
  79. package/tsconfig.json +29 -0
  80. package/tui/CodeTui.tsx +394 -0
  81. package/tui/CodeTuiAgents.ts +65 -0
  82. package/tui/CodeTuiApp.test.tsx +251 -0
  83. package/tui/CodeTuiApp.tsx +312 -0
  84. package/tui/CodeTuiAutoCompact.ts +33 -0
  85. package/tui/CodeTuiClipboard.ts +94 -0
  86. package/tui/CodeTuiCommandRunner.ts +242 -0
  87. package/tui/CodeTuiCommands.ts +59 -0
  88. package/tui/CodeTuiEditor.ts +168 -0
  89. package/tui/CodeTuiFiles.ts +45 -0
  90. package/tui/CodeTuiFrame.ts +133 -0
  91. package/tui/CodeTuiLines.ts +117 -0
  92. package/tui/CodeTuiMarkdown.ts +159 -0
  93. package/tui/CodeTuiMcp.ts +111 -0
  94. package/tui/CodeTuiModels.ts +82 -0
  95. package/tui/CodeTuiMouse.ts +39 -0
  96. package/tui/CodeTuiOverlay.ts +148 -0
  97. package/tui/CodeTuiParts.ts +168 -0
  98. package/tui/CodeTuiPrompt.ts +271 -0
  99. package/tui/CodeTuiQuestion.ts +170 -0
  100. package/tui/codeTranscript.test.ts +445 -0
  101. package/tui/codeTui.test.tsx +1104 -0
  102. package/tui/codeTuiAgents.test.ts +61 -0
  103. package/tui/codeTuiClipboard.test.ts +16 -0
  104. package/tui/codeTuiCommands.test.ts +38 -0
  105. package/tui/codeTuiEditor.test.ts +122 -0
  106. package/tui/codeTuiFiles.test.ts +43 -0
  107. package/tui/codeTuiMarkdown.test.ts +91 -0
  108. package/tui/codeTuiMcp.test.ts +160 -0
  109. package/tui/codeTuiMouse.test.ts +61 -0
@@ -0,0 +1,372 @@
1
+ import path from "node:path";
2
+
3
+ interface ShellWord {
4
+ text: string;
5
+ expands: boolean;
6
+ quoted: boolean;
7
+ }
8
+
9
+ type Redirect = "read" | "here" | "write" | "dup";
10
+
11
+ // Reads a shell line only as far as it is sure of: anything it does not model answers `undefined`, and the caller asks.
12
+ export class CodeAgentCommandLine {
13
+ static readonly networkClients = [
14
+ "curl",
15
+ "wget",
16
+ "nc",
17
+ "ncat",
18
+ "netcat",
19
+ "socat",
20
+ "telnet",
21
+ "ssh",
22
+ "scp",
23
+ "sftp",
24
+ "rsync",
25
+ "ftp",
26
+ ];
27
+ static readonly wrappers = [
28
+ "sudo",
29
+ "env",
30
+ "command",
31
+ "exec",
32
+ "nohup",
33
+ "time",
34
+ "timeout",
35
+ "nice",
36
+ "watch",
37
+ "stdbuf",
38
+ "xargs",
39
+ ];
40
+ // A wrapper or a shell runs whatever it is handed, so its name says nothing; `rm` and what leaves the machine cannot be undone.
41
+ static readonly alwaysAsked = new Set([
42
+ ...CodeAgentCommandLine.networkClients,
43
+ ...CodeAgentCommandLine.wrappers,
44
+ "sh",
45
+ "bash",
46
+ "zsh",
47
+ "dash",
48
+ "ksh",
49
+ "fish",
50
+ "eval",
51
+ "builtin",
52
+ "source",
53
+ ".",
54
+ "trap",
55
+ "alias",
56
+ "coproc",
57
+ "export",
58
+ "declare",
59
+ "typeset",
60
+ "readonly",
61
+ "rm",
62
+ "git push",
63
+ "npm publish",
64
+ "pnpm publish",
65
+ "yarn publish",
66
+ "yarn npm",
67
+ "bun publish",
68
+ "cargo publish",
69
+ "docker push",
70
+ "gh api",
71
+ ]);
72
+ // A variable in front of a command can change what that command runs, so only these are read past.
73
+ static readonly harmlessVariables = new Set([
74
+ "CI",
75
+ "NODE_ENV",
76
+ "FORCE_COLOR",
77
+ "NO_COLOR",
78
+ "TZ",
79
+ "LANG",
80
+ "LC_ALL",
81
+ "TERM",
82
+ "DEBUG",
83
+ "PORT",
84
+ ]);
85
+ // `gh` groups its verbs one level down: `gh pr view` and `gh pr merge` are different commands.
86
+ static readonly #subcommandDepth = new Map([
87
+ ["git", 1],
88
+ ["bun", 1],
89
+ ["bunx", 1],
90
+ ["npm", 1],
91
+ ["npx", 1],
92
+ ["pnpm", 1],
93
+ ["yarn", 1],
94
+ ["akan", 1],
95
+ ["docker", 1],
96
+ ["kubectl", 1],
97
+ ["helm", 1],
98
+ ["cargo", 1],
99
+ ["go", 1],
100
+ ["gh", 2],
101
+ ]);
102
+ static readonly #reserved = new Set([
103
+ "if",
104
+ "then",
105
+ "else",
106
+ "elif",
107
+ "fi",
108
+ "for",
109
+ "while",
110
+ "until",
111
+ "do",
112
+ "done",
113
+ "case",
114
+ "esac",
115
+ "select",
116
+ "function",
117
+ "in",
118
+ "coproc",
119
+ ]);
120
+ static readonly #runsItsArguments = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
121
+ static readonly #assignment = /^([A-Za-z_]\w*)(\+?=)(.*)$/s;
122
+ static readonly #plainValue = /^[\w@%+.,:/*-]*$/;
123
+ // bash opens a redirection to `/dev/tcp/<host>/<port>` or `/dev/udp/…` as a connection, not a file.
124
+ static readonly #socketPath = /^\/+dev\/+(?:tcp|udp)\//i;
125
+ static readonly #program = /^[\w@%+.,:/~-]+$/;
126
+ static readonly #subcommand = /^[A-Za-z0-9@][\w@.:/-]*$/;
127
+ static readonly #redirectOperator = /^(?:<<<|<<|<>|<&|<|>>|>&|>\||>)/;
128
+
129
+ readonly #line: string;
130
+ readonly #commands: ShellWord[][] = [];
131
+ #at: number;
132
+ #words: ShellWord[] = [];
133
+ #word: ShellWord | undefined;
134
+ #redirect: Redirect | undefined;
135
+
136
+ private constructor(line: string, at = 0) {
137
+ this.#line = line;
138
+ this.#at = at;
139
+ }
140
+
141
+ static allowable(line: string): string[] | undefined {
142
+ const parsed = new CodeAgentCommandLine(line);
143
+ if (!parsed.#read()) return undefined;
144
+ const names: string[] = [];
145
+ for (const words of parsed.#commands) {
146
+ const name = CodeAgentCommandLine.#nameOf(words);
147
+ if (!name) return undefined;
148
+ names.push(name);
149
+ }
150
+ return names.length ? [...new Set(names)] : undefined;
151
+ }
152
+
153
+ static #nameOf(words: ShellWord[]) {
154
+ const [program] = words;
155
+ if (!program || program.expands || !CodeAgentCommandLine.#program.test(program.text)) return undefined;
156
+ // Lowercased: a case-insensitive disk runs `CURL` as `curl`.
157
+ const base = path.posix.basename(program.text).toLowerCase();
158
+ if (CodeAgentCommandLine.#reserved.has(base) || CodeAgentCommandLine.alwaysAsked.has(base)) return undefined;
159
+ if (words.some((word) => CodeAgentCommandLine.#runsItsArguments.has(word.text))) return undefined;
160
+ // docker also pushes as `docker image push`, `docker compose push` and `docker build --push`.
161
+ if (base === "docker" && words.some((word) => word.text === "push" || word.text.startsWith("--push")))
162
+ return undefined;
163
+ const depth = CodeAgentCommandLine.#subcommandDepth.get(base);
164
+ if (!depth) return program.text;
165
+ // The words right after the program, or nothing: `git -C <dir> push` would otherwise be named `git <dir>`.
166
+ const subs = words.slice(1, 1 + depth);
167
+ if (!subs.length || subs.some((sub) => sub.expands || !CodeAgentCommandLine.#subcommand.test(sub.text)))
168
+ return undefined;
169
+ const names = subs.map((_, idx) =>
170
+ subs
171
+ .slice(0, idx + 1)
172
+ .map((sub) => sub.text)
173
+ .join(" "),
174
+ );
175
+ if (names.some((name) => CodeAgentCommandLine.alwaysAsked.has(`${base} ${name}`))) return undefined;
176
+ return `${program.text} ${names.at(-1)}`;
177
+ }
178
+
179
+ static #harmless(word: ShellWord) {
180
+ const [, name = "", operator, value = ""] = CodeAgentCommandLine.#assignment.exec(word.text) ?? [];
181
+ if (operator !== "=" || word.quoted || word.expands) return false;
182
+ return CodeAgentCommandLine.harmlessVariables.has(name) && CodeAgentCommandLine.#plainValue.test(value);
183
+ }
184
+
185
+ #read(close?: ")"): boolean {
186
+ while (this.#at < this.#line.length) {
187
+ const char = this.#line[this.#at] ?? "";
188
+ if (char === close) {
189
+ this.#at += 1;
190
+ return this.#endCommand();
191
+ }
192
+ if (!this.#step(char)) return false;
193
+ }
194
+ return close === undefined && this.#endCommand();
195
+ }
196
+
197
+ #step(char: string): boolean {
198
+ const next = this.#line[this.#at + 1];
199
+ switch (char) {
200
+ case " ":
201
+ case "\t":
202
+ this.#at += 1;
203
+ return this.#endWord();
204
+ case "\n":
205
+ case ";":
206
+ this.#at += 1;
207
+ return this.#endCommand();
208
+ case "&":
209
+ if (next === ">") {
210
+ this.#at += 1;
211
+ return this.#endWord() && this.#redirection();
212
+ }
213
+ this.#at += next === "&" ? 2 : 1;
214
+ return this.#endCommand();
215
+ case "|":
216
+ this.#at += next === "|" || next === "&" ? 2 : 1;
217
+ return this.#endCommand();
218
+ case "(":
219
+ if (this.#word) return false;
220
+ this.#at += 1;
221
+ return this.#endCommand() && this.#nested();
222
+ case "<":
223
+ case ">":
224
+ return this.#redirection();
225
+ case "'":
226
+ return this.#single();
227
+ case '"':
228
+ return this.#double();
229
+ case "$":
230
+ return this.#dollar();
231
+ case ")":
232
+ case "`":
233
+ return false;
234
+ case "\\":
235
+ if (next === undefined) return false;
236
+ this.#at += 2;
237
+ if (next === "\n") return true;
238
+ this.#quote();
239
+ this.#append(next);
240
+ return true;
241
+ case "#":
242
+ if (this.#word) break;
243
+ while (this.#at < this.#line.length && this.#line[this.#at] !== "\n") this.#at += 1;
244
+ return true;
245
+ }
246
+ this.#at += 1;
247
+ this.#append(char);
248
+ return true;
249
+ }
250
+
251
+ #append(text: string) {
252
+ this.#word ??= { text: "", expands: false, quoted: false };
253
+ this.#word.text += text;
254
+ }
255
+
256
+ #quote() {
257
+ this.#append("");
258
+ if (this.#word) this.#word.quoted = true;
259
+ }
260
+
261
+ #expand() {
262
+ this.#append("");
263
+ if (this.#word) this.#word.expands = true;
264
+ }
265
+
266
+ #endWord(): boolean {
267
+ const word = this.#word;
268
+ const redirect = this.#redirect;
269
+ if (!word) return true;
270
+ this.#word = undefined;
271
+ if (!redirect) {
272
+ this.#words.push(word);
273
+ return true;
274
+ }
275
+ this.#redirect = undefined;
276
+ if (redirect === "here") return true;
277
+ if (word.expands) return false;
278
+ if (redirect === "read") return !CodeAgentCommandLine.#socketPath.test(word.text);
279
+ // A file written through a redirection is outside what a command's name covers, wherever the file is.
280
+ return redirect === "dup" ? /^(?:\d+|-)$/.test(word.text) : word.text === "/dev/null";
281
+ }
282
+
283
+ #endCommand(): boolean {
284
+ if (!this.#endWord() || this.#redirect) return false;
285
+ const from = this.#words.findIndex((word) => !CodeAgentCommandLine.#assignment.test(word.text));
286
+ const assigned = from < 0 ? this.#words : this.#words.slice(0, from);
287
+ if (!assigned.every((word) => CodeAgentCommandLine.#harmless(word))) return false;
288
+ if (from >= 0) this.#commands.push(this.#words.slice(from));
289
+ this.#words = [];
290
+ return true;
291
+ }
292
+
293
+ #redirection(): boolean {
294
+ if (this.#word && !this.#word.expands && !this.#word.quoted && /^\d+$/.test(this.#word.text))
295
+ this.#word = undefined;
296
+ else if (!this.#endWord()) return false;
297
+ const operator = CodeAgentCommandLine.#redirectOperator.exec(this.#line.slice(this.#at, this.#at + 3))?.[0] ?? "";
298
+ this.#at += operator.length;
299
+ if (!operator || operator === "<<" || this.#redirect || this.#line[this.#at] === "(") return false;
300
+ if (operator === "<<<") this.#redirect = "here";
301
+ else if (operator === "<") this.#redirect = "read";
302
+ else this.#redirect = operator.endsWith("&") ? "dup" : "write";
303
+ return true;
304
+ }
305
+
306
+ #single(): boolean {
307
+ const end = this.#line.indexOf("'", this.#at + 1);
308
+ if (end < 0) return false;
309
+ this.#quote();
310
+ this.#append(this.#line.slice(this.#at + 1, end));
311
+ this.#at = end + 1;
312
+ return true;
313
+ }
314
+
315
+ #double(): boolean {
316
+ this.#at += 1;
317
+ this.#quote();
318
+ while (this.#at < this.#line.length) {
319
+ const char = this.#line[this.#at] ?? "";
320
+ if (char === '"') {
321
+ this.#at += 1;
322
+ return true;
323
+ }
324
+ if (char === "`") return false;
325
+ if (char === "$") {
326
+ if (!this.#dollar()) return false;
327
+ continue;
328
+ }
329
+ if (char !== "\\") {
330
+ this.#at += 1;
331
+ this.#append(char);
332
+ continue;
333
+ }
334
+ const next = this.#line[this.#at + 1];
335
+ if (next === undefined) return false;
336
+ this.#at += 2;
337
+ if (next !== "\n") this.#append('$`"\\'.includes(next) ? next : `\\${next}`);
338
+ }
339
+ return false;
340
+ }
341
+
342
+ #dollar(): boolean {
343
+ const rest = this.#line.slice(this.#at + 1);
344
+ // `$((…))` is arithmetic, and `$'…'` decodes escapes into characters this reader would not see.
345
+ if (rest.startsWith("((") || rest.startsWith("'") || rest.startsWith('"')) return false;
346
+ if (rest.startsWith("(")) {
347
+ this.#at += 2;
348
+ this.#expand();
349
+ return this.#nested();
350
+ }
351
+ if (rest.startsWith("{")) {
352
+ const end = rest.indexOf("}");
353
+ if (end < 0 || /[$`]/.test(rest.slice(1, end))) return false;
354
+ this.#at += end + 2;
355
+ this.#expand();
356
+ return true;
357
+ }
358
+ const name = /^(?:\w+|[?!#@*$-])/.exec(rest)?.[0];
359
+ this.#at += 1 + (name?.length ?? 0);
360
+ if (name) this.#expand();
361
+ else this.#append("$");
362
+ return true;
363
+ }
364
+
365
+ #nested(): boolean {
366
+ const inner = new CodeAgentCommandLine(this.#line, this.#at);
367
+ const read = inner.#read(")");
368
+ this.#at = inner.#at;
369
+ this.#commands.push(...inner.#commands);
370
+ return read;
371
+ }
372
+ }
@@ -0,0 +1,225 @@
1
+ import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ type CodeAgentEventBody,
4
+ type CodeAgentStopReason,
5
+ type CodeAgentToolOp,
6
+ type CodeAgentToolSummary,
7
+ codeAgentClip,
8
+ codeAgentLabelChars,
9
+ codeAgentOutputChars,
10
+ } from "akanjs/common";
11
+ import { stringArg } from "./stringArg";
12
+
13
+ const toolOps: { [key: string]: CodeAgentToolOp } = {
14
+ read: "read",
15
+ write: "write",
16
+ edit: "write",
17
+ ls: "list",
18
+ find: "search",
19
+ grep: "search",
20
+ bash: "execute",
21
+ };
22
+
23
+ // A turn is one prompt: the engine's `turn_start` fires per LLM round trip, so `agent_start`/`agent_end` bound it.
24
+ export class CodeAgentEventMapper {
25
+ #turn = 0;
26
+ #turnId = "";
27
+ #outcome: CodeAgentStopReason | undefined;
28
+ readonly #openTools = new Map<string, CodeAgentToolSummary>();
29
+ readonly #blocked = new Map<string, string>();
30
+
31
+ get turnId() {
32
+ return this.#turnId;
33
+ }
34
+
35
+ map(event: AgentSessionEvent): CodeAgentEventBody[] {
36
+ switch (event.type) {
37
+ case "agent_start":
38
+ this.#turn += 1;
39
+ this.#turnId = `t${this.#turn}`;
40
+ // A hint left by an abort that hit an idle session must not colour the turn after it.
41
+ this.#outcome = undefined;
42
+ return [{ type: "turn_start", turnId: this.#turnId }];
43
+ case "agent_end":
44
+ // `turn_end` is last by contract; the engine finalizes the message before the run ends, even on abort.
45
+ return [
46
+ ...this.flushBlocked(),
47
+ { type: "turn_end", turnId: this.#turnId, stopReason: this.#stopReason(event) },
48
+ ];
49
+ case "agent_settled":
50
+ return [{ type: "idle" }];
51
+ case "message_update":
52
+ return this.#mapDelta(event);
53
+ case "message_end":
54
+ return this.#mapMessage(event);
55
+ case "tool_execution_start": {
56
+ const tool = this.#summary(event.toolCallId, event.toolName, event.args);
57
+ this.#openTools.set(event.toolCallId, tool);
58
+ return [{ type: "tool_start", turnId: this.#turnId, tool }];
59
+ }
60
+ case "tool_execution_update":
61
+ return [
62
+ {
63
+ type: "tool_progress",
64
+ turnId: this.#turnId,
65
+ toolCallId: event.toolCallId,
66
+ text: codeAgentClip(CodeAgentEventMapper.#renderToolText(event.partialResult), codeAgentLabelChars),
67
+ },
68
+ ];
69
+ case "tool_execution_end":
70
+ return [this.#mapToolEnd(event)];
71
+ case "queue_update":
72
+ return [{ type: "queue", steering: [...event.steering], followUp: [...event.followUp] }];
73
+ case "compaction_start":
74
+ return [{ type: "compaction", phase: "start", reason: event.reason }];
75
+ case "compaction_end":
76
+ return [
77
+ {
78
+ type: "compaction",
79
+ phase: "end",
80
+ reason: event.reason,
81
+ ...(event.errorMessage ? { error: event.errorMessage } : {}),
82
+ ...(event.aborted ? { aborted: true } : {}),
83
+ },
84
+ ];
85
+ case "auto_retry_start":
86
+ return [
87
+ {
88
+ type: "retry",
89
+ attempt: event.attempt,
90
+ maxAttempts: event.maxAttempts,
91
+ delayMs: event.delayMs,
92
+ message: event.errorMessage,
93
+ },
94
+ ];
95
+ default:
96
+ return [];
97
+ }
98
+ }
99
+
100
+ // The engine sends a blocked call no start event, only an `isError` end: synthesise the start, relabel the end.
101
+ markBlocked(toolCallId: string, toolName: string, args: unknown, reason: string): CodeAgentEventBody[] {
102
+ this.#blocked.set(toolCallId, reason);
103
+ if (this.#openTools.has(toolCallId)) return [];
104
+ const tool = this.#summary(toolCallId, toolName, args);
105
+ this.#openTools.set(toolCallId, tool);
106
+ return [{ type: "tool_start", turnId: this.#turnId, tool }];
107
+ }
108
+
109
+ /** A refusal the engine never closed would leave a row open forever, so the turn boundary sweeps them. */
110
+ flushBlocked(): CodeAgentEventBody[] {
111
+ const frames: CodeAgentEventBody[] = [];
112
+ for (const [toolCallId, reason] of this.#blocked) {
113
+ const tool = this.#openTools.get(toolCallId);
114
+ if (!tool) continue;
115
+ this.#openTools.delete(toolCallId);
116
+ frames.push({
117
+ type: "tool_end",
118
+ turnId: this.#turnId,
119
+ tool,
120
+ outcome: "blocked",
121
+ output: reason,
122
+ truncated: false,
123
+ });
124
+ }
125
+ this.#blocked.clear();
126
+ return frames;
127
+ }
128
+
129
+ #mapToolEnd(event: Extract<AgentSessionEvent, { type: "tool_execution_end" }>): CodeAgentEventBody {
130
+ const tool = this.#openTools.get(event.toolCallId) ?? this.#summary(event.toolCallId, event.toolName, undefined);
131
+ this.#openTools.delete(event.toolCallId);
132
+ const reason = this.#blocked.get(event.toolCallId);
133
+ this.#blocked.delete(event.toolCallId);
134
+ const full = reason ?? CodeAgentEventMapper.#renderToolText(event.result);
135
+ return {
136
+ type: "tool_end",
137
+ turnId: this.#turnId,
138
+ tool,
139
+ outcome: reason ? "blocked" : event.isError ? "error" : "ok",
140
+ output: codeAgentClip(full, codeAgentOutputChars),
141
+ truncated: full.length > codeAgentOutputChars,
142
+ };
143
+ }
144
+
145
+ /** Consumed once, by the next `agent_end`, and wins over the engine's own stop reason. */
146
+ noteOutcome(reason: CodeAgentStopReason) {
147
+ this.#outcome = reason;
148
+ }
149
+
150
+ // The engine reports an interrupted stream as `stop`, so the core's own note wins and the engine's is a fallback.
151
+ #stopReason(event: Extract<AgentSessionEvent, { type: "agent_end" }>): CodeAgentStopReason {
152
+ const noted = this.#outcome;
153
+ this.#outcome = undefined;
154
+ if (noted) return noted;
155
+ if (event.willRetry) return "error";
156
+ const last = event.messages.at(-1) as { stopReason?: string } | undefined;
157
+ if (last?.stopReason === "aborted") return "aborted";
158
+ if (last?.stopReason === "error") return "error";
159
+ // `length` is the model hitting its output cap: a half-written answer must not be stored as `done`.
160
+ if (last?.stopReason === "length") return "truncated";
161
+ return "done";
162
+ }
163
+
164
+ #summary(toolCallId: string, name: string, args: unknown): CodeAgentToolSummary {
165
+ const path = stringArg(args, "path");
166
+ return {
167
+ toolCallId,
168
+ name,
169
+ op: toolOps[name] ?? "other",
170
+ ...(path ? { path } : {}),
171
+ title: codeAgentClip(`${name}${CodeAgentEventMapper.#renderArgs(args)}`, codeAgentLabelChars),
172
+ };
173
+ }
174
+
175
+ #mapDelta(event: Extract<AgentSessionEvent, { type: "message_update" }>): CodeAgentEventBody[] {
176
+ const inner = event.assistantMessageEvent;
177
+ if (inner.type === "text_delta") return [{ type: "text_delta", turnId: this.#turnId, text: inner.delta }];
178
+ if (inner.type === "thinking_delta") return [{ type: "thinking_delta", turnId: this.#turnId, text: inner.delta }];
179
+ return [];
180
+ }
181
+
182
+ #mapMessage(event: Extract<AgentSessionEvent, { type: "message_end" }>): CodeAgentEventBody[] {
183
+ const message = event.message as { role?: string; content?: unknown };
184
+ if (message.role !== "assistant" && message.role !== "user") return [];
185
+ const text = CodeAgentEventMapper.#renderContent(message.content);
186
+ if (!text) return [];
187
+ return [{ type: "message", turnId: this.#turnId, role: message.role, text }];
188
+ }
189
+
190
+ static #renderArgs(args: unknown) {
191
+ if (!args || typeof args !== "object") return "";
192
+ const entries = Object.entries(args as Record<string, unknown>).filter(([, value]) => value !== undefined);
193
+ if (!entries.length) return "";
194
+ const rendered = entries.map(([key, value]) => `${key}=${CodeAgentEventMapper.#renderArgValue(value)}`).join(" ");
195
+ return `(${codeAgentClip(rendered, 120)})`;
196
+ }
197
+
198
+ // By shape, not `String()`, which renders an `edit` call's replacement list as `[object Object]`s.
199
+ static #renderArgValue(value: unknown) {
200
+ if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? "" : "s"}`;
201
+ if (value && typeof value === "object") {
202
+ const keys = Object.keys(value as Record<string, unknown>).length;
203
+ return `{${keys} key${keys === 1 ? "" : "s"}}`;
204
+ }
205
+ return codeAgentClip(String(value), 60);
206
+ }
207
+
208
+ static #renderContent(content: unknown): string {
209
+ if (typeof content === "string") return content;
210
+ if (!Array.isArray(content)) return "";
211
+ return content
212
+ .filter(
213
+ (part): part is { type: string; text: string } => !!part && typeof part === "object" && part.type === "text",
214
+ )
215
+ .map((part) => part.text)
216
+ .join("");
217
+ }
218
+
219
+ static #renderToolText(value: unknown): string {
220
+ if (typeof value === "string") return value;
221
+ if (value && typeof value === "object" && "content" in value)
222
+ return CodeAgentEventMapper.#renderContent((value as { content: unknown }).content);
223
+ return value === undefined ? "" : JSON.stringify(value);
224
+ }
225
+ }
@@ -0,0 +1,57 @@
1
+ import type { CodeAgentEvent, CodeAgentEventBody } from "akanjs/common";
2
+
3
+ export class CodeAgentFrames {
4
+ /** One turn's worth of frames is kept for reconnection; a client further behind reloads the transcript. */
5
+ static readonly replayLimit = 2_000;
6
+ readonly #listeners = new Set<(event: CodeAgentEvent) => void>();
7
+ // Cleared at `idle`: an earlier turn is in the transcript; only the turn in flight exists nowhere else.
8
+ readonly #replay: CodeAgentEvent[] = [];
9
+ #replayFrom = 0;
10
+ #seq = 0;
11
+ #lastContextTokens: number | undefined;
12
+
13
+ get replayFrom() {
14
+ return this.#replayFrom;
15
+ }
16
+
17
+ since(seq: number) {
18
+ return this.#replay.filter((event) => event.seq > seq);
19
+ }
20
+
21
+ on(listener: (event: CodeAgentEvent) => void) {
22
+ this.#listeners.add(listener);
23
+ return () => this.#listeners.delete(listener);
24
+ }
25
+
26
+ emit(body: CodeAgentEventBody) {
27
+ this.#seq += 1;
28
+ const event = { ...body, seq: this.#seq } as CodeAgentEvent;
29
+ this.#remember(event);
30
+ for (const listener of this.#listeners) listener(event);
31
+ }
32
+
33
+ emitContext(usage: { tokens: number | null; contextWindow?: number } | undefined) {
34
+ // `== null` on purpose: typed `number | null`, but `undefined` must not emit `used: undefined`.
35
+ if (usage?.tokens == null) return;
36
+ if (usage.tokens === this.#lastContextTokens) return;
37
+ this.#lastContextTokens = usage.tokens;
38
+ this.emit({ type: "context", used: usage.tokens, max: usage.contextWindow || undefined });
39
+ }
40
+
41
+ clear() {
42
+ this.#listeners.clear();
43
+ }
44
+
45
+ #remember(event: CodeAgentEvent) {
46
+ if (event.type === "idle") {
47
+ this.#replay.length = 0;
48
+ this.#replayFrom = event.seq;
49
+ return;
50
+ }
51
+ this.#replay.push(event);
52
+ while (this.#replay.length > CodeAgentFrames.replayLimit) {
53
+ const dropped = this.#replay.shift();
54
+ this.#replayFrom = dropped?.seq ?? this.#replayFrom;
55
+ }
56
+ }
57
+ }