@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,50 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
|
|
5
|
+
// Bun auto-loads .env from the current directory only, so a run from a subdirectory sees none of the workspace's keys.
|
|
6
|
+
// Applied as runtime overrides, never stored: copying a key into ~/.akan/code/auth.json gives it a second lifetime.
|
|
7
|
+
export class AkanEnvKeys {
|
|
8
|
+
static async apply(runtime: ModelRuntime, workspaceRoot: string) {
|
|
9
|
+
const applied: string[] = [];
|
|
10
|
+
for (const [name, value] of AkanEnvKeys.#entries(workspaceRoot)) {
|
|
11
|
+
const provider = AkanEnvKeys.#providerOf(name);
|
|
12
|
+
if (!provider || !value) continue;
|
|
13
|
+
// Serially: the runtime's credential writes share one file, and a key written mid-write goes missing.
|
|
14
|
+
await runtime.setRuntimeApiKey(provider, value);
|
|
15
|
+
applied.push(provider);
|
|
16
|
+
}
|
|
17
|
+
return applied;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
static #entries(workspaceRoot: string): [string, string][] {
|
|
21
|
+
const fromProcess = Object.entries(process.env).filter(([, value]) => typeof value === "string") as [
|
|
22
|
+
string,
|
|
23
|
+
string,
|
|
24
|
+
][];
|
|
25
|
+
const file = path.join(workspaceRoot, ".env");
|
|
26
|
+
if (!existsSync(file)) return fromProcess;
|
|
27
|
+
const fromFile = readFileSync(file, "utf8")
|
|
28
|
+
.split("\n")
|
|
29
|
+
.map((line) => line.trim())
|
|
30
|
+
.filter((line) => line && !line.startsWith("#") && line.includes("="))
|
|
31
|
+
.map((line): [string, string] => {
|
|
32
|
+
const index = line.indexOf("=");
|
|
33
|
+
return [
|
|
34
|
+
line.slice(0, index).trim(),
|
|
35
|
+
line
|
|
36
|
+
.slice(index + 1)
|
|
37
|
+
.trim()
|
|
38
|
+
.replace(/^["']|["']$/g, ""),
|
|
39
|
+
];
|
|
40
|
+
});
|
|
41
|
+
// The real environment wins: an operator exporting a key for one run should not be overridden by the file.
|
|
42
|
+
return [...fromFile, ...fromProcess];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** `DEEPSEEK_API_KEY` names the provider `deepseek`; the engine's provider ids are lower-kebab. */
|
|
46
|
+
static #providerOf(name: string) {
|
|
47
|
+
const match = /^([A-Z0-9_]+)_API_KEY$/.exec(name);
|
|
48
|
+
return match?.[1]?.toLowerCase().replace(/_/g, "-");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { Workspace } from "@akanjs/devkit/commandDecorators";
|
|
2
|
+
import type { ExtensionAPI, InlineExtension } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import { AkanVerifier } from "./AkanVerifier";
|
|
5
|
+
|
|
6
|
+
export type AkanToolMode = "readonly" | "plan" | "apply";
|
|
7
|
+
|
|
8
|
+
export interface AkanCatalogTool {
|
|
9
|
+
name: string;
|
|
10
|
+
description?: string;
|
|
11
|
+
inputSchema: Record<string, unknown>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface AkanToolCatalog {
|
|
15
|
+
list: (mode: AkanToolMode) => Promise<AkanCatalogTool[]>;
|
|
16
|
+
call: (workspace: Workspace, name: string, args: Record<string, unknown>, mode: AkanToolMode) => Promise<unknown>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface AkanToolPackOptions {
|
|
20
|
+
workspace: Workspace;
|
|
21
|
+
cwd: string;
|
|
22
|
+
/** `readonly` for a reviewer, `apply` for an agent that may run a workflow. */
|
|
23
|
+
mode: AkanToolMode;
|
|
24
|
+
catalog?: AkanToolCatalog;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Wraps the CLI's in-process akan MCP dispatcher (ContextRunner), handed in as the catalog: a copy would drift from it.
|
|
28
|
+
export class AkanToolPack {
|
|
29
|
+
readonly #options: AkanToolPackOptions;
|
|
30
|
+
|
|
31
|
+
constructor(options: AkanToolPackOptions) {
|
|
32
|
+
this.#options = options;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
extension(): InlineExtension {
|
|
36
|
+
return { name: "akan-tools", factory: async (pi) => await this.#register(pi) };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// The session allowlist covers extension tools too; a name missing here tells the model the tool does not exist.
|
|
40
|
+
async names() {
|
|
41
|
+
const listed = (await this.#options.catalog?.list(this.#options.mode)) ?? [];
|
|
42
|
+
return [...listed.map((tool) => tool.name), AkanToolPack.verifyToolName];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
static readonly verifyToolName = "akan_verify";
|
|
46
|
+
|
|
47
|
+
async #register(pi: ExtensionAPI) {
|
|
48
|
+
if (this.#options.catalog) await this.#registerCatalog(pi, this.#options.catalog);
|
|
49
|
+
this.#registerVerify(pi);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async #registerCatalog(pi: ExtensionAPI, catalog: AkanToolCatalog) {
|
|
53
|
+
const { workspace, mode } = this.#options;
|
|
54
|
+
for (const tool of await catalog.list(mode)) {
|
|
55
|
+
const description = tool.description ?? tool.name;
|
|
56
|
+
pi.registerTool({
|
|
57
|
+
name: tool.name,
|
|
58
|
+
label: tool.name,
|
|
59
|
+
description,
|
|
60
|
+
// Without a snippet the engine leaves a custom tool out of the system prompt's tool list entirely.
|
|
61
|
+
promptSnippet: `${tool.name}: ${description.split(".")[0] ?? description}`,
|
|
62
|
+
parameters: Type.Unsafe<Record<string, unknown>>(tool.inputSchema),
|
|
63
|
+
execute: async (_id, params) => {
|
|
64
|
+
const result = await catalog.call(workspace, tool.name, params ?? {}, mode);
|
|
65
|
+
const text = typeof result === "string" ? result : JSON.stringify(result, null, 2);
|
|
66
|
+
return { content: [{ type: "text", text }], details: undefined };
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
#registerVerify(pi: ExtensionAPI) {
|
|
73
|
+
const verifier = new AkanVerifier(this.#options.cwd);
|
|
74
|
+
pi.registerTool({
|
|
75
|
+
name: AkanToolPack.verifyToolName,
|
|
76
|
+
label: "akan verify",
|
|
77
|
+
description:
|
|
78
|
+
"Run `akan verify` over everything the working tree has changed: sync, lint (with fixes), typecheck, a build of each changed app's server and SSR routes, and the SSR check for .tsx changes, in one call. It prints one line when it passes and one line per problem when it fails. Call this after editing, before you finish; never run lint, typecheck or build separately.",
|
|
79
|
+
promptSnippet: "akan_verify: sync, lint, typecheck and build what the working tree changed, in one call",
|
|
80
|
+
parameters: Type.Object({}),
|
|
81
|
+
execute: async () => {
|
|
82
|
+
const report = await verifier.verify();
|
|
83
|
+
return { content: [{ type: "text", text: report.text }], details: undefined, isError: !report.ok };
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { AkanCli, type AkanCliResult } from "./AkanCli";
|
|
2
|
+
|
|
3
|
+
export interface AkanVerifyReport {
|
|
4
|
+
ok: boolean;
|
|
5
|
+
text: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export class AkanVerifier {
|
|
9
|
+
static readonly tailLines = 20;
|
|
10
|
+
readonly #cli: AkanCli;
|
|
11
|
+
|
|
12
|
+
constructor(cwd: string) {
|
|
13
|
+
this.#cli = new AkanCli(cwd);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async verify(paths: string[] = []): Promise<AkanVerifyReport> {
|
|
17
|
+
const args = ["verify", ...(paths.length ? ["--files", paths.join(",")] : [])];
|
|
18
|
+
const result = await this.#cli.run(args, { timeoutMs: 600_000 });
|
|
19
|
+
return { ok: result.ok, text: AkanVerifier.summarize(result) };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
//* `akan verify` already prints the agent-sized report; only a crash before it prints needs trimming.
|
|
23
|
+
static summarize(result: AkanCliResult) {
|
|
24
|
+
if (result.output.startsWith("verify ")) return result.output;
|
|
25
|
+
const lines = result.output.split("\n");
|
|
26
|
+
const tail =
|
|
27
|
+
lines.length <= AkanVerifier.tailLines ? result.output : `…\n${lines.slice(-AkanVerifier.tailLines).join("\n")}`;
|
|
28
|
+
return `${result.command} exited ${result.exitCode} before reporting:\n${tail}`;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { ExtensionAPI, InlineExtension } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { CodeAgentProfile, CodeAgentQuestion } from "akanjs/common";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
|
|
5
|
+
export interface AskToolPackOptions {
|
|
6
|
+
profile: CodeAgentProfile;
|
|
7
|
+
/** Puts one question on the wire and resolves with the labels chosen, or nothing when it was skipped. */
|
|
8
|
+
ask: (question: Omit<CodeAgentQuestion, "questionId">) => Promise<string | undefined>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// One question at a time even when several are sent: the host draws one block, and an answer can change the next.
|
|
12
|
+
export class AskToolPack {
|
|
13
|
+
static readonly toolName = "ask_user";
|
|
14
|
+
/** Four is what fits on a screen without the transcript disappearing behind the questions. */
|
|
15
|
+
static readonly maxQuestions = 4;
|
|
16
|
+
|
|
17
|
+
readonly #options: AskToolPackOptions;
|
|
18
|
+
|
|
19
|
+
constructor(options: AskToolPackOptions) {
|
|
20
|
+
this.#options = options;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
names() {
|
|
24
|
+
return this.#options.profile.ui.canPrompt ? [AskToolPack.toolName] : [];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
extension(): InlineExtension | undefined {
|
|
28
|
+
if (!this.#options.profile.ui.canPrompt) return undefined;
|
|
29
|
+
return { name: "akan-ask", factory: (pi: ExtensionAPI) => this.#register(pi) };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
#register(pi: ExtensionAPI) {
|
|
33
|
+
pi.registerTool({
|
|
34
|
+
name: AskToolPack.toolName,
|
|
35
|
+
label: "Ask",
|
|
36
|
+
description:
|
|
37
|
+
"Ask the user to decide something you cannot decide from the code or the request. Use it when two readings of the task would lead to materially different work, not for choices with an obvious default — and never to ask permission for work you were already asked to do. Offer concrete options whenever you can name them; mark one recommended when you have a view.",
|
|
38
|
+
promptSnippet: "ask_user: put a decision the user owns back to them, with options",
|
|
39
|
+
parameters: Type.Object({
|
|
40
|
+
questions: Type.Array(
|
|
41
|
+
Type.Object({
|
|
42
|
+
question: Type.String({ description: "The whole question, as one sentence ending in a question mark." }),
|
|
43
|
+
header: Type.Optional(
|
|
44
|
+
Type.String({ description: "Two or three words naming what is being chosen, e.g. 'Auth method'." }),
|
|
45
|
+
),
|
|
46
|
+
options: Type.Optional(
|
|
47
|
+
Type.Array(
|
|
48
|
+
Type.Object({
|
|
49
|
+
label: Type.String({ description: "The choice, in one to five words." }),
|
|
50
|
+
detail: Type.Optional(
|
|
51
|
+
Type.String({ description: "What picking it means, or the trade-off it carries." }),
|
|
52
|
+
),
|
|
53
|
+
recommended: Type.Optional(
|
|
54
|
+
Type.Boolean({ description: "Mark at most one. It is offered first and labelled as such." }),
|
|
55
|
+
),
|
|
56
|
+
}),
|
|
57
|
+
{ description: "Two to four distinct choices. Leave it out to ask for an answer in prose." },
|
|
58
|
+
),
|
|
59
|
+
),
|
|
60
|
+
multiSelect: Type.Optional(
|
|
61
|
+
Type.Boolean({ description: "Several options may be chosen together, rather than exactly one." }),
|
|
62
|
+
),
|
|
63
|
+
freeText: Type.Optional(
|
|
64
|
+
Type.Boolean({
|
|
65
|
+
description: "Offer a further choice that lets the user type an answer of their own. Default true.",
|
|
66
|
+
}),
|
|
67
|
+
),
|
|
68
|
+
}),
|
|
69
|
+
{ description: `One to ${AskToolPack.maxQuestions} questions, asked in order.` },
|
|
70
|
+
),
|
|
71
|
+
}),
|
|
72
|
+
execute: async (_id, params) => {
|
|
73
|
+
const questions = (params.questions ?? []).slice(0, AskToolPack.maxQuestions);
|
|
74
|
+
if (!questions.length)
|
|
75
|
+
return { content: [{ type: "text", text: "No question was asked." }], details: undefined, isError: true };
|
|
76
|
+
const answers: string[] = [];
|
|
77
|
+
for (const entry of questions) {
|
|
78
|
+
const options = (entry.options ?? []).map((option, at) => ({
|
|
79
|
+
key: `${at}`,
|
|
80
|
+
label: option.label,
|
|
81
|
+
...(option.detail ? { detail: option.detail } : {}),
|
|
82
|
+
...(option.recommended ? { recommended: true } : {}),
|
|
83
|
+
}));
|
|
84
|
+
const answer = await this.#options.ask({
|
|
85
|
+
prompt: entry.header ? `${entry.header} — ${entry.question}` : entry.question,
|
|
86
|
+
kind: options.length ? "select" : "text",
|
|
87
|
+
...(options.length ? { options } : {}),
|
|
88
|
+
...(entry.multiSelect ? { multiSelect: true } : {}),
|
|
89
|
+
// On by default: the model's options are a guess, and only the person knows when none of them fits.
|
|
90
|
+
freeText: entry.freeText ?? true,
|
|
91
|
+
});
|
|
92
|
+
// Spelled out as a skip: a blank answer reads to a model as "the user wanted nothing".
|
|
93
|
+
answers.push(`${entry.question}\n→ ${answer ?? "(skipped — decide this yourself and say what you chose)"}`);
|
|
94
|
+
}
|
|
95
|
+
return { content: [{ type: "text", text: answers.join("\n\n") }], details: undefined };
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { codeAgentClip } from "akanjs/common";
|
|
3
|
+
|
|
4
|
+
interface DeepSeekSearchResult {
|
|
5
|
+
title: string;
|
|
6
|
+
url: string;
|
|
7
|
+
snippet?: string;
|
|
8
|
+
summary?: string;
|
|
9
|
+
date?: string | null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface DeepSeekPage {
|
|
13
|
+
title: string;
|
|
14
|
+
content: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class DeepSeekWeb {
|
|
18
|
+
static readonly baseUrl = "https://api.deepseek.com/v1/tools";
|
|
19
|
+
static readonly maxQueryChars = 128;
|
|
20
|
+
static readonly summaryChars = 600;
|
|
21
|
+
// Only a successful call is billed, so a retry costs nothing. Search has no fallback and waits out every transient
|
|
22
|
+
// status; fetch waits only on its quota and otherwise falls back to a direct read, which beats DeepSeek's 504.
|
|
23
|
+
static readonly #retryable: { [tool in "search" | "fetch"]: number[] } = {
|
|
24
|
+
search: [408, 429, 500, 502, 503, 504],
|
|
25
|
+
fetch: [429],
|
|
26
|
+
};
|
|
27
|
+
static readonly #attempts = 3;
|
|
28
|
+
|
|
29
|
+
readonly #key: string;
|
|
30
|
+
readonly #baseUrl: string;
|
|
31
|
+
|
|
32
|
+
constructor(key: string, baseUrl = DeepSeekWeb.baseUrl) {
|
|
33
|
+
this.#key = key;
|
|
34
|
+
this.#baseUrl = baseUrl;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Undefined behind a proxy, where the runtime holds only a placeholder and the real key stays with the host. */
|
|
38
|
+
static async fromRuntime(runtime: ModelRuntime, proxied: boolean) {
|
|
39
|
+
if (proxied) return undefined;
|
|
40
|
+
const key = (await runtime.getAuth("deepseek").catch(() => undefined))?.auth.apiKey;
|
|
41
|
+
return key ? new DeepSeekWeb(key) : undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async search(query: string, count: number, signal?: AbortSignal) {
|
|
45
|
+
if ([...query].length > DeepSeekWeb.maxQueryChars)
|
|
46
|
+
throw new Error(`DeepSeek search takes at most ${DeepSeekWeb.maxQueryChars} characters; shorten the query.`);
|
|
47
|
+
const body = await this.#call<{ results?: DeepSeekSearchResult[] }>("search", { query, count }, 20_000, signal);
|
|
48
|
+
const byUrl = new Map<string, DeepSeekSearchResult>();
|
|
49
|
+
for (const result of body.results ?? []) {
|
|
50
|
+
const url = DeepSeekWeb.#cleanUrl(result.url);
|
|
51
|
+
if (!byUrl.has(url)) byUrl.set(url, { ...result, url });
|
|
52
|
+
}
|
|
53
|
+
return [...byUrl.values()]
|
|
54
|
+
.map((result) => {
|
|
55
|
+
const date = result.date ? ` · ${result.date.slice(0, 10)}` : "";
|
|
56
|
+
const summary = DeepSeekWeb.unescape(result.summary || result.snippet || "")
|
|
57
|
+
.replace(/\s+/g, " ")
|
|
58
|
+
.trim();
|
|
59
|
+
return `- ${result.title}\n ${result.url}${date}\n ${codeAgentClip(summary, DeepSeekWeb.summaryChars)}`;
|
|
60
|
+
})
|
|
61
|
+
.join("\n");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async fetch(url: string, signal?: AbortSignal): Promise<DeepSeekPage> {
|
|
65
|
+
const page = await this.#call<{ title?: string; content?: string }>("fetch", { url }, 30_000, signal);
|
|
66
|
+
return { title: page.title ?? "", content: DeepSeekWeb.unescape(page.content ?? "") };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Fetch escapes every ASCII punctuation mark, structure included (`\#\# Title`, `foo\(\)`), which costs tokens
|
|
70
|
+
// and garbles code. Undone only when nearly all punctuation is escaped, so a page already clean keeps its `\.`.
|
|
71
|
+
static unescape(markdown: string) {
|
|
72
|
+
const escaped = markdown.match(/\\[!-/:-@[-`{-~]/g)?.length ?? 0;
|
|
73
|
+
const punctuation = markdown.match(/[!-/:-@[-`{-~]/g)?.length ?? 0;
|
|
74
|
+
if (!escaped || escaped < (punctuation - escaped) / 2) return markdown;
|
|
75
|
+
return markdown.replace(/\\([!-/:-@[-`{-~])/g, "$1");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async #call<T>(tool: "search" | "fetch", body: object, timeoutMs: number, signal?: AbortSignal): Promise<T> {
|
|
79
|
+
for (let attempt = 1; ; attempt++) {
|
|
80
|
+
const response = await fetch(`${this.#baseUrl}/${tool}`, {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: { authorization: `Bearer ${this.#key}`, "content-type": "application/json" },
|
|
83
|
+
body: JSON.stringify(body),
|
|
84
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),
|
|
85
|
+
});
|
|
86
|
+
if (response.ok) return (await response.json()) as T;
|
|
87
|
+
if (!DeepSeekWeb.#retryable[tool].includes(response.status) || attempt >= DeepSeekWeb.#attempts) {
|
|
88
|
+
const error = (await response.json().catch(() => undefined)) as { error?: { message?: string } } | undefined;
|
|
89
|
+
throw new Error(
|
|
90
|
+
`DeepSeek ${tool} answered ${response.status}: ${error?.error?.message ?? response.statusText}`,
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
await DeepSeekWeb.#wait(DeepSeekWeb.#delayOf(response, attempt), signal);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
static #delayOf(response: Response, attempt: number) {
|
|
98
|
+
const retryAfter = Number(response.headers.get("retry-after"));
|
|
99
|
+
return Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 5) * 1000 : 1000 * 2 ** (attempt - 1);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
static #wait(ms: number, signal?: AbortSignal) {
|
|
103
|
+
return new Promise<void>((resolve) => {
|
|
104
|
+
const timer = setTimeout(resolve, ms);
|
|
105
|
+
signal?.addEventListener(
|
|
106
|
+
"abort",
|
|
107
|
+
() => {
|
|
108
|
+
clearTimeout(timer);
|
|
109
|
+
resolve();
|
|
110
|
+
},
|
|
111
|
+
{ once: true },
|
|
112
|
+
);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Drops the tracking parameters and the bare `#1` chunk marker DeepSeek appends to result URLs. */
|
|
117
|
+
static #cleanUrl(url: string) {
|
|
118
|
+
try {
|
|
119
|
+
const parsed = new URL(url);
|
|
120
|
+
for (const name of [...parsed.searchParams.keys()]) if (name.startsWith("utm_")) parsed.searchParams.delete(name);
|
|
121
|
+
if (/^#\d+$/.test(parsed.hash)) parsed.hash = "";
|
|
122
|
+
return parsed.toString();
|
|
123
|
+
} catch {
|
|
124
|
+
return url;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { ExtensionAPI, InlineExtension } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { CodeAgentProfile } from "akanjs/common";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import type { CodeMailbox, CodePeer } from "../agent/CodeMailbox";
|
|
5
|
+
|
|
6
|
+
export interface MailToolPackOptions {
|
|
7
|
+
profile: CodeAgentProfile;
|
|
8
|
+
/** Late, because the mailbox only exists once the session it announces has one. */
|
|
9
|
+
mailbox: () => CodeMailbox | undefined;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class MailToolPack {
|
|
13
|
+
static readonly toolNames = ["list_peers", "send_peer_message"];
|
|
14
|
+
|
|
15
|
+
readonly #options: MailToolPackOptions;
|
|
16
|
+
|
|
17
|
+
constructor(options: MailToolPackOptions) {
|
|
18
|
+
this.#options = options;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
names() {
|
|
22
|
+
return this.#options.profile.session.store === "file" ? MailToolPack.toolNames : [];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
extension(): InlineExtension | undefined {
|
|
26
|
+
if (!this.names().length) return undefined;
|
|
27
|
+
return { name: "akan-mail", factory: (pi: ExtensionAPI) => this.#register(pi) };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
#register(pi: ExtensionAPI) {
|
|
31
|
+
pi.registerTool({
|
|
32
|
+
name: "list_peers",
|
|
33
|
+
label: "List peer sessions",
|
|
34
|
+
description:
|
|
35
|
+
"List the other akan code sessions running in this workspace right now, with their name and working directory. Call it before send_peer_message so you name a session that is actually there.",
|
|
36
|
+
promptSnippet: "list_peers: the other akan code sessions running here",
|
|
37
|
+
parameters: Type.Object({}),
|
|
38
|
+
execute: async () => ({
|
|
39
|
+
content: [{ type: "text" as const, text: MailToolPack.#render(this.#options.mailbox()?.peers() ?? []) }],
|
|
40
|
+
details: undefined,
|
|
41
|
+
}),
|
|
42
|
+
});
|
|
43
|
+
pi.registerTool({
|
|
44
|
+
name: "send_peer_message",
|
|
45
|
+
label: "Message a peer session",
|
|
46
|
+
description:
|
|
47
|
+
"Hand a message to another akan code session in this workspace. It arrives there as a prompt, so it costs that session a turn — use it to hand over a piece of work or to warn it about a change you made, not to chat. Say what you want done and what you already did.",
|
|
48
|
+
promptSnippet: "send_peer_message: hand work to another akan code session",
|
|
49
|
+
parameters: Type.Object({
|
|
50
|
+
to: Type.String({ description: "The peer's name, or the front of its id, from list_peers." }),
|
|
51
|
+
message: Type.String({ description: "What that session should know or do." }),
|
|
52
|
+
}),
|
|
53
|
+
execute: async (_id, params) => {
|
|
54
|
+
const mailbox = this.#options.mailbox();
|
|
55
|
+
const peer = mailbox?.find(params.to);
|
|
56
|
+
if (!mailbox || !peer)
|
|
57
|
+
return {
|
|
58
|
+
content: [{ type: "text" as const, text: `No live session matches "${params.to}". Call list_peers.` }],
|
|
59
|
+
details: undefined,
|
|
60
|
+
isError: true,
|
|
61
|
+
};
|
|
62
|
+
try {
|
|
63
|
+
mailbox.send(peer.id, params.message);
|
|
64
|
+
return { content: [{ type: "text" as const, text: `Sent to ${peer.name}.` }], details: undefined };
|
|
65
|
+
} catch (error: unknown) {
|
|
66
|
+
return { content: [{ type: "text" as const, text: String(error) }], details: undefined, isError: true };
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
static #render(peers: CodePeer[]) {
|
|
73
|
+
if (!peers.length) return "No other akan code session is running in this workspace.";
|
|
74
|
+
return peers.map((peer) => `${peer.name} (${peer.id.slice(0, 8)}) — ${peer.cwd}`).join("\n");
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { type CodeAgentMcpServerRef, FailureCode, MCP_FAILURE_META } from "akanjs/common";
|
|
2
|
+
|
|
3
|
+
export interface McpToolInfo {
|
|
4
|
+
name: string;
|
|
5
|
+
description?: string;
|
|
6
|
+
inputSchema: { type: "object"; properties: Record<string, unknown>; required?: string[] };
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
interface JsonRpcResponse {
|
|
10
|
+
id?: number;
|
|
11
|
+
result?: {
|
|
12
|
+
tools?: McpToolInfo[];
|
|
13
|
+
nextCursor?: string;
|
|
14
|
+
content?: unknown;
|
|
15
|
+
isError?: boolean;
|
|
16
|
+
_meta?: Record<string, unknown>;
|
|
17
|
+
};
|
|
18
|
+
error?: { code: number; message: string; data?: unknown };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface McpToolCallResult {
|
|
22
|
+
text: string;
|
|
23
|
+
isError: boolean;
|
|
24
|
+
/** What the server named the failure by: `_meta["akanjs/failure"].code`, or a JSON-RPC error's `data.code`. */
|
|
25
|
+
code?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const protocolVersion = "2025-06-18";
|
|
29
|
+
|
|
30
|
+
// Its own class: a 401 is fixed by signing in, and calling it "unavailable" sends someone to debug a working server.
|
|
31
|
+
export class McpUnauthorized extends Error {
|
|
32
|
+
/** The `WWW-Authenticate` value, which names the resource metadata discovery starts from. */
|
|
33
|
+
readonly challenge: string;
|
|
34
|
+
|
|
35
|
+
constructor(name: string, challenge: string) {
|
|
36
|
+
super(`MCP server "${name}" requires authentication`);
|
|
37
|
+
this.name = "McpUnauthorized";
|
|
38
|
+
this.challenge = challenge;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class McpClient {
|
|
43
|
+
/** A ceiling on a server that never stops paging; 50 pages is 5,000 tools at the usual page size. */
|
|
44
|
+
static readonly maxToolPages = 50;
|
|
45
|
+
|
|
46
|
+
readonly ref: CodeAgentMcpServerRef;
|
|
47
|
+
#proc: Bun.Subprocess<"pipe", "pipe", "ignore"> | undefined;
|
|
48
|
+
#nextId = 0;
|
|
49
|
+
#buffer = "";
|
|
50
|
+
readonly #pending = new Map<number, (response: JsonRpcResponse) => void>();
|
|
51
|
+
#sessionId: string | undefined;
|
|
52
|
+
readonly #token: string | undefined;
|
|
53
|
+
|
|
54
|
+
constructor(ref: CodeAgentMcpServerRef, token?: string) {
|
|
55
|
+
this.ref = ref;
|
|
56
|
+
this.#token = token;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async connect() {
|
|
60
|
+
if (this.ref.transport === "stdio") this.#spawn();
|
|
61
|
+
const initialize = await this.#call("initialize", {
|
|
62
|
+
protocolVersion,
|
|
63
|
+
capabilities: {},
|
|
64
|
+
clientInfo: { name: "akan-code", version: "1" },
|
|
65
|
+
});
|
|
66
|
+
if (initialize.error) throw new Error(initialize.error.message);
|
|
67
|
+
await this.#notify("notifications/initialized");
|
|
68
|
+
return this;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Every page: `tools/list` pages by `nextCursor` (an akan server at 100), and one page silently drops the tail. */
|
|
72
|
+
async listTools(): Promise<McpToolInfo[]> {
|
|
73
|
+
const tools: McpToolInfo[] = [];
|
|
74
|
+
let cursor: string | undefined;
|
|
75
|
+
for (let page = 0; page < McpClient.maxToolPages; page += 1) {
|
|
76
|
+
const response = await this.#call("tools/list", cursor ? { cursor } : {});
|
|
77
|
+
if (response.error) throw new Error(response.error.message);
|
|
78
|
+
tools.push(...(response.result?.tools ?? []));
|
|
79
|
+
const next = response.result?.nextCursor;
|
|
80
|
+
// Handing back the cursor it was given is a server that would page forever; so is one that cycles.
|
|
81
|
+
if (!next || next === cursor) return tools;
|
|
82
|
+
cursor = next;
|
|
83
|
+
}
|
|
84
|
+
return tools;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async callTool(name: string, args: Record<string, unknown>): Promise<McpToolCallResult> {
|
|
88
|
+
const response = await this.#call("tools/call", { name, arguments: args });
|
|
89
|
+
if (response.error)
|
|
90
|
+
return { text: response.error.message, isError: true, ...McpClient.#coded(response.error.data) };
|
|
91
|
+
const isError = !!response.result?.isError;
|
|
92
|
+
const failure = isError ? response.result?._meta?.[MCP_FAILURE_META] : undefined;
|
|
93
|
+
return { text: McpClient.#renderContent(response.result?.content), isError, ...McpClient.#coded(failure) };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Only a code shaped as an akan server names one: the server is a third party, and its value reaches the transcript.
|
|
97
|
+
static #coded(carrier: unknown): { code?: string } {
|
|
98
|
+
const code = carrier && typeof carrier === "object" ? (carrier as { code?: unknown }).code : undefined;
|
|
99
|
+
return FailureCode.is(code) ? { code } : {};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
close() {
|
|
103
|
+
this.#proc?.kill();
|
|
104
|
+
this.#proc = undefined;
|
|
105
|
+
for (const resolve of this.#pending.values()) resolve({ error: { code: -1, message: "MCP server closed" } });
|
|
106
|
+
this.#pending.clear();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
#spawn() {
|
|
110
|
+
if (!this.ref.command) throw new Error(`MCP server "${this.ref.name}" declares no command`);
|
|
111
|
+
this.#proc = Bun.spawn([this.ref.command, ...(this.ref.args ?? [])], {
|
|
112
|
+
stdin: "pipe",
|
|
113
|
+
stdout: "pipe",
|
|
114
|
+
stderr: "ignore",
|
|
115
|
+
env: { ...process.env, ...this.ref.env },
|
|
116
|
+
});
|
|
117
|
+
void this.#readStdout();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async #readStdout() {
|
|
121
|
+
const decoder = new TextDecoder();
|
|
122
|
+
for await (const chunk of this.#proc?.stdout ?? []) {
|
|
123
|
+
this.#buffer += decoder.decode(chunk as Uint8Array, { stream: true });
|
|
124
|
+
let index = this.#buffer.indexOf("\n");
|
|
125
|
+
while (index >= 0) {
|
|
126
|
+
const line = this.#buffer.slice(0, index).trim();
|
|
127
|
+
this.#buffer = this.#buffer.slice(index + 1);
|
|
128
|
+
if (line) this.#receive(line);
|
|
129
|
+
index = this.#buffer.indexOf("\n");
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
#receive(line: string) {
|
|
135
|
+
try {
|
|
136
|
+
const message = JSON.parse(line) as JsonRpcResponse;
|
|
137
|
+
if (typeof message.id !== "number") return;
|
|
138
|
+
this.#pending.get(message.id)?.(message);
|
|
139
|
+
this.#pending.delete(message.id);
|
|
140
|
+
} catch {
|
|
141
|
+
// A server that writes anything but JSON-RPC on stdout is misbehaving; dropping the line keeps us alive.
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async #call(method: string, params: unknown): Promise<JsonRpcResponse> {
|
|
146
|
+
this.#nextId += 1;
|
|
147
|
+
const id = this.#nextId;
|
|
148
|
+
const request = { jsonrpc: "2.0", id, method, params };
|
|
149
|
+
if (this.ref.transport === "http") return await this.#post(request);
|
|
150
|
+
this.#proc?.stdin.write(`${JSON.stringify(request)}\n`);
|
|
151
|
+
return await new Promise<JsonRpcResponse>((resolve) => {
|
|
152
|
+
this.#pending.set(id, resolve);
|
|
153
|
+
setTimeout(() => {
|
|
154
|
+
if (!this.#pending.delete(id)) return;
|
|
155
|
+
resolve({ error: { code: -2, message: `MCP server "${this.ref.name}" timed out on ${method}` } });
|
|
156
|
+
}, 30_000);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async #notify(method: string) {
|
|
161
|
+
const request = { jsonrpc: "2.0", method };
|
|
162
|
+
if (this.ref.transport === "http") await this.#post(request);
|
|
163
|
+
else this.#proc?.stdin.write(`${JSON.stringify(request)}\n`);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async #post(body: unknown): Promise<JsonRpcResponse> {
|
|
167
|
+
if (!this.ref.url) throw new Error(`MCP server "${this.ref.name}" declares no url`);
|
|
168
|
+
const response = await fetch(this.ref.url, {
|
|
169
|
+
method: "POST",
|
|
170
|
+
headers: {
|
|
171
|
+
"content-type": "application/json",
|
|
172
|
+
// Streamable HTTP lets a server answer either way; a client that omits the SSE type gets a 406.
|
|
173
|
+
accept: "application/json, text/event-stream",
|
|
174
|
+
"mcp-protocol-version": protocolVersion,
|
|
175
|
+
...this.ref.headers,
|
|
176
|
+
...(this.#token ? { authorization: `Bearer ${this.#token}` } : {}),
|
|
177
|
+
...(this.#sessionId ? { "mcp-session-id": this.#sessionId } : {}),
|
|
178
|
+
},
|
|
179
|
+
body: JSON.stringify(body),
|
|
180
|
+
signal: AbortSignal.timeout(30_000),
|
|
181
|
+
});
|
|
182
|
+
// Thrown, not returned as a JSON-RPC error: a 401's body says nothing, and the caller needs its header.
|
|
183
|
+
if (response.status === 401)
|
|
184
|
+
throw new McpUnauthorized(this.ref.name, response.headers.get("www-authenticate") ?? "");
|
|
185
|
+
this.#sessionId = response.headers.get("mcp-session-id") ?? this.#sessionId;
|
|
186
|
+
const text = await response.text();
|
|
187
|
+
if (!text.trim()) return {};
|
|
188
|
+
// An SSE answer to a single request carries one `data:` line holding the whole JSON-RPC response.
|
|
189
|
+
const payload = text.startsWith("event:") || text.startsWith("data:") ? McpClient.#firstSseData(text) : text;
|
|
190
|
+
return payload ? (JSON.parse(payload) as JsonRpcResponse) : {};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
static #firstSseData(text: string) {
|
|
194
|
+
return text
|
|
195
|
+
.split("\n")
|
|
196
|
+
.find((line) => line.startsWith("data:"))
|
|
197
|
+
?.slice(5)
|
|
198
|
+
.trim();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
static #renderContent(content: unknown) {
|
|
202
|
+
if (!Array.isArray(content)) return typeof content === "string" ? content : JSON.stringify(content ?? null);
|
|
203
|
+
return content
|
|
204
|
+
.map((part: { type?: string; text?: string }) =>
|
|
205
|
+
part.type === "text" ? (part.text ?? "") : JSON.stringify(part),
|
|
206
|
+
)
|
|
207
|
+
.join("\n");
|
|
208
|
+
}
|
|
209
|
+
}
|