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