@armadra/agent 0.13.0 → 0.14.0
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/CHANGELOG.md +10 -0
- package/CHANGELOG.zh-CN.md +10 -0
- package/dist/bridge/pi/args.d.ts +19 -0
- package/dist/bridge/pi/args.js +96 -0
- package/dist/bridge/pi/capabilities.d.ts +57 -0
- package/dist/bridge/pi/capabilities.js +65 -0
- package/dist/bridge/pi/config.d.ts +28 -0
- package/dist/bridge/pi/config.js +67 -0
- package/dist/bridge/pi/elicit.d.ts +23 -0
- package/dist/bridge/pi/elicit.js +86 -0
- package/dist/bridge/pi/entry.d.ts +14 -0
- package/dist/bridge/pi/entry.js +59 -0
- package/dist/bridge/pi/events.d.ts +62 -0
- package/dist/bridge/pi/events.js +223 -0
- package/dist/bridge/pi/gate.d.ts +42 -0
- package/dist/bridge/pi/gate.js +69 -0
- package/dist/bridge/pi/mcp.d.ts +17 -0
- package/dist/bridge/pi/mcp.js +49 -0
- package/dist/bridge/pi/prompt.d.ts +8 -0
- package/dist/bridge/pi/prompt.js +26 -0
- package/dist/bridge/pi/replay.d.ts +10 -0
- package/dist/bridge/pi/replay.js +87 -0
- package/dist/bridge/pi/server.d.ts +61 -0
- package/dist/bridge/pi/server.js +240 -0
- package/dist/bridge/pi/session.d.ts +112 -0
- package/dist/bridge/pi/session.js +497 -0
- package/dist/bridge/pi/tools.d.ts +36 -0
- package/dist/bridge/pi/tools.js +129 -0
- package/dist/bundle/ama.cjs +2376 -561
- package/dist/cli/main.d.ts +1 -0
- package/dist/cli/main.js +7 -0
- package/dist/drivers/catalog.js +1 -1
- package/dist/drivers/native/pi-extension.d.ts +39 -0
- package/dist/drivers/native/pi-extension.js +100 -0
- package/dist/drivers/native/pi-rpc-core.d.ts +49 -0
- package/dist/drivers/native/pi-rpc-core.js +108 -0
- package/dist/drivers/native/pi-rpc.d.ts +4 -1
- package/dist/drivers/native/pi-rpc.js +40 -76
- package/dist/i18n/catalog.d.ts +56 -0
- package/dist/i18n/catalog.js +3 -0
- package/dist/i18n/messages/bridge.d.ts +123 -0
- package/dist/i18n/messages/bridge.js +123 -0
- package/dist/i18n/messages/cli-help.js +4 -0
- package/docs/README.md +6 -6
- package/docs/en/README.md +1 -1
- package/docs/en/reference/acp.md +87 -9
- package/docs/guides/agents.md +2 -0
- package/docs/reference/acp.md +87 -9
- package/package.json +1 -1
- package/dist/drivers/native/pi-gate.d.ts +0 -19
- package/dist/drivers/native/pi-gate.js +0 -39
package/dist/cli/main.d.ts
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* `createRuntimeDeps()`(cli/compose.ts,动态 import)。
|
|
15
15
|
* - 签名 `main(argv): Promise<number>` 与「直接执行才自动运行」判定保持不变:
|
|
16
16
|
* src/bundle.ts 显式调用 `main()`。
|
|
17
|
+
* - `--bridge pi`(配 `--mode acp`)在解析前分流到 Pi 的 ACP 桥(bridge/pi),不走 bootstrap。
|
|
17
18
|
* - [W6-C0] 界面语言在解析参数后、任何输出前定一次:`AMA_LANG` > `--lang` > 用户级 `ui.language` >
|
|
18
19
|
* `LC_ALL` / `LC_MESSAGES` / `LANG`(docs/guides/i18n.md);profile / 项目级的 `ui.language` 由 bootstrap 合并后补定。
|
|
19
20
|
*/
|
package/dist/cli/main.js
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* `createRuntimeDeps()`(cli/compose.ts,动态 import)。
|
|
15
15
|
* - 签名 `main(argv): Promise<number>` 与「直接执行才自动运行」判定保持不变:
|
|
16
16
|
* src/bundle.ts 显式调用 `main()`。
|
|
17
|
+
* - `--bridge pi`(配 `--mode acp`)在解析前分流到 Pi 的 ACP 桥(bridge/pi),不走 bootstrap。
|
|
17
18
|
* - [W6-C0] 界面语言在解析参数后、任何输出前定一次:`AMA_LANG` > `--lang` > 用户级 `ui.language` >
|
|
18
19
|
* `LC_ALL` / `LC_MESSAGES` / `LANG`(docs/guides/i18n.md);profile / 项目级的 `ui.language` 由 bootstrap 合并后补定。
|
|
19
20
|
*/
|
|
@@ -35,6 +36,7 @@ import { resolveConfigDir } from "../config/paths.js";
|
|
|
35
36
|
import { runSessions } from "./subcommands/sessions.js";
|
|
36
37
|
import { runStats } from "./subcommands/stats.js";
|
|
37
38
|
import { enableEnvProxy, proxyHint } from "./proxy.js";
|
|
39
|
+
import { bridgeLangOf, hasBridgeFlag } from "../bridge/pi/args.js";
|
|
38
40
|
import { msg, resolveLocale, setLocale } from "../i18n/index.js";
|
|
39
41
|
let registeredDeps;
|
|
40
42
|
/** 集成批次注入运行时实现(B1 / B2 / B3 / B6 / B7)。 */
|
|
@@ -184,6 +186,11 @@ export async function main(argv, options = {}) {
|
|
|
184
186
|
}
|
|
185
187
|
if (options.processHooks !== false)
|
|
186
188
|
installProcessHooks(io);
|
|
189
|
+
// `--bridge pi`:在解析供应商与模型之前分流(不需要 ama 的 key),详见 bridge/pi/entry.ts
|
|
190
|
+
if (hasBridgeFlag(argv)) {
|
|
191
|
+
setLocale(resolveLocale(io.env, { language: peekUserLanguage(io.env) }, bridgeLangOf(argv)));
|
|
192
|
+
return (await import("../bridge/pi/entry.js")).runBridge(argv, io);
|
|
193
|
+
}
|
|
187
194
|
// 缺省装配走动态 import:--version / auth 不加载运行时实现(bundle 里同样内联)。
|
|
188
195
|
// io 交给组装根决定启动期问答(迷你 TUI / 文本 / 不问);--no-tui 在解析后才知道。
|
|
189
196
|
let noTui = false;
|
package/dist/drivers/catalog.js
CHANGED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ama 给每次 pi 运行加载的扩展(`-e <文件>`,#198 审批闸,#254 并入桥):驱动与 ACP 桥共用,源码固定。
|
|
3
|
+
*
|
|
4
|
+
* pi 自己没有审批通道,所以扩展做三件事:
|
|
5
|
+
* 1. **审批闸**:只读内置工具以外的每次工具调用,经 RPC 的扩展对话框(`extension_ui_request{confirm}`,
|
|
6
|
+
* 标题 {@link PI_GATE_TITLE},正文 JSON `{id, tool, input, readOnly, parent?}`)交给 ama;ama 按模式决定直接
|
|
7
|
+
* 拒绝、直接放行或交给人。`readOnly` 取自工具的 `annotations.readOnlyHint`(MCP 工具带服务器声明的值)。
|
|
8
|
+
* 被拒绝时再用 editor 对话框(标题 {@link PI_REASON_TITLE},预填工具调用 id)向 ama 取一句理由,作为
|
|
9
|
+
* 阻止原因回给模型(plan 模式借此告诉模型“现在只许只读”);取不到用默认句。
|
|
10
|
+
* 2. **MCP 透传**:读 `AMA_BRIDGE_CONFIG` 指向的 `bridge.json`,对 `mcpServers` 的每一项调用
|
|
11
|
+
* `pi.registerMcpServer(name, { …, exposure: "direct" })`——ama 自己不说 MCP,连接由 Pi 内置的 MCP 做。
|
|
12
|
+
* 没有这个环境变量(驱动)时什么也不注册。
|
|
13
|
+
* 3. **能力报告**:`session_start` 时用 fire-and-forget 的 `setStatus`(键 {@link PI_STATUS_KEY},正文 JSON
|
|
14
|
+
* `{tools, mcpFailures}`)告诉 ama 当前有哪些工具、哪些 MCP 注册失败。
|
|
15
|
+
*
|
|
16
|
+
* 文件写在每个会话自己的临时目录(`mkdtemp`,目录与文件只有当前用户可读写),会话关闭时整目录删除;
|
|
17
|
+
* 不写 pi 的配置目录,不改用户的扩展设置。扩展源码只用纯 JS 语法(pi 用 jiti 加载)。
|
|
18
|
+
*/
|
|
19
|
+
/** 审批对话框标题:ama 只认这个标题的 confirm,其它扩展的对话框一律取消(不代答)。 */
|
|
20
|
+
export declare const PI_GATE_TITLE = "ama-approval";
|
|
21
|
+
/** 取拒绝理由的 editor 对话框标题。 */
|
|
22
|
+
export declare const PI_REASON_TITLE = "ama-reason";
|
|
23
|
+
/** 能力报告的 `setStatus` 键。 */
|
|
24
|
+
export declare const PI_STATUS_KEY = "ama-bridge";
|
|
25
|
+
/** 指向 `bridge.json` 的环境变量名。 */
|
|
26
|
+
export declare const PI_CONFIG_ENV = "AMA_BRIDGE_CONFIG";
|
|
27
|
+
/** pi 不经审批就放行的内置只读工具。 */
|
|
28
|
+
export declare const PI_READ_ONLY_TOOLS: readonly string[];
|
|
29
|
+
/** 扩展源码(固定,不含时间与随机数)。 */
|
|
30
|
+
export declare const PI_EXTENSION_SOURCE: string;
|
|
31
|
+
export interface PiExtensionFiles {
|
|
32
|
+
/** 扩展文件(`-e` 的参数)。 */
|
|
33
|
+
path: string;
|
|
34
|
+
/** `bridge.json`(`AMA_BRIDGE_CONFIG` 的值);没有配置时不写。 */
|
|
35
|
+
configPath: string | undefined;
|
|
36
|
+
dispose(): void;
|
|
37
|
+
}
|
|
38
|
+
/** 写一份扩展(与可选的 `bridge.json`),返回路径与清理函数。 */
|
|
39
|
+
export declare function writePiExtension(config?: Record<string, unknown>): PiExtensionFiles;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ama 给每次 pi 运行加载的扩展(`-e <文件>`,#198 审批闸,#254 并入桥):驱动与 ACP 桥共用,源码固定。
|
|
3
|
+
*
|
|
4
|
+
* pi 自己没有审批通道,所以扩展做三件事:
|
|
5
|
+
* 1. **审批闸**:只读内置工具以外的每次工具调用,经 RPC 的扩展对话框(`extension_ui_request{confirm}`,
|
|
6
|
+
* 标题 {@link PI_GATE_TITLE},正文 JSON `{id, tool, input, readOnly, parent?}`)交给 ama;ama 按模式决定直接
|
|
7
|
+
* 拒绝、直接放行或交给人。`readOnly` 取自工具的 `annotations.readOnlyHint`(MCP 工具带服务器声明的值)。
|
|
8
|
+
* 被拒绝时再用 editor 对话框(标题 {@link PI_REASON_TITLE},预填工具调用 id)向 ama 取一句理由,作为
|
|
9
|
+
* 阻止原因回给模型(plan 模式借此告诉模型“现在只许只读”);取不到用默认句。
|
|
10
|
+
* 2. **MCP 透传**:读 `AMA_BRIDGE_CONFIG` 指向的 `bridge.json`,对 `mcpServers` 的每一项调用
|
|
11
|
+
* `pi.registerMcpServer(name, { …, exposure: "direct" })`——ama 自己不说 MCP,连接由 Pi 内置的 MCP 做。
|
|
12
|
+
* 没有这个环境变量(驱动)时什么也不注册。
|
|
13
|
+
* 3. **能力报告**:`session_start` 时用 fire-and-forget 的 `setStatus`(键 {@link PI_STATUS_KEY},正文 JSON
|
|
14
|
+
* `{tools, mcpFailures}`)告诉 ama 当前有哪些工具、哪些 MCP 注册失败。
|
|
15
|
+
*
|
|
16
|
+
* 文件写在每个会话自己的临时目录(`mkdtemp`,目录与文件只有当前用户可读写),会话关闭时整目录删除;
|
|
17
|
+
* 不写 pi 的配置目录,不改用户的扩展设置。扩展源码只用纯 JS 语法(pi 用 jiti 加载)。
|
|
18
|
+
*/
|
|
19
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
20
|
+
import { tmpdir } from "node:os";
|
|
21
|
+
import { join } from "node:path";
|
|
22
|
+
/** 审批对话框标题:ama 只认这个标题的 confirm,其它扩展的对话框一律取消(不代答)。 */
|
|
23
|
+
export const PI_GATE_TITLE = "ama-approval";
|
|
24
|
+
/** 取拒绝理由的 editor 对话框标题。 */
|
|
25
|
+
export const PI_REASON_TITLE = "ama-reason";
|
|
26
|
+
/** 能力报告的 `setStatus` 键。 */
|
|
27
|
+
export const PI_STATUS_KEY = "ama-bridge";
|
|
28
|
+
/** 指向 `bridge.json` 的环境变量名。 */
|
|
29
|
+
export const PI_CONFIG_ENV = "AMA_BRIDGE_CONFIG";
|
|
30
|
+
/** pi 不经审批就放行的内置只读工具。 */
|
|
31
|
+
export const PI_READ_ONLY_TOOLS = ["read", "grep", "find", "ls"];
|
|
32
|
+
/** 扩展源码(固定,不含时间与随机数)。 */
|
|
33
|
+
export const PI_EXTENSION_SOURCE = `// Generated by ama for one pi run: approval gate, MCP hand-over, capability report.
|
|
34
|
+
import { readFileSync } from "node:fs";
|
|
35
|
+
const READ_ONLY = new Set(${JSON.stringify(PI_READ_ONLY_TOOLS)});
|
|
36
|
+
function readConfig() {
|
|
37
|
+
const file = process.env[${JSON.stringify(PI_CONFIG_ENV)}];
|
|
38
|
+
if (!file) return {};
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
41
|
+
} catch {
|
|
42
|
+
return {};
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export default function (pi) {
|
|
46
|
+
const config = readConfig();
|
|
47
|
+
const failures = [];
|
|
48
|
+
if (typeof pi.registerMcpServer === "function") {
|
|
49
|
+
for (const [name, server] of Object.entries(config.mcpServers || {})) {
|
|
50
|
+
try {
|
|
51
|
+
pi.registerMcpServer(name, Object.assign({}, server, { exposure: "direct" }));
|
|
52
|
+
} catch (error) {
|
|
53
|
+
failures.push(name + ": " + (error && error.message ? error.message : String(error)));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const allTools = () => (typeof pi.getAllTools === "function" ? pi.getAllTools() : []);
|
|
58
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
59
|
+
ctx.ui.setStatus(
|
|
60
|
+
${JSON.stringify(PI_STATUS_KEY)},
|
|
61
|
+
JSON.stringify({ tools: allTools().map((tool) => tool.name), mcpFailures: failures }),
|
|
62
|
+
);
|
|
63
|
+
});
|
|
64
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
65
|
+
if (READ_ONLY.has(event.toolName)) return undefined;
|
|
66
|
+
const tool = allTools().find((candidate) => candidate.name === event.toolName);
|
|
67
|
+
const hints = tool && tool.annotations;
|
|
68
|
+
const ok = await ctx.ui.confirm(
|
|
69
|
+
${JSON.stringify(PI_GATE_TITLE)},
|
|
70
|
+
JSON.stringify({
|
|
71
|
+
id: event.toolCallId,
|
|
72
|
+
tool: event.toolName,
|
|
73
|
+
input: event.input,
|
|
74
|
+
readOnly: Boolean(hints && hints.readOnlyHint === true),
|
|
75
|
+
parent: event.parentToolCallId,
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
if (ok) return undefined;
|
|
79
|
+
let reason = "";
|
|
80
|
+
try {
|
|
81
|
+
reason = (await ctx.ui.editor(${JSON.stringify(PI_REASON_TITLE)}, event.toolCallId)) || "";
|
|
82
|
+
} catch {
|
|
83
|
+
reason = "";
|
|
84
|
+
}
|
|
85
|
+
return { block: true, reason: reason || event.toolName + " was not approved by the user" };
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
`;
|
|
89
|
+
/** 写一份扩展(与可选的 `bridge.json`),返回路径与清理函数。 */
|
|
90
|
+
export function writePiExtension(config) {
|
|
91
|
+
const dir = mkdtempSync(join(tmpdir(), "ama-pi-"));
|
|
92
|
+
const path = join(dir, "ama-bridge.ts");
|
|
93
|
+
writeFileSync(path, PI_EXTENSION_SOURCE, { mode: 0o600 });
|
|
94
|
+
let configPath;
|
|
95
|
+
if (config !== undefined) {
|
|
96
|
+
configPath = join(dir, "bridge.json");
|
|
97
|
+
writeFileSync(configPath, JSON.stringify(config), { mode: 0o600 });
|
|
98
|
+
}
|
|
99
|
+
return { path, configPath, dispose: () => rmSync(dir, { recursive: true, force: true }) };
|
|
100
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi `--mode rpc` 的传输核心(驱动 `pi-rpc.ts` 与 ACP 桥 `bridge/pi` 共用,#254)。
|
|
3
|
+
*
|
|
4
|
+
* - 分帧:stdout 严格按 LF 切行(`createLineReader`),stdin 每条命令一行 JSON;
|
|
5
|
+
* - 请求关联:每条命令带 `ama-<n>` 的 id,`response` 按 id 回到等待者;不带 id 的应答(旧版 Pi 对未知
|
|
6
|
+
* 命令、坏 JSON 的应答)无从关联,直接忽略——所以这里**只发调用方列出的命令**(`commands`),
|
|
7
|
+
* 并给每条非 prompt 命令一个 10 秒截止,到点以 `agent_timeout` 失败而不是永远等;
|
|
8
|
+
* - 进程退出:所有挂起请求以 `agent_exited` 失败,并通知调用方一次;
|
|
9
|
+
* - 事件与扩展 UI 请求原样交给调用方,核心不解释。
|
|
10
|
+
*/
|
|
11
|
+
import { AmaError } from "../../errors.js";
|
|
12
|
+
import { type AgentTransport } from "../process.js";
|
|
13
|
+
export type Json = Record<string, unknown>;
|
|
14
|
+
/** 非 prompt 命令的截止。 */
|
|
15
|
+
export declare const PI_COMMAND_DEADLINE_MS = 10000;
|
|
16
|
+
export interface PiRpcCoreOptions {
|
|
17
|
+
transport: AgentTransport;
|
|
18
|
+
/** 只允许发这些命令(缺省不限);不在表里的命令不上线,直接 `agent_failed`。 */
|
|
19
|
+
commands?: ReadonlySet<string>;
|
|
20
|
+
/** `response`、`extension_ui_request` 以外的每条记录。 */
|
|
21
|
+
onEvent(record: Json): void;
|
|
22
|
+
/** `extension_ui_request`(对话框与 fire-and-forget 都在这里)。 */
|
|
23
|
+
onUiRequest(record: Json): void;
|
|
24
|
+
/** 进程退出(输出流结束),只调一次。 */
|
|
25
|
+
onExit(error: AmaError): void;
|
|
26
|
+
/** 一行不是 JSON。 */
|
|
27
|
+
onNonJson?(): void;
|
|
28
|
+
/** 退出错误的文案(缺省 `pi process exited[: <stderr 尾部>]`)。 */
|
|
29
|
+
exitMessage?(hint: string): string;
|
|
30
|
+
/** 截止错误的文案(缺省 `pi did not answer <command> in time`)。 */
|
|
31
|
+
timeoutMessage?(command: string): string;
|
|
32
|
+
deadlineMs?: number;
|
|
33
|
+
setTimer?(fn: () => void, ms: number): () => void;
|
|
34
|
+
}
|
|
35
|
+
export declare class PiRpcCore {
|
|
36
|
+
private readonly options;
|
|
37
|
+
private nextId;
|
|
38
|
+
private readonly pending;
|
|
39
|
+
private isExited;
|
|
40
|
+
constructor(options: PiRpcCoreOptions);
|
|
41
|
+
get exited(): boolean;
|
|
42
|
+
exitError(): AmaError;
|
|
43
|
+
/** 发命令并等应答;`prompt` 不设截止(它的应答只表示「已接收」,但模型启动前的扩展钩子可能较慢)。 */
|
|
44
|
+
request(command: Json): Promise<Json>;
|
|
45
|
+
/** 写一行(进程已退出则丢弃)。 */
|
|
46
|
+
write(record: Json): void;
|
|
47
|
+
private onEnd;
|
|
48
|
+
private onLine;
|
|
49
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi `--mode rpc` 的传输核心(驱动 `pi-rpc.ts` 与 ACP 桥 `bridge/pi` 共用,#254)。
|
|
3
|
+
*
|
|
4
|
+
* - 分帧:stdout 严格按 LF 切行(`createLineReader`),stdin 每条命令一行 JSON;
|
|
5
|
+
* - 请求关联:每条命令带 `ama-<n>` 的 id,`response` 按 id 回到等待者;不带 id 的应答(旧版 Pi 对未知
|
|
6
|
+
* 命令、坏 JSON 的应答)无从关联,直接忽略——所以这里**只发调用方列出的命令**(`commands`),
|
|
7
|
+
* 并给每条非 prompt 命令一个 10 秒截止,到点以 `agent_timeout` 失败而不是永远等;
|
|
8
|
+
* - 进程退出:所有挂起请求以 `agent_exited` 失败,并通知调用方一次;
|
|
9
|
+
* - 事件与扩展 UI 请求原样交给调用方,核心不解释。
|
|
10
|
+
*/
|
|
11
|
+
import { AmaError } from "../../errors.js";
|
|
12
|
+
import { createLineReader } from "../../modes/rpc/jsonl.js";
|
|
13
|
+
import { stderrHint } from "../process.js";
|
|
14
|
+
/** 非 prompt 命令的截止。 */
|
|
15
|
+
export const PI_COMMAND_DEADLINE_MS = 10_000;
|
|
16
|
+
function defaultSetTimer(fn, ms) {
|
|
17
|
+
const timer = setTimeout(fn, ms);
|
|
18
|
+
timer.unref?.();
|
|
19
|
+
return () => clearTimeout(timer);
|
|
20
|
+
}
|
|
21
|
+
export class PiRpcCore {
|
|
22
|
+
options;
|
|
23
|
+
nextId = 1;
|
|
24
|
+
pending = new Map();
|
|
25
|
+
isExited = false;
|
|
26
|
+
constructor(options) {
|
|
27
|
+
this.options = options;
|
|
28
|
+
createLineReader(options.transport.stdout, (line) => this.onLine(line), () => this.onEnd());
|
|
29
|
+
options.transport.stdin.on?.("error", () => undefined);
|
|
30
|
+
}
|
|
31
|
+
get exited() {
|
|
32
|
+
return this.isExited;
|
|
33
|
+
}
|
|
34
|
+
exitError() {
|
|
35
|
+
const hint = stderrHint(this.options.transport);
|
|
36
|
+
const text = this.options.exitMessage?.(hint) ?? `pi process exited${hint !== "" ? `: ${hint}` : ""}`;
|
|
37
|
+
return new AmaError("agent_exited", text);
|
|
38
|
+
}
|
|
39
|
+
/** 发命令并等应答;`prompt` 不设截止(它的应答只表示「已接收」,但模型启动前的扩展钩子可能较慢)。 */
|
|
40
|
+
request(command) {
|
|
41
|
+
const name = String(command["type"] ?? "");
|
|
42
|
+
if (this.isExited)
|
|
43
|
+
return Promise.reject(this.exitError());
|
|
44
|
+
const allowed = this.options.commands;
|
|
45
|
+
if (allowed !== undefined && !allowed.has(name))
|
|
46
|
+
return Promise.reject(new AmaError("agent_failed", `pi command not supported: ${name}`));
|
|
47
|
+
const id = `ama-${this.nextId++}`;
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const entry = { command: name, resolve, reject, clear: () => undefined };
|
|
50
|
+
if (name !== "prompt") {
|
|
51
|
+
const setTimer = this.options.setTimer ?? defaultSetTimer;
|
|
52
|
+
entry.clear = setTimer(() => {
|
|
53
|
+
if (this.pending.delete(id))
|
|
54
|
+
reject(new AmaError("agent_timeout", this.options.timeoutMessage?.(name) ?? `pi did not answer ${name} in time`));
|
|
55
|
+
}, this.options.deadlineMs ?? PI_COMMAND_DEADLINE_MS);
|
|
56
|
+
}
|
|
57
|
+
this.pending.set(id, entry);
|
|
58
|
+
this.write({ id, ...command });
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
/** 写一行(进程已退出则丢弃)。 */
|
|
62
|
+
write(record) {
|
|
63
|
+
if (this.isExited)
|
|
64
|
+
return;
|
|
65
|
+
this.options.transport.stdin.write(`${JSON.stringify(record)}\n`);
|
|
66
|
+
}
|
|
67
|
+
onEnd() {
|
|
68
|
+
if (this.isExited)
|
|
69
|
+
return;
|
|
70
|
+
this.isExited = true;
|
|
71
|
+
const error = this.exitError();
|
|
72
|
+
for (const p of this.pending.values()) {
|
|
73
|
+
p.clear();
|
|
74
|
+
p.reject(error);
|
|
75
|
+
}
|
|
76
|
+
this.pending.clear();
|
|
77
|
+
this.options.onExit(error);
|
|
78
|
+
}
|
|
79
|
+
onLine(line) {
|
|
80
|
+
let record;
|
|
81
|
+
try {
|
|
82
|
+
record = JSON.parse(line);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
this.options.onNonJson?.();
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
switch (record["type"]) {
|
|
89
|
+
case "response": {
|
|
90
|
+
const id = record["id"];
|
|
91
|
+
if (typeof id !== "string")
|
|
92
|
+
return;
|
|
93
|
+
const pending = this.pending.get(id);
|
|
94
|
+
if (pending === undefined)
|
|
95
|
+
return;
|
|
96
|
+
this.pending.delete(id);
|
|
97
|
+
pending.clear();
|
|
98
|
+
pending.resolve(record);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
case "extension_ui_request":
|
|
102
|
+
this.options.onUiRequest(record);
|
|
103
|
+
return;
|
|
104
|
+
default:
|
|
105
|
+
this.options.onEvent(record);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* - 回合:`prompt` → 响应 `disposition`(`handled` 时没有运行,直接结束)→ 事件流 → `agent_settled`
|
|
8
8
|
* 结束(`aborted` 为真即中断);运行中追加用 `steer`;中断 `abort`(15 s 看门狗)。
|
|
9
|
-
* - 审批:pi 自己不问人,ama 以 `-e` 加载审批闸({@link
|
|
9
|
+
* - 审批:pi 自己不问人,ama 以 `-e` 加载审批闸({@link PI_EXTENSION_SOURCE}),只读内置工具以外的调用
|
|
10
10
|
* 经 `extension_ui_request{confirm, title: "ama-approval"}` 到这里:plan / allowlist 直接拒绝(并以
|
|
11
11
|
* `--tools` 只开只读工具),auto-edit / auto / full-auto 放行 `edit` / `write`,其余交给人(只交给人,
|
|
12
12
|
* 不代答)。其它扩展的对话框(select / input / editor / 别的 confirm)一律取消并提示。
|
|
@@ -16,8 +16,11 @@
|
|
|
16
16
|
import { type DriverDeps } from "../base.js";
|
|
17
17
|
import type { CatalogCandidate } from "../catalog.js";
|
|
18
18
|
import type { AcpToolKind, AgentDriver, DriverOpenOptions, DriverProbe, DriverSession } from "../types.js";
|
|
19
|
+
import { type Json } from "./pi-rpc-core.js";
|
|
19
20
|
export declare function piArgs(options: Pick<DriverOpenOptions, "mode" | "model">, sessionId: string, gatePath: string): string[];
|
|
20
21
|
export declare function piToolKind(tool: string): AcpToolKind;
|
|
22
|
+
export declare function piToolTitle(tool: string, input: Json): string;
|
|
23
|
+
export declare function textOf(message: Json): string;
|
|
21
24
|
export declare class PiRpcDriver implements AgentDriver {
|
|
22
25
|
readonly agentId: string;
|
|
23
26
|
private readonly candidate;
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* - 回合:`prompt` → 响应 `disposition`(`handled` 时没有运行,直接结束)→ 事件流 → `agent_settled`
|
|
8
8
|
* 结束(`aborted` 为真即中断);运行中追加用 `steer`;中断 `abort`(15 s 看门狗)。
|
|
9
|
-
* - 审批:pi 自己不问人,ama 以 `-e` 加载审批闸({@link
|
|
9
|
+
* - 审批:pi 自己不问人,ama 以 `-e` 加载审批闸({@link PI_EXTENSION_SOURCE}),只读内置工具以外的调用
|
|
10
10
|
* 经 `extension_ui_request{confirm, title: "ama-approval"}` 到这里:plan / allowlist 直接拒绝(并以
|
|
11
11
|
* `--tools` 只开只读工具),auto-edit / auto / full-auto 放行 `edit` / `write`,其余交给人(只交给人,
|
|
12
12
|
* 不代答)。其它扩展的对话框(select / input / editor / 别的 confirm)一律取消并提示。
|
|
@@ -16,11 +16,11 @@
|
|
|
16
16
|
import { randomUUID } from "node:crypto";
|
|
17
17
|
import { resolve as resolvePath } from "node:path";
|
|
18
18
|
import { AmaError } from "../../errors.js";
|
|
19
|
-
import { createLineReader } from "../../modes/rpc/jsonl.js";
|
|
20
19
|
import { armCancelWatchdog, isReadOnlyMode, probeCandidate, spawnOf, } from "../base.js";
|
|
21
20
|
import { stderrHint } from "../process.js";
|
|
22
21
|
import { TurnCollector, oneLine } from "../turn.js";
|
|
23
|
-
import { PI_GATE_TITLE, PI_READ_ONLY_TOOLS,
|
|
22
|
+
import { PI_GATE_TITLE, PI_READ_ONLY_TOOLS, PI_REASON_TITLE, writePiExtension, } from "./pi-extension.js";
|
|
23
|
+
import { PiRpcCore } from "./pi-rpc-core.js";
|
|
24
24
|
import { msg } from "../../i18n/index.js";
|
|
25
25
|
const DIALOG_METHODS = new Set(["select", "confirm", "input", "editor"]);
|
|
26
26
|
/** auto-edit 及更宽的模式下不问人的文件编辑工具。 */
|
|
@@ -52,7 +52,7 @@ export function piToolKind(tool) {
|
|
|
52
52
|
return "other";
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
|
-
function piToolTitle(tool, input) {
|
|
55
|
+
export function piToolTitle(tool, input) {
|
|
56
56
|
if (typeof input["command"] === "string")
|
|
57
57
|
return `$ ${oneLine(input["command"], 100)}`;
|
|
58
58
|
if (typeof input["path"] === "string")
|
|
@@ -61,7 +61,7 @@ function piToolTitle(tool, input) {
|
|
|
61
61
|
return `${tool} ${oneLine(input["pattern"], 80)}`;
|
|
62
62
|
return tool;
|
|
63
63
|
}
|
|
64
|
-
function textOf(message) {
|
|
64
|
+
export function textOf(message) {
|
|
65
65
|
const content = message["content"];
|
|
66
66
|
if (typeof content === "string")
|
|
67
67
|
return content;
|
|
@@ -87,7 +87,7 @@ export class PiRpcDriver {
|
|
|
87
87
|
async open(options) {
|
|
88
88
|
const probed = await probeCandidate(this.candidate, this.deps);
|
|
89
89
|
const sessionId = options.resume ?? randomUUID();
|
|
90
|
-
const gate =
|
|
90
|
+
const gate = writePiExtension();
|
|
91
91
|
const transport = spawnOf(this.deps)({
|
|
92
92
|
program: probed.path ?? this.candidate.program,
|
|
93
93
|
args: [...this.candidate.args, ...piArgs(options, sessionId, gate.path)],
|
|
@@ -115,8 +115,7 @@ class PiSession {
|
|
|
115
115
|
deps;
|
|
116
116
|
dispose;
|
|
117
117
|
notices = [];
|
|
118
|
-
|
|
119
|
-
pending = new Map();
|
|
118
|
+
core;
|
|
120
119
|
permissions = new Set();
|
|
121
120
|
turn;
|
|
122
121
|
hooks;
|
|
@@ -126,7 +125,6 @@ class PiSession {
|
|
|
126
125
|
lastAssistant;
|
|
127
126
|
interrupted = false;
|
|
128
127
|
closed = false;
|
|
129
|
-
exited = false;
|
|
130
128
|
exitWaiters = new Set();
|
|
131
129
|
constructor(agentId, id, transport, options, deps, dispose) {
|
|
132
130
|
this.agentId = agentId;
|
|
@@ -135,8 +133,15 @@ class PiSession {
|
|
|
135
133
|
this.options = options;
|
|
136
134
|
this.deps = deps;
|
|
137
135
|
this.dispose = dispose;
|
|
138
|
-
|
|
139
|
-
|
|
136
|
+
this.core = new PiRpcCore({
|
|
137
|
+
transport,
|
|
138
|
+
onEvent: (record) => this.onRecord(record),
|
|
139
|
+
onUiRequest: (record) => void this.onDialog(record),
|
|
140
|
+
onExit: (error) => this.onExit(error),
|
|
141
|
+
onNonJson: () => this.deps.log?.("debug", msg().drivers.agent.nonJson(this.agentId)),
|
|
142
|
+
exitMessage: (hint) => `${this.agentId} process exited${hint !== "" ? `: ${hint}` : ""}`,
|
|
143
|
+
timeoutMessage: (command) => `${this.agentId} did not answer ${command} in time`,
|
|
144
|
+
});
|
|
140
145
|
}
|
|
141
146
|
get sessionId() {
|
|
142
147
|
return this.id;
|
|
@@ -149,13 +154,13 @@ class PiSession {
|
|
|
149
154
|
signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true });
|
|
150
155
|
});
|
|
151
156
|
void aborted.catch(() => undefined);
|
|
152
|
-
const state = await Promise.race([this.request({ type: "get_state" }), aborted]);
|
|
157
|
+
const state = await Promise.race([this.core.request({ type: "get_state" }), aborted]);
|
|
153
158
|
const data = (state["data"] ?? {});
|
|
154
159
|
if (typeof data["sessionId"] === "string" && data["sessionId"] !== "")
|
|
155
160
|
this.id = data["sessionId"];
|
|
156
161
|
}
|
|
157
162
|
async prompt(content, hooks) {
|
|
158
|
-
if (this.closed || this.exited)
|
|
163
|
+
if (this.closed || this.core.exited)
|
|
159
164
|
throw new AmaError("agent_closed", `${this.agentId} session is closed`);
|
|
160
165
|
if (this.running !== undefined)
|
|
161
166
|
throw new AmaError("busy", `${this.agentId} is already running`);
|
|
@@ -183,7 +188,7 @@ class PiSession {
|
|
|
183
188
|
// 先让出一拍:`this.running` 赋值之后再写命令(同步回显的对端里事件可能立刻到达并触发 cancel)
|
|
184
189
|
await Promise.resolve();
|
|
185
190
|
const settled = new Promise((resolve) => (this.settle = resolve));
|
|
186
|
-
const response = await this.request({ type: "prompt", ...this.message(content) });
|
|
191
|
+
const response = await this.core.request({ type: "prompt", ...this.message(content) });
|
|
187
192
|
if (response["success"] !== true)
|
|
188
193
|
throw new AmaError("agent_failed", `${this.agentId} rejected the prompt: ${oneLine(String(response["error"] ?? "unknown"), 300)}`);
|
|
189
194
|
const disposition = (response["data"] ?? {})["disposition"];
|
|
@@ -194,9 +199,9 @@ class PiSession {
|
|
|
194
199
|
return this.complete(turn, aborted);
|
|
195
200
|
}
|
|
196
201
|
async steer(content) {
|
|
197
|
-
if (this.closed || this.exited)
|
|
202
|
+
if (this.closed || this.core.exited)
|
|
198
203
|
throw new AmaError("agent_closed", `${this.agentId} session is closed`);
|
|
199
|
-
await this.request({ type: "steer", ...this.message(content) });
|
|
204
|
+
await this.core.request({ type: "steer", ...this.message(content) });
|
|
200
205
|
}
|
|
201
206
|
async cancel() {
|
|
202
207
|
const running = this.running;
|
|
@@ -205,7 +210,7 @@ class PiSession {
|
|
|
205
210
|
this.interrupted = true;
|
|
206
211
|
for (const c of this.permissions)
|
|
207
212
|
c.abort();
|
|
208
|
-
void this.request({ type: "abort" }).catch(() => undefined);
|
|
213
|
+
void this.core.request({ type: "abort" }).catch(() => undefined);
|
|
209
214
|
armCancelWatchdog(this.transport, running.catch(() => undefined), this.deps);
|
|
210
215
|
}
|
|
211
216
|
async close() {
|
|
@@ -216,7 +221,7 @@ class PiSession {
|
|
|
216
221
|
c.abort();
|
|
217
222
|
if (this.running !== undefined) {
|
|
218
223
|
this.interrupted = true;
|
|
219
|
-
this.write({ type: "abort" });
|
|
224
|
+
this.core.write({ type: "abort" });
|
|
220
225
|
}
|
|
221
226
|
try {
|
|
222
227
|
await this.transport.terminate();
|
|
@@ -261,11 +266,11 @@ class PiSession {
|
|
|
261
266
|
}
|
|
262
267
|
/** `get_session_stats.contextUsage` → 上下文占用与窗口(拿不到就算了)。 */
|
|
263
268
|
async reportContext(turn) {
|
|
264
|
-
if (this.exited)
|
|
269
|
+
if (this.core.exited)
|
|
265
270
|
return;
|
|
266
271
|
try {
|
|
267
272
|
const stats = await Promise.race([
|
|
268
|
-
this.request({ type: "get_session_stats" }),
|
|
273
|
+
this.core.request({ type: "get_session_stats" }),
|
|
269
274
|
new Promise((resolve) => setTimeout(() => resolve({}), 5_000).unref()),
|
|
270
275
|
]);
|
|
271
276
|
const usage = ((stats["data"] ?? {})["contextUsage"] ?? {});
|
|
@@ -284,70 +289,24 @@ class PiSession {
|
|
|
284
289
|
}
|
|
285
290
|
exitPromise() {
|
|
286
291
|
return new Promise((_, reject) => {
|
|
287
|
-
if (this.exited)
|
|
288
|
-
reject(this.exitError());
|
|
292
|
+
if (this.core.exited)
|
|
293
|
+
reject(this.core.exitError());
|
|
289
294
|
else
|
|
290
295
|
this.exitWaiters.add(reject);
|
|
291
296
|
});
|
|
292
297
|
}
|
|
293
|
-
|
|
294
|
-
const hint = stderrHint(this.transport);
|
|
295
|
-
return new AmaError("agent_exited", `${this.agentId} process exited${hint !== "" ? `: ${hint}` : ""}`);
|
|
296
|
-
}
|
|
297
|
-
request(command) {
|
|
298
|
-
if (this.exited)
|
|
299
|
-
return Promise.reject(this.exitError());
|
|
300
|
-
const id = `ama-${this.nextId++}`;
|
|
301
|
-
return new Promise((resolve, reject) => {
|
|
302
|
-
this.pending.set(id, { resolve, reject });
|
|
303
|
-
this.write({ id, ...command });
|
|
304
|
-
});
|
|
305
|
-
}
|
|
306
|
-
write(record) {
|
|
307
|
-
if (this.exited)
|
|
308
|
-
return;
|
|
309
|
-
this.transport.stdin.write(`${JSON.stringify(record)}\n`);
|
|
310
|
-
}
|
|
311
|
-
onExit() {
|
|
312
|
-
this.exited = true;
|
|
313
|
-
const error = this.exitError();
|
|
314
|
-
for (const p of this.pending.values())
|
|
315
|
-
p.reject(error);
|
|
316
|
-
this.pending.clear();
|
|
298
|
+
onExit(error) {
|
|
317
299
|
for (const reject of this.exitWaiters)
|
|
318
300
|
reject(error);
|
|
319
301
|
this.exitWaiters.clear();
|
|
320
302
|
for (const c of this.permissions)
|
|
321
303
|
c.abort();
|
|
322
304
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
catch {
|
|
329
|
-
this.deps.log?.("debug", msg().drivers.agent.nonJson(this.agentId));
|
|
330
|
-
return;
|
|
331
|
-
}
|
|
332
|
-
switch (record["type"]) {
|
|
333
|
-
case "response": {
|
|
334
|
-
const id = record["id"];
|
|
335
|
-
const pending = typeof id === "string" ? this.pending.get(id) : undefined;
|
|
336
|
-
if (pending === undefined || typeof id !== "string")
|
|
337
|
-
return;
|
|
338
|
-
this.pending.delete(id);
|
|
339
|
-
pending.resolve(record);
|
|
340
|
-
return;
|
|
341
|
-
}
|
|
342
|
-
case "agent_settled":
|
|
343
|
-
this.settle?.(record["aborted"] === true);
|
|
344
|
-
return;
|
|
345
|
-
case "extension_ui_request":
|
|
346
|
-
void this.onDialog(record);
|
|
347
|
-
return;
|
|
348
|
-
default:
|
|
349
|
-
this.onEvent(record);
|
|
350
|
-
}
|
|
305
|
+
onRecord(record) {
|
|
306
|
+
if (record["type"] === "agent_settled")
|
|
307
|
+
this.settle?.(record["aborted"] === true);
|
|
308
|
+
else
|
|
309
|
+
this.onEvent(record);
|
|
351
310
|
}
|
|
352
311
|
onEvent(record) {
|
|
353
312
|
const turn = this.turn;
|
|
@@ -427,17 +386,22 @@ class PiSession {
|
|
|
427
386
|
});
|
|
428
387
|
return;
|
|
429
388
|
}
|
|
389
|
+
// 审批闸被拒绝后向 ama 取理由的 editor:驱动没有自定义理由,静默取消(扩展用默认句)
|
|
390
|
+
if (method === "editor" && record["title"] === PI_REASON_TITLE) {
|
|
391
|
+
this.core.write({ type: "extension_ui_response", id, cancelled: true });
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
430
394
|
if (method !== "confirm" || record["title"] !== PI_GATE_TITLE) {
|
|
431
395
|
this.turn?.push({
|
|
432
396
|
type: "notice",
|
|
433
397
|
level: "warn",
|
|
434
398
|
text: msg().drivers.agent.extensionDialog(this.agentId, oneLine(String(record["title"] ?? method), 80)),
|
|
435
399
|
});
|
|
436
|
-
this.write({ type: "extension_ui_response", id, cancelled: true });
|
|
400
|
+
this.core.write({ type: "extension_ui_response", id, cancelled: true });
|
|
437
401
|
return;
|
|
438
402
|
}
|
|
439
403
|
const confirmed = await this.decide(record);
|
|
440
|
-
this.write({ type: "extension_ui_response", id, confirmed });
|
|
404
|
+
this.core.write({ type: "extension_ui_response", id, confirmed });
|
|
441
405
|
}
|
|
442
406
|
async decide(record) {
|
|
443
407
|
let call;
|