@armadra/agent 0.12.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.
Files changed (57) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/CHANGELOG.zh-CN.md +16 -0
  3. package/dist/ai/fake/fake-provider.d.ts +6 -0
  4. package/dist/ai/fake/fake-provider.js +46 -0
  5. package/dist/ai/fake/fake-script.d.ts +8 -1
  6. package/dist/ai/fake/fake-script.js +5 -1
  7. package/dist/bridge/pi/args.d.ts +19 -0
  8. package/dist/bridge/pi/args.js +96 -0
  9. package/dist/bridge/pi/capabilities.d.ts +57 -0
  10. package/dist/bridge/pi/capabilities.js +65 -0
  11. package/dist/bridge/pi/config.d.ts +28 -0
  12. package/dist/bridge/pi/config.js +67 -0
  13. package/dist/bridge/pi/elicit.d.ts +23 -0
  14. package/dist/bridge/pi/elicit.js +86 -0
  15. package/dist/bridge/pi/entry.d.ts +14 -0
  16. package/dist/bridge/pi/entry.js +59 -0
  17. package/dist/bridge/pi/events.d.ts +62 -0
  18. package/dist/bridge/pi/events.js +223 -0
  19. package/dist/bridge/pi/gate.d.ts +42 -0
  20. package/dist/bridge/pi/gate.js +69 -0
  21. package/dist/bridge/pi/mcp.d.ts +17 -0
  22. package/dist/bridge/pi/mcp.js +49 -0
  23. package/dist/bridge/pi/prompt.d.ts +8 -0
  24. package/dist/bridge/pi/prompt.js +26 -0
  25. package/dist/bridge/pi/replay.d.ts +10 -0
  26. package/dist/bridge/pi/replay.js +87 -0
  27. package/dist/bridge/pi/server.d.ts +61 -0
  28. package/dist/bridge/pi/server.js +240 -0
  29. package/dist/bridge/pi/session.d.ts +112 -0
  30. package/dist/bridge/pi/session.js +497 -0
  31. package/dist/bridge/pi/tools.d.ts +36 -0
  32. package/dist/bridge/pi/tools.js +129 -0
  33. package/dist/bundle/ama.cjs +2426 -559
  34. package/dist/cli/main.d.ts +1 -0
  35. package/dist/cli/main.js +7 -0
  36. package/dist/codemode/host-side.d.ts +7 -0
  37. package/dist/codemode/host-side.js +7 -2
  38. package/dist/drivers/catalog.js +1 -1
  39. package/dist/drivers/native/pi-extension.d.ts +39 -0
  40. package/dist/drivers/native/pi-extension.js +100 -0
  41. package/dist/drivers/native/pi-rpc-core.d.ts +49 -0
  42. package/dist/drivers/native/pi-rpc-core.js +108 -0
  43. package/dist/drivers/native/pi-rpc.d.ts +4 -1
  44. package/dist/drivers/native/pi-rpc.js +40 -76
  45. package/dist/i18n/catalog.d.ts +56 -0
  46. package/dist/i18n/catalog.js +3 -0
  47. package/dist/i18n/messages/bridge.d.ts +123 -0
  48. package/dist/i18n/messages/bridge.js +123 -0
  49. package/dist/i18n/messages/cli-help.js +4 -0
  50. package/docs/README.md +6 -6
  51. package/docs/en/README.md +1 -1
  52. package/docs/en/reference/acp.md +87 -9
  53. package/docs/guides/agents.md +2 -0
  54. package/docs/reference/acp.md +87 -9
  55. package/package.json +1 -1
  56. package/dist/drivers/native/pi-gate.d.ts +0 -19
  57. package/dist/drivers/native/pi-gate.js +0 -39
@@ -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;
@@ -58,6 +58,13 @@ export interface SandboxRunRequest {
58
58
  requireOsSandbox?: boolean;
59
59
  /** 子进程堆上限(MB),缺省 DEFAULT_CODEMODE_HEAP_MB;0 不设上限。 */
60
60
  maxHeapMb?: number;
61
+ /** 脚本总超时计时器的注入(测试用手动时钟,不随机器负载漂移);缺省真实 `setTimeout`。 */
62
+ timeoutTimers?: TimeoutTimers;
63
+ }
64
+ /** 脚本总超时的计时器(缺省 `setTimeout`)。 */
65
+ export interface TimeoutTimers {
66
+ set(fn: () => void, ms: number): unknown;
67
+ clear(handle: unknown): void;
61
68
  }
62
69
  /** 子进程因堆上限 OOM 退出时给模型的文案(固定英文)。 */
63
70
  export declare function heapLimitError(heapMb: number): string;
@@ -80,6 +80,10 @@ export function sandboxEnv(versions = process.versions, platform = process.platf
80
80
  }
81
81
  return env;
82
82
  }
83
+ const realTimeoutTimers = {
84
+ set: (fn, ms) => setTimeout(fn, ms),
85
+ clear: (handle) => clearTimeout(handle),
86
+ };
83
87
  /** 子进程因堆上限 OOM 退出时给模型的文案(固定英文)。 */
84
88
  export function heapLimitError(heapMb) {
85
89
  return `Script exceeded the codemode memory limit (${heapMb} MB); process the data in smaller pieces`;
@@ -157,7 +161,8 @@ export async function runSandbox(request) {
157
161
  calls.abort();
158
162
  finish();
159
163
  };
160
- const timer = setTimeout(() => {
164
+ const timers = request.timeoutTimers ?? realTimeoutTimers;
165
+ const timer = timers.set(() => {
161
166
  settle({
162
167
  ok: false,
163
168
  timedOut: true,
@@ -280,7 +285,7 @@ export async function runSandbox(request) {
280
285
  store: request.store,
281
286
  });
282
287
  await finished;
283
- clearTimeout(timer);
288
+ timers.clear(timer);
284
289
  if (graceTimer !== undefined)
285
290
  clearTimeout(graceTimer);
286
291
  request.signal.removeEventListener("abort", onAbort);
@@ -222,7 +222,7 @@ export function candidateCapabilities(c) {
222
222
  images: false,
223
223
  };
224
224
  case "pi-rpc":
225
- // 审批经 ama 加载的审批闸扩展交给人(native/pi-gate.ts)
225
+ // 审批经 ama 加载的审批闸扩展交给人(native/pi-extension.ts)
226
226
  return {
227
227
  resume: "resume",
228
228
  list: false,
@@ -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 PI_GATE_SOURCE}),只读内置工具以外的调用
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;