@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,626 +0,0 @@
1
- import {
2
- type AgentSession,
3
- createAgentSession,
4
- DefaultResourceLoader,
5
- type ExtensionAPI,
6
- type InlineExtension,
7
- type ToolDefinition,
8
- } from "@earendil-works/pi-coding-agent";
9
- import {
10
- type CodeAgentAnswer,
11
- type CodeAgentEffort,
12
- type CodeAgentEvent,
13
- type CodeAgentEventBody,
14
- type CodeAgentImage,
15
- type CodeAgentMcpStatus,
16
- type CodeAgentProfile,
17
- type CodeAgentProviderInfo,
18
- type CodeAgentQuestion,
19
- type CodeAgentSessionInfo,
20
- type CodeAgentState,
21
- codeAgentClip,
22
- codeAgentLabelChars,
23
- codeAgentRenderAnswer,
24
- codeAgentSessionName,
25
- } from "akanjs/common";
26
- import type { Workspace } from "../../commandDecorators";
27
- import { AkanCodePlugins } from "../tools/AkanCodePlugins";
28
- import { DeepSeekWeb } from "../tools/DeepSeekWeb";
29
- import { AkanCodeCompaction } from "./AkanCodeCompaction";
30
- import { AkanCodeServices } from "./AkanCodeServices";
31
- import {
32
- akanCodeModel,
33
- akanCodeModelSupportsImages,
34
- akanCodeModelWarnings,
35
- type CodeAgentModelRef,
36
- } from "./akanCodeModel";
37
- import { akanCodePaths } from "./akanCodePaths";
38
- import { CodeAgentAsks } from "./CodeAgentAsks";
39
- import { CodeAgentEventMapper } from "./CodeAgentEventMapper";
40
- import { CodeAgentGate } from "./CodeAgentGate";
41
- import { CodeAgentProxy } from "./CodeAgentProxy";
42
- import { CodeAgentSuspended } from "./CodeAgentSuspended";
43
- import { CodeAgentUi } from "./CodeAgentUi";
44
- import { CodeMailbox } from "./CodeMailbox";
45
- import { CodeSessionFork } from "./CodeSessionFork";
46
- import { CodeSessionIndex } from "./CodeSessionIndex";
47
- import type { SubagentSpend } from "./SubagentPool";
48
-
49
- // The engine's run-mode type is not re-exported from its package entry, so the literal set is restated.
50
- export type CodeAgentHostMode = "tui" | "rpc" | "json" | "print";
51
-
52
- export interface CodeAgentOptions {
53
- workspace: Workspace;
54
- cwd?: string;
55
- profile: CodeAgentProfile;
56
- model?: CodeAgentModelRef;
57
- /** Percent of the context window that starts a compaction, in steps of 10. */
58
- autoCompactAt?: number;
59
- /** Apps whose dev server and preview the turn-end feedback loop watches. */
60
- apps?: string[];
61
- extensions?: InlineExtension[];
62
- customTools?: ToolDefinition[];
63
- /** `print` for a one-shot stream, `rpc` when a host drives this process over stdio. */
64
- mode?: CodeAgentHostMode;
65
- /** How many `task` tools deep this agent already is. */
66
- depth?: number;
67
- /** The tally (tokens spent, sub-agents running) of the sub-agent tree whose `task` opened this agent. */
68
- subagentSpend?: SubagentSpend;
69
- /** Id of a stored session to continue instead of opening a new one. */
70
- resume?: string;
71
- }
72
-
73
- const textOf = (content: unknown) => {
74
- if (typeof content === "string") return content.trim();
75
- if (!Array.isArray(content)) return "";
76
- return content
77
- .map((part) => (typeof part === "object" && part && "text" in part ? String(part.text) : ""))
78
- .join("")
79
- .trim();
80
- };
81
-
82
- export class CodeAgent {
83
- readonly #profile: CodeAgentProfile;
84
- readonly #gate: CodeAgentGate;
85
- readonly #mapper = new CodeAgentEventMapper();
86
- readonly #asks = new CodeAgentAsks();
87
- #suspended = new CodeAgentSuspended(null);
88
- readonly #listeners = new Set<(event: CodeAgentEvent) => void>();
89
- #session: AgentSession | undefined;
90
- #disposePlugins: (() => void) | undefined;
91
- #seq = 0;
92
- #disposed = false;
93
- #sessionDir: string | undefined;
94
- #mailbox: CodeMailbox | undefined;
95
- #mcp: CodeAgentMcpStatus[] = [];
96
- #workspaceRoot = "";
97
- // Cleared at `idle`: an earlier turn is in the transcript; only the turn in flight exists nowhere else.
98
- readonly #replay: CodeAgentEvent[] = [];
99
- #replayFrom = 0;
100
- #lastContextTokens: number | undefined;
101
- #autoCompactAt: number | undefined;
102
-
103
- private constructor(profile: CodeAgentProfile) {
104
- this.#profile = profile;
105
- this.#gate = new CodeAgentGate(profile);
106
- }
107
-
108
- static async create(options: CodeAgentOptions) {
109
- const workspaceRoot = options.workspace.workspaceRoot;
110
- const cwd = options.cwd ?? workspaceRoot;
111
- const agent = new CodeAgent(options.profile);
112
- const autoCompactAt = AkanCodeCompaction.normalize(options.autoCompactAt);
113
- const settingsManager = AkanCodeServices.settings();
114
- const proxy = CodeAgentProxy.fromEnv(options.profile);
115
- const modelRuntime = await AkanCodeServices.runtime(workspaceRoot, proxy);
116
- const model = await akanCodeModel(modelRuntime, options.model);
117
- const compaction = settingsManager.getCompactionSettings(model);
118
- const modelWarnings = akanCodeModelWarnings(model, compaction.reserveTokens + compaction.keepRecentTokens);
119
-
120
- const akan = await AkanCodePlugins.build({
121
- workspace: options.workspace,
122
- cwd,
123
- profile: options.profile,
124
- apps: options.apps ?? [],
125
- canSeeImages: akanCodeModelSupportsImages(model),
126
- model: () => {
127
- const current = agent.#session?.model;
128
- return current ? { provider: current.provider, id: current.id } : undefined;
129
- },
130
- deepseek: await DeepSeekWeb.fromRuntime(modelRuntime, !!proxy),
131
- depth: options.depth ?? 0,
132
- ...(options.subagentSpend ? { subagentSpend: options.subagentSpend } : {}),
133
- currentSessionId: () => agent.sessionId,
134
- mailbox: () => agent.#mailbox,
135
- onNotice: (message) => agent.#emit({ type: "notice", level: "warning", message }),
136
- onAgents: (agents) => agent.#emit({ type: "subagent", agents }),
137
- onAsk: (question) => agent.ask(question),
138
- });
139
-
140
- const resourceLoader = new DefaultResourceLoader({
141
- cwd,
142
- agentDir: akanCodePaths.globalDir(),
143
- settingsManager,
144
- ...AkanCodeServices.resourceOptions({
145
- workspaceRoot,
146
- cwd,
147
- profile: options.profile,
148
- extensions: [agent.#gateExtension(), ...akan.extensions, ...(options.extensions ?? [])],
149
- }),
150
- });
151
- await resourceLoader.reload();
152
-
153
- const { session } = await createAgentSession({
154
- cwd,
155
- agentDir: akanCodePaths.globalDir(),
156
- modelRuntime,
157
- settingsManager,
158
- resourceLoader,
159
- model,
160
- sessionManager: AkanCodeServices.sessions(workspaceRoot, cwd, options.profile, options.resume),
161
- noTools: "builtin",
162
- tools: [...options.profile.tools.builtin, ...akan.toolNames],
163
- customTools: options.customTools,
164
- });
165
- agent.#disposePlugins = akan.dispose;
166
- agent.#mcp = akan.mcp;
167
- agent.#workspaceRoot = workspaceRoot;
168
- if (options.profile.session.store !== "memory") agent.#sessionDir = akanCodePaths.sessionsDir(workspaceRoot);
169
- await agent.#attach(session, options.mode ?? "print");
170
- const autoCompactWarning = agent.#fitAutoCompact(autoCompactAt);
171
- agent.#suspended = new CodeAgentSuspended(CodeAgentSuspended.fileOf(agent.#sessionDir, agent.sessionId));
172
- if (agent.#sessionDir && options.profile.session.store === "file")
173
- agent.#openMail(akanCodePaths.mailDir(workspaceRoot), cwd);
174
- for (const message of [...modelWarnings, ...autoCompactWarning])
175
- agent.#emit({ type: "notice", level: "warning", message });
176
- return agent;
177
- }
178
-
179
- get profile() {
180
- return this.#profile;
181
- }
182
-
183
- get allowed() {
184
- return this.#gate.allowed;
185
- }
186
-
187
- get canSeeImages() {
188
- const model = this.#session?.model;
189
- return model ? akanCodeModelSupportsImages(model) : false;
190
- }
191
-
192
- /** The workspace's stored sessions, newest first. Empty on a profile that keeps none. */
193
- sessions() {
194
- return this.#sessionDir ? CodeSessionIndex.list(this.#sessionDir) : [];
195
- }
196
-
197
- /** The repo, which is not `profile.paths.root` — that one is narrowed to an app by `akan code --app`. */
198
- get workspaceRoot() {
199
- return this.#workspaceRoot;
200
- }
201
-
202
- /**
203
- * As assembled at creation: the tool allowlist is fixed then, so a server declared later is unreachable. A
204
- * server's `auth` still turns `required` when a call's token cannot be renewed, until a reload.
205
- */
206
- mcpServers(): CodeAgentMcpStatus[] {
207
- return this.#mcp;
208
- }
209
-
210
- /** The other `akan code` sessions running in this workspace right now. */
211
- peers() {
212
- return this.#mailbox?.peers() ?? [];
213
- }
214
-
215
- /** The peer receives the text as a prompt of its own, queued as a follow-up when it is mid-turn. */
216
- send(target: string, text: string) {
217
- const mailbox = this.#mailbox;
218
- if (!mailbox) throw new Error("This profile keeps no shared mailbox, so it has no peers.");
219
- const peer = mailbox.find(target);
220
- if (!peer) throw new Error(`No live session matches "${target}". Ask for the list first.`);
221
- mailbox.send(peer.id, text);
222
- return peer;
223
- }
224
-
225
- #openMail(dir: string, cwd: string) {
226
- const session = this.#session;
227
- if (!session) return;
228
- this.#mailbox = new CodeMailbox(dir, session.sessionId, session.sessionName ?? session.sessionId.slice(0, 8));
229
- this.#mailbox.open(cwd, (mail) => {
230
- const from = `${mail.fromName} (${mail.from.slice(0, 8)})`;
231
- this.#emit({ type: "notice", level: "info", message: `message from ${from}` });
232
- void this.#prompt(`Message from another session — ${from}:\n${mail.text}`).catch((error: unknown) =>
233
- this.#emit({ type: "notice", level: "error", message: String(error) }),
234
- );
235
- });
236
- }
237
-
238
- get sessionId() {
239
- return this.#session?.sessionId ?? "";
240
- }
241
-
242
- get isStreaming() {
243
- return this.#session?.isStreaming ?? false;
244
- }
245
-
246
- get tokensUsed() {
247
- return this.#session?.getSessionStats().tokens.total ?? 0;
248
- }
249
-
250
- get info(): CodeAgentSessionInfo {
251
- const session = this.#require();
252
- const model = session.model;
253
- return {
254
- sessionId: session.sessionId,
255
- cwd: this.#profile.paths.root,
256
- profile: this.#profile.name,
257
- model: model ? { provider: model.provider, id: model.id, name: model.name } : undefined,
258
- tools: session.getActiveToolNames(),
259
- contextTokens: model?.contextWindow,
260
- // Not `off`: that is a setting of a reasoning model, not the absence of reasoning.
261
- effort: session.supportsThinking() ? session.thinkingLevel : undefined,
262
- autoCompactAt: this.#autoCompactAt,
263
- name: session.sessionName,
264
- interaction: this.#profile.interaction,
265
- };
266
- }
267
-
268
- /** A `session` frame minted outside this counter would carry `seq: 0`, which every client drops. */
269
- announce() {
270
- this.#emit({ type: "session", info: this.info });
271
- this.#restore();
272
- //* A resumed worker says again what it is still waiting on, or a host that reattached has no card to answer.
273
- const { question, approvals } = this.#suspended;
274
- if (question) this.#emit({ type: "question", question });
275
- for (const request of approvals) this.#emit({ type: "approval", request });
276
- }
277
-
278
- // Prose only: a past turn's tool calls would redraw rows nobody waits on, against a tree that has moved since.
279
- #restore() {
280
- const session = this.#session;
281
- if (!session) return;
282
- const turnId = `restored:${session.sessionId}`;
283
- for (const message of session.messages) {
284
- if (message.role !== "user" && message.role !== "assistant") continue;
285
- const text = textOf(message.content);
286
- if (text) this.#emit({ type: "message", turnId, role: message.role, text });
287
- }
288
- this.#emitContextNow();
289
- }
290
-
291
- on(listener: (event: CodeAgentEvent) => void) {
292
- this.#listeners.add(listener);
293
- return () => this.#listeners.delete(listener);
294
- }
295
-
296
- /** One turn's worth of frames is kept for reconnection; a client further behind reloads the transcript. */
297
- static readonly replayLimit = 2_000;
298
-
299
- /** `frames` only when `sinceSeq` is given; a client behind `replayFrom` has to reload the transcript. */
300
- async state({ sinceSeq }: { sinceSeq?: number } = {}): Promise<CodeAgentState> {
301
- const base = { info: this.info, streaming: this.isStreaming, replayFrom: this.#replayFrom };
302
- if (sinceSeq === undefined) return base;
303
- return { ...base, frames: this.#replay.filter((event) => event.seq > sinceSeq) };
304
- }
305
-
306
- async prompt(message: string, images?: CodeAgentImage[]) {
307
- this.#suspended.clear();
308
- await this.#prompt(message, images);
309
- }
310
-
311
- async #prompt(message: string, images?: CodeAgentImage[]) {
312
- const session = this.#require();
313
- // From the first prompt, not the answer, so the session is not nameless while it is worth watching.
314
- if (!session.sessionName && message.trim()) this.setName(codeAgentSessionName(message));
315
- const attachments = await CodeAgent.#attachments(images);
316
- const options = attachments.length ? { images: attachments } : {};
317
- if (session.isStreaming) return await session.prompt(message, { ...options, streamingBehavior: "followUp" });
318
- await session.prompt(message, { ...options, source: "extension" });
319
- }
320
-
321
- async abort() {
322
- // The engine finalizes an interrupted message as an ordinary stop, so the abort is noted here.
323
- this.#mapper.noteOutcome("aborted");
324
- this.#asks.clear();
325
- await this.#require().abort();
326
- }
327
-
328
- // Not via `prompt`: that opens a turn with the question slot still filled, which the engine does not stop.
329
- async answer(questionId: string, answer: CodeAgentAnswer) {
330
- const question = this.#asks.questionOf(questionId);
331
- const rendered = question ? codeAgentRenderAnswer(question, answer) : (answer.text ?? "");
332
- if (this.#asks.answer(questionId, rendered)) {
333
- this.#emit({ type: "question_resolved", questionId, answer, rendered });
334
- return true;
335
- }
336
- if (this.#profile.interaction.question !== "suspend") return false;
337
- const suspended = this.#suspended.takeQuestion(questionId);
338
- if (!suspended) return false;
339
- const suspendedRendered = codeAgentRenderAnswer(suspended, answer);
340
- this.#emit({ type: "question_resolved", questionId, answer, rendered: suspendedRendered });
341
- // As prose: compaction and the next turn read message content only, so a structured-only answer is lost.
342
- await this.#prompt(`The user answered: ${suspendedRendered}\nContinue the task.`);
343
- return true;
344
- }
345
-
346
- async approve(approvalId: string, approved: boolean, remember?: "session") {
347
- if (this.#asks.resolveApproval(approvalId, approved)) {
348
- const remembered = this.allowed.settle(approvalId, approved && remember === "session");
349
- this.#emit({ type: "approval_resolved", approvalId, approved, ...(remembered.length ? { remembered } : {}) });
350
- for (const covered of this.allowed.covered())
351
- if (this.#asks.resolveApproval(covered, true))
352
- this.#emit({ type: "approval_resolved", approvalId: covered, approved: true });
353
- return true;
354
- }
355
- if (this.#profile.interaction.approval !== "suspend") return false;
356
- if (!this.#suspended.takeApproval(approvalId)) return false;
357
- this.#emit({ type: "approval_resolved", approvalId, approved });
358
- if (approved) await this.#prompt("The user approved the pending action. Retry it and continue.");
359
- return true;
360
- }
361
-
362
- async compact(instructions?: string) {
363
- await this.#require().compact(instructions);
364
- }
365
-
366
- /** Renames the session and says so on the wire, because a host draws the name from the session frame. */
367
- setName(name: string) {
368
- const clean = name.trim();
369
- if (!clean) return;
370
- this.#require().setSessionName(clean);
371
- this.#mailbox?.rename(clean, this.#profile.paths.root);
372
- this.#emit({ type: "session", info: this.info });
373
- }
374
-
375
- /** Copies the session file, not memory, under a new id: the file is what a resume replays. */
376
- fork(name?: string) {
377
- if (!this.#sessionDir) throw new Error("This profile keeps no sessions on disk, so there is nothing to fork");
378
- return CodeSessionFork.fork(this.#sessionDir, this.sessionId, name);
379
- }
380
-
381
- /** The reasoning levels this model offers, clamped by the engine to what the provider actually serves. */
382
- efforts(): CodeAgentEffort[] {
383
- const session = this.#session;
384
- if (!session?.supportsThinking()) return [];
385
- return session.getAvailableThinkingLevels();
386
- }
387
-
388
- setEffort(effort: CodeAgentEffort) {
389
- const session = this.#require();
390
- if (!session.supportsThinking()) throw new Error(`${session.model?.id ?? "this model"} does no reasoning`);
391
- // The engine clamps rather than refuses, so the frame that follows is the level that took, not the one asked.
392
- session.setThinkingLevel(effort);
393
- this.#emit({ type: "session", info: this.info });
394
- }
395
-
396
- /** Every registered provider, keyed or not — `getAvailable()` would list only what is already reachable. */
397
- catalogue(): CodeAgentProviderInfo[] {
398
- const runtime = this.#session?.modelRuntime;
399
- if (!runtime) return [];
400
- const current = this.#session?.model;
401
- return runtime
402
- .getProviders()
403
- .map((provider) => ({
404
- id: provider.id,
405
- name: provider.name ?? provider.id,
406
- authorized: runtime.hasConfiguredAuth(provider.id),
407
- models: (runtime.getModels(provider.id) ?? []).map((model) => ({
408
- id: model.id,
409
- name: model.name,
410
- ...(model.contextWindow ? { contextWindow: model.contextWindow } : {}),
411
- current: model.provider === current?.provider && model.id === current?.id,
412
- })),
413
- }))
414
- .sort((a, b) => a.id.localeCompare(b.id));
415
- }
416
-
417
- async setModel(ref: CodeAgentModelRef) {
418
- const session = this.#require();
419
- const model = await akanCodeModel(session.modelRuntime, ref);
420
- if (!model) throw new Error(`Unknown model: ${ref.provider}/${ref.id}`);
421
- await session.setModel(model);
422
- for (const message of this.#fitAutoCompact(this.#autoCompactAt))
423
- this.#emit({ type: "notice", level: "warning", message });
424
- this.#emit({ type: "session", info: this.info });
425
- }
426
-
427
- setAutoCompactAt(percent: number | undefined) {
428
- const wanted = AkanCodeCompaction.normalize(percent);
429
- const problem = this.#autoCompactProblem(wanted);
430
- if (problem) throw new Error(problem);
431
- this.#autoCompactAt = wanted;
432
- this.#applyAutoCompact();
433
- this.#emit({ type: "session", info: this.info });
434
- }
435
-
436
- // A share that fit one window can fall under the kept turns of a smaller one, and would compact every turn.
437
- #fitAutoCompact(percent: number | undefined) {
438
- const problem = this.#autoCompactProblem(percent);
439
- this.#autoCompactAt = problem ? undefined : percent;
440
- this.#applyAutoCompact();
441
- return problem ? [`${problem} Autocompact is back to the default.`] : [];
442
- }
443
-
444
- #autoCompactProblem(percent: number | undefined) {
445
- const session = this.#require();
446
- const model = session.model;
447
- if (!model || !percent) return undefined;
448
- const { keepRecentTokens } = session.settingsManager.getCompactionSettings(model);
449
- return AkanCodeCompaction.problemOf(model, percent, keepRecentTokens);
450
- }
451
-
452
- // Never before `create` has built the session: `settingsManager.reload()` drops whatever `applyOverrides` set.
453
- #applyAutoCompact() {
454
- const session = this.#require();
455
- if (session.model) AkanCodeCompaction.apply(session.settingsManager, session.model, this.#autoCompactAt);
456
- }
457
-
458
- async waitForIdle() {
459
- await this.#require().waitForIdle();
460
- }
461
-
462
- dispose() {
463
- this.#mailbox?.close();
464
- if (this.#disposed) return;
465
- this.#disposed = true;
466
- this.#asks.clear();
467
- this.#listeners.clear();
468
- this.#disposePlugins?.();
469
- this.#session?.dispose();
470
- }
471
-
472
- async #attach(session: AgentSession, mode: CodeAgentHostMode) {
473
- this.#session = session;
474
- session.subscribe((event) => {
475
- for (const body of this.#mapper.map(event)) this.#emit(body);
476
- // Per turn, not per delta: the count only moves when a provider response lands.
477
- if (event.type === "agent_end" || event.type === "compaction_end") this.#emitContextNow();
478
- });
479
- await session.bindExtensions({
480
- mode,
481
- uiContext: this.#ui().context(),
482
- abortHandler: () => void session.abort(),
483
- onError: (error: unknown) => this.#emit({ type: "error", message: String(error), fatal: false }),
484
- });
485
- }
486
-
487
- /** A path is read here rather than by the host, so a browser and a terminal hand the core the same thing. */
488
- static async #attachments(images: CodeAgentImage[] | undefined) {
489
- if (!images?.length) return [];
490
- return await Promise.all(
491
- images.map(async (image) => {
492
- if ("data" in image) return { type: "image" as const, data: image.data, mimeType: image.mime };
493
- const file = Bun.file(image.path);
494
- return {
495
- type: "image" as const,
496
- data: Buffer.from(await file.arrayBuffer()).toString("base64"),
497
- mimeType: file.type || "image/png",
498
- };
499
- }),
500
- );
501
- }
502
-
503
- // Also on resume, or a session reopened at 80% shows no usage until its next turn ends.
504
- #emitContextNow() {
505
- const usage = this.#session?.getContextUsage();
506
- // `== null` on purpose: typed `number | null`, but `undefined` must not emit `used: undefined`.
507
- if (usage?.tokens == null) return;
508
- if (usage.tokens === this.#lastContextTokens) return;
509
- this.#lastContextTokens = usage.tokens;
510
- this.#emit({ type: "context", used: usage.tokens, max: usage.contextWindow || undefined });
511
- }
512
-
513
- #require() {
514
- if (!this.#session) throw new Error("CodeAgent is not started");
515
- return this.#session;
516
- }
517
-
518
- #emit(body: CodeAgentEventBody) {
519
- this.#seq += 1;
520
- const event = { ...body, seq: this.#seq } as CodeAgentEvent;
521
- this.#remember(event);
522
- for (const listener of this.#listeners) listener(event);
523
- }
524
-
525
- #remember(event: CodeAgentEvent) {
526
- if (event.type === "idle") {
527
- this.#replay.length = 0;
528
- this.#replayFrom = event.seq;
529
- return;
530
- }
531
- this.#replay.push(event);
532
- while (this.#replay.length > CodeAgent.replayLimit) {
533
- const dropped = this.#replay.shift();
534
- this.#replayFrom = dropped?.seq ?? this.#replayFrom;
535
- }
536
- }
537
-
538
- #gateExtension(): InlineExtension {
539
- return {
540
- name: "akan-profile-gate",
541
- factory: (pi: ExtensionAPI) => {
542
- pi.on("tool_call", async (event) => {
543
- const verdict = this.#gate.verdict(event.toolName, event.input);
544
- if (verdict.block) return this.#refuse(event.toolCallId, event.toolName, event.input, verdict.block);
545
- if (!verdict.approval) return undefined;
546
- if (verdict.strict && !this.#profile.ui.canPrompt)
547
- return this.#refuse(
548
- event.toolCallId,
549
- event.toolName,
550
- event.input,
551
- "This reaches a host outside the profile's list, which needs the user's approval, and nobody can be asked in this session. Use a listed host, or say what you need fetched.",
552
- );
553
- const approved = await this.#requestApproval(
554
- event.toolCallId,
555
- event.toolName,
556
- verdict.approval,
557
- verdict.remember,
558
- );
559
- if (approved) return undefined;
560
- return this.#refuse(event.toolCallId, event.toolName, event.input, "The user declined this action.");
561
- });
562
- },
563
- };
564
- }
565
-
566
- #refuse(toolCallId: string, toolName: string, args: unknown, reason: string) {
567
- for (const body of this.#mapper.markBlocked(toolCallId, toolName, args, reason)) this.#emit(body);
568
- return { block: true, reason };
569
- }
570
-
571
- async #requestApproval(toolCallId: string, name: string, summary: string, offered?: string[]) {
572
- // Nobody to ask means nobody to refuse: a pod would otherwise deny every write it was created to make.
573
- if (!this.#profile.ui.canPrompt) return true;
574
- const approvalId = this.#asks.nextId("a");
575
- const suspends = this.#profile.interaction.approval === "suspend";
576
- // A suspended approval ends its turn, and the retry is a new call, so there is no session answer to offer.
577
- const remember = suspends ? undefined : offered;
578
- const request = {
579
- approvalId,
580
- toolCallId,
581
- name,
582
- summary: codeAgentClip(summary, codeAgentLabelChars),
583
- policy: this.#profile.approval,
584
- ...(remember ? { remember } : {}),
585
- };
586
- this.#emit({ type: "approval", request });
587
- if (suspends) {
588
- this.#suspended.addApproval(request);
589
- this.#mapper.noteOutcome("awaiting");
590
- return false;
591
- }
592
- if (remember) this.allowed.offer(approvalId, remember);
593
- const approved = await this.#asks.openApproval(approvalId);
594
- this.allowed.settle(approvalId, false);
595
- return approved;
596
- }
597
-
598
- /** The rendered answer; `undefined` when skipped, suspended, or nobody can be prompted. */
599
- async ask(spec: Omit<CodeAgentQuestion, "questionId">) {
600
- const question: CodeAgentQuestion = { questionId: this.#asks.nextId("q"), ...spec };
601
- if (!this.#profile.ui.canPrompt) {
602
- this.#emit({ type: "question_skipped", question, reason: "no-host" });
603
- return undefined;
604
- }
605
- this.#emit({ type: "question", question });
606
- if (this.#profile.interaction.question === "suspend") {
607
- this.#suspended.setQuestion(question);
608
- this.#mapper.noteOutcome("awaiting");
609
- return undefined;
610
- }
611
- return (await this.#asks.openQuestion(question)) || undefined;
612
- }
613
-
614
- #ui() {
615
- return new CodeAgentUi({
616
- ask: async (prompt, kind, choices) =>
617
- await this.ask({
618
- prompt,
619
- kind,
620
- ...(choices ? { options: choices.map((label) => ({ key: label, label })) } : {}),
621
- freeText: kind === "text",
622
- }),
623
- notify: (level, message) => this.#emit({ type: "notice", level, message }),
624
- });
625
- }
626
- }
@@ -1,35 +0,0 @@
1
- // Kept in this process only: a resumed or reloaded session starts with nothing allowed.
2
- export class CodeAgentAllowed {
3
- readonly #names = new Set<string>();
4
- readonly #offers = new Map<string, string[]>();
5
-
6
- get names() {
7
- return [...this.#names].sort();
8
- }
9
-
10
- missing(names: string[]) {
11
- return names.filter((name) => !this.#names.has(name));
12
- }
13
-
14
- offer(approvalId: string, names: string[]) {
15
- this.#offers.set(approvalId, names);
16
- }
17
-
18
- settle(approvalId: string, remember: boolean) {
19
- const names = this.#offers.get(approvalId) ?? [];
20
- this.#offers.delete(approvalId);
21
- if (!remember) return [];
22
- for (const name of names) this.#names.add(name);
23
- return names;
24
- }
25
-
26
- covered() {
27
- return [...this.#offers].filter(([, names]) => !this.missing(names).length).map(([approvalId]) => approvalId);
28
- }
29
-
30
- clear() {
31
- const count = this.#names.size;
32
- this.#names.clear();
33
- return count;
34
- }
35
- }