@armadra/agent 0.18.0 → 0.19.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 (82) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/CHANGELOG.zh-CN.md +20 -0
  3. package/README.md +4 -0
  4. package/README.zh-CN.md +4 -0
  5. package/dist/bundle/ama.cjs +25956 -25161
  6. package/dist/cli/bootstrap.js +32 -6
  7. package/dist/cli/compose-agents.js +2 -1
  8. package/dist/cli/compose-extensions-load.d.ts +20 -0
  9. package/dist/cli/compose-extensions-load.js +38 -0
  10. package/dist/cli/compose.js +1 -0
  11. package/dist/cli/deps.d.ts +11 -0
  12. package/dist/cli/runtime.d.ts +7 -0
  13. package/dist/cli/subcommands/doctor.js +33 -0
  14. package/dist/config/extension-tree-hash.d.ts +31 -0
  15. package/dist/config/extension-tree-hash.js +88 -0
  16. package/dist/config/extension-trust.d.ts +70 -0
  17. package/dist/config/extension-trust.js +112 -0
  18. package/dist/config/profile.d.ts +2 -0
  19. package/dist/config/profile.js +1 -0
  20. package/dist/config/schema-trust.d.ts +7 -0
  21. package/dist/config/schema-trust.js +46 -0
  22. package/dist/config/schema.d.ts +4 -5
  23. package/dist/config/schema.js +3 -25
  24. package/dist/config/trust.d.ts +2 -0
  25. package/dist/config/trust.js +5 -1
  26. package/dist/config/types.d.ts +13 -0
  27. package/dist/drivers/host-runners.d.ts +15 -4
  28. package/dist/drivers/host-runners.js +31 -17
  29. package/dist/errors.d.ts +1 -1
  30. package/dist/host/api-impl.d.ts +47 -4
  31. package/dist/host/api-impl.js +181 -20
  32. package/dist/host/commands.d.ts +23 -0
  33. package/dist/host/commands.js +76 -0
  34. package/dist/host/extensions.d.ts +43 -0
  35. package/dist/host/extensions.js +117 -0
  36. package/dist/host/resources.d.ts +2 -0
  37. package/dist/host/resources.js +5 -0
  38. package/dist/host/types.d.ts +41 -2
  39. package/dist/host/types.js +4 -2
  40. package/dist/i18n/catalog.d.ts +31 -0
  41. package/dist/i18n/messages/cli.d.ts +24 -0
  42. package/dist/i18n/messages/cli.js +24 -0
  43. package/dist/i18n/messages/drivers.d.ts +22 -0
  44. package/dist/i18n/messages/drivers.js +22 -0
  45. package/dist/i18n/messages/errors.d.ts +1 -1
  46. package/dist/i18n/messages/interactive-startup.d.ts +4 -0
  47. package/dist/i18n/messages/interactive-startup.js +4 -0
  48. package/dist/i18n/messages/interactive.d.ts +4 -0
  49. package/dist/i18n/messages/report.d.ts +12 -0
  50. package/dist/i18n/messages/report.js +12 -0
  51. package/dist/modes/acp/acp-config.d.ts +4 -2
  52. package/dist/modes/acp/acp-config.js +17 -3
  53. package/dist/modes/acp/acp-events.d.ts +2 -0
  54. package/dist/modes/acp/acp-events.js +4 -0
  55. package/dist/modes/acp/acp-server.js +6 -2
  56. package/dist/modes/acp/acp-sessions.d.ts +8 -1
  57. package/dist/modes/acp/acp-sessions.js +18 -0
  58. package/dist/modes/commands-core.d.ts +14 -1
  59. package/dist/modes/commands-core.js +34 -2
  60. package/dist/modes/interactive/startup-ui.js +21 -0
  61. package/dist/modes/interactive/status-area.js +1 -1
  62. package/dist/modes/print/print-mode.d.ts +3 -0
  63. package/dist/modes/print/print-mode.js +35 -8
  64. package/dist/modes/rpc/commands.d.ts +2 -0
  65. package/dist/modes/rpc/commands.js +22 -7
  66. package/dist/modes/rpc/rpc-mode.js +3 -0
  67. package/dist/modes/startup-ui-text.js +11 -0
  68. package/dist/rpc.d.ts +2 -1
  69. package/dist/tools/registry.d.ts +6 -0
  70. package/dist/tools/registry.js +13 -0
  71. package/dist/tools/types.d.ts +7 -0
  72. package/docs/README.md +1 -1
  73. package/docs/en/README.md +3 -3
  74. package/docs/en/guides/extensions.md +141 -0
  75. package/docs/en/reference/acp.md +1 -1
  76. package/docs/en/reference/host-api.md +55 -27
  77. package/docs/en/reference/rpc.md +9 -7
  78. package/docs/guides/extensions.md +136 -0
  79. package/docs/reference/acp.md +1 -1
  80. package/docs/reference/host-api.md +55 -27
  81. package/docs/reference/rpc.md +9 -7
  82. package/package.json +4 -2
@@ -58,6 +58,8 @@ export interface CommandInfo {
58
58
  name: string;
59
59
  args?: string;
60
60
  description: string;
61
+ /** [#301] 经 `commands.register` 注册的命令(宿主适配器 / 本地扩展);缺省为内置。 */
62
+ source?: "extension";
61
63
  /** 只在该能力可用时列出(`/help`、补全、RPC `get_commands`);输入时照常分派。 */
62
64
  requires?: "memory" | "task";
63
65
  }
@@ -66,9 +68,20 @@ export declare const BUILTIN_COMMANDS: readonly CommandInfo[];
66
68
  * 能力关闭的命令不列出(capability-off.test.ts 锁定):memory = 记忆工具已注册(`memory.enabled`);
67
69
  * task = 模型能直接调 `task`,或能经 codemode 脚本调(`task` 已注册且 codemode 在活动集)。
68
70
  */
69
- export declare function availableCommands(runtime: Pick<Runtime, "tools">, session: Pick<AgentSession, "getTools">, list?: readonly CommandInfo[]): CommandInfo[];
71
+ export declare function availableCommands(runtime: Pick<Runtime, "tools" | "hostCommands">, session: Pick<AgentSession, "getTools">, list?: readonly CommandInfo[]): CommandInfo[];
72
+ /** 交互界面自己处理的命令(interactive/commands.ts 的 INTERACTIVE_COMMANDS;测试锁定一致)。 */
73
+ export declare const INTERACTIVE_COMMAND_NAMES: readonly string[];
74
+ /** [#301] 保留的命令名:内置命令、别名与交互界面命令;`commands.register` 不得占用。 */
75
+ export declare function isReservedCommandName(name: string): boolean;
70
76
  export declare function parseSlash(line: string): {
71
77
  name: string;
72
78
  args: string;
73
79
  } | undefined;
74
80
  export declare function runSlashCommand(line: string, ctx: CommandContext): Promise<CommandResult | undefined>;
81
+ /**
82
+ * [#301] 只查宿主 / 扩展注册的命令(RPC 的 `prompt` 没有内置命令分派,只认它);`name` 已按 `parseSlash`
83
+ * 规整。没有同名命令返回 undefined。
84
+ */
85
+ export declare function runHostSlash(name: string, args: string, runtime: Pick<Runtime, "hostCommands" | "mode">, session: Pick<AgentSession, "state">): Promise<Extract<CommandResult, {
86
+ kind: "handled" | "prompt";
87
+ }> | undefined>;
@@ -17,6 +17,7 @@ import { AgentSessionImpl } from "../agent/session.js";
17
17
  import { WARMING_MODES } from "../ai/cache/types.js";
18
18
  import { THINKING_LEVELS } from "../ai/thinking.js";
19
19
  import { AmaError } from "../errors.js";
20
+ import { runHostCommand } from "../host/commands.js";
20
21
  import { PERMISSION_MODE_ORDER, parsePermissionMode, permissionModeLabel, } from "../permissions/modes.js";
21
22
  import { pasteImage } from "./interactive/clipboard-paste.js";
22
23
  import { planCommand } from "./interactive/plan-command.js";
@@ -92,9 +93,23 @@ export function availableCommands(runtime, session, list = BUILTIN_COMMANDS) {
92
93
  : requires === "task"
93
94
  ? active.has("task") || (active.has("codemode") && registered.has("task"))
94
95
  : true;
95
- return list.filter((c) => has(c.requires));
96
+ const extension = (runtime.hostCommands?.list() ?? []).map((c) => ({
97
+ name: c.name,
98
+ description: c.description,
99
+ ...(c.args !== undefined ? { args: c.args } : {}),
100
+ source: "extension",
101
+ }));
102
+ return [...list.filter((c) => has(c.requires)), ...extension];
96
103
  }
97
104
  const ALIASES = { quit: "exit", q: "exit", "?": "help" };
105
+ /** 交互界面自己处理的命令(interactive/commands.ts 的 INTERACTIVE_COMMANDS;测试锁定一致)。 */
106
+ export const INTERACTIVE_COMMAND_NAMES = ["tree", "permissions"];
107
+ /** [#301] 保留的命令名:内置命令、别名与交互界面命令;`commands.register` 不得占用。 */
108
+ export function isReservedCommandName(name) {
109
+ return (BUILTIN_COMMANDS.some((c) => c.name === name) ||
110
+ Object.hasOwn(ALIASES, name) ||
111
+ INTERACTIVE_COMMAND_NAMES.includes(name));
112
+ }
98
113
  export function parseSlash(line) {
99
114
  const m = /^\/([A-Za-z?][\w-]*)(?:\s+([\s\S]*))?$/.exec(line.trim());
100
115
  if (m === null)
@@ -299,6 +314,23 @@ export async function runSlashCommand(line, ctx) {
299
314
  case "memory":
300
315
  return { kind: "handled", message: msg().interactive.commands.unavailable(name) };
301
316
  default:
302
- return undefined;
317
+ return extensionCommand(name, args, ctx);
303
318
  }
304
319
  }
320
+ /** [#301] 内置命令之后、提示模板之前:宿主适配器 / 扩展注册的命令;没有同名的返回 undefined。 */
321
+ async function extensionCommand(name, args, ctx) {
322
+ return runHostSlash(name, args, ctx.runtime, ctx.session());
323
+ }
324
+ /**
325
+ * [#301] 只查宿主 / 扩展注册的命令(RPC 的 `prompt` 没有内置命令分派,只认它);`name` 已按 `parseSlash`
326
+ * 规整。没有同名命令返回 undefined。
327
+ */
328
+ export async function runHostSlash(name, args, runtime, session) {
329
+ const command = runtime.hostCommands?.get(name);
330
+ if (command === undefined)
331
+ return undefined;
332
+ return runHostCommand(command, args, {
333
+ mode: runtime.mode,
334
+ session: { id: () => session.state.sessionId, cwd: () => session.state.cwd },
335
+ });
336
+ }
@@ -181,6 +181,27 @@ export function createStartupUi(options = {}) {
181
181
  const choice = choices.find((c) => c.value === picked?.value);
182
182
  return choice?.answer ?? { trusted: false, remember: false };
183
183
  },
184
+ async promptExtensions(files) {
185
+ const m = msg().interactive.startup.ui;
186
+ const choices = trustChoices();
187
+ const shown = files
188
+ .slice(0, 4)
189
+ .flatMap((f) => [
190
+ f.directory === true ? `${f.path} ${m.extensionDirectory}` : f.path,
191
+ ` sha256 ${f.sha256}`,
192
+ ]);
193
+ if (files.length > 4)
194
+ shown.push(m.moreResources(files.length - 4));
195
+ const picked = await askSelect(r, {
196
+ title: m.extensionsTitle,
197
+ lines: shown,
198
+ items: choices.map(({ value, label }) => ({ value, label })),
199
+ selected: "skip",
200
+ numberKeys: true,
201
+ });
202
+ const choice = choices.find((c) => c.value === picked?.value);
203
+ return choice?.answer ?? { trusted: false, remember: false };
204
+ },
184
205
  async pickSession(items) {
185
206
  if (items.length === 0)
186
207
  return undefined;
@@ -65,7 +65,7 @@ export class StatusArea {
65
65
  const source = {
66
66
  session: () => deps.session(),
67
67
  preset: () => runtime.config.tools?.preset ?? "default",
68
- hostStatus: () => runtime.host?.status(),
68
+ hostStatus: () => runtime.hostStatus?.() ?? runtime.host?.status(),
69
69
  codemode: () => {
70
70
  const mode = effectiveCodemodeMode(runtime.config);
71
71
  const active = deps
@@ -26,6 +26,9 @@
26
26
  * 在跑或通知待投递,stderr 一行提示并等它们结束、跑完通知回合再输出(最终文本 = 最后一条助手回复);
27
27
  * 受 `--max-turns` / `--max-cost` / `limits.*` 约束(到限即停止等待,退出码 8),SIGINT / SIGTERM 照常中止
28
28
  * (未结束的任务随会话关闭被停止);json 结果带 `tasks`(同 `getStats().tasks`)。
29
+ * - [#303] 提示整段形如 `/名 参数` 且命中扩展命令(`api.commands.register`):`handled` 把 `message` 写到 stdout、
30
+ * 退出 0、不调模型(json 与 stream-json 给一行 `result` 对象,`text` 为 message);`prompt` 改发其 `text`;
31
+ * 命令抛错 → stderr 一行、退出码 1。
29
32
  * - 退出码:最终助手消息 `error / aborted` 或提示被拒 → 1;有工具调用被拒 → 7;到达预算 → 8;
30
33
  * 计划待审批 → 9;SIGINT 130、SIGTERM 143(先 abort)。
31
34
  */
@@ -26,11 +26,15 @@
26
26
  * 在跑或通知待投递,stderr 一行提示并等它们结束、跑完通知回合再输出(最终文本 = 最后一条助手回复);
27
27
  * 受 `--max-turns` / `--max-cost` / `limits.*` 约束(到限即停止等待,退出码 8),SIGINT / SIGTERM 照常中止
28
28
  * (未结束的任务随会话关闭被停止);json 结果带 `tasks`(同 `getStats().tasks`)。
29
+ * - [#303] 提示整段形如 `/名 参数` 且命中扩展命令(`api.commands.register`):`handled` 把 `message` 写到 stdout、
30
+ * 退出 0、不调模型(json 与 stream-json 给一行 `result` 对象,`text` 为 message);`prompt` 改发其 `text`;
31
+ * 命令抛错 → stderr 一行、退出码 1。
29
32
  * - 退出码:最终助手消息 `error / aborted` 或提示被拒 → 1;有工具调用被拒 → 7;到达预算 → 8;
30
33
  * 计划待审批 → 9;SIGINT 130、SIGTERM 143(先 abort)。
31
34
  */
32
35
  import { currentSession } from "../../cli/compose-session.js";
33
36
  import { ExitCode } from "../../cli/exit-codes.js";
37
+ import { parseSlash, runHostSlash } from "../commands-core.js";
34
38
  import { errorText, lastAssistant, onStdoutClosed, onTerminationSignals } from "../shared.js";
35
39
  import { toJsonLine, toWireEvent } from "./json-event.js";
36
40
  import { formatUsd } from "../../agent/limits.js";
@@ -107,16 +111,35 @@ export async function runPrintMode(runtime, context) {
107
111
  const format = context.args.outputFormat ?? "text";
108
112
  const stdinMode = context.args.noStdin ? "off" : context.args.stdin ? "explicit" : "auto";
109
113
  const piped = await readPromptStdin(io, context.prompt, stdinMode);
110
- const prompt = joinPrompt(context.prompt, piped);
114
+ let prompt = joinPrompt(context.prompt, piped);
111
115
  if (prompt === "") {
112
116
  io.stderr(msg().print.print.needsPrompt);
113
117
  return ExitCode.Usage;
114
118
  }
115
119
  const session = currentSession(runtime);
116
- let images;
120
+ // [#303] `/<名> 参数` 命中扩展命令:handled 直接输出 message、不调模型;prompt 改发其文本。
121
+ // 只认命令行给的提示:有管道 stdin 时整段原样发给模型(免得文件首行恰好像命令就被执行)
122
+ let handledText;
123
+ const slash = piped === "" ? parseSlash(prompt) : undefined;
124
+ if (slash !== undefined) {
125
+ try {
126
+ const hosted = await runHostSlash(slash.name, slash.args, runtime, session);
127
+ if (hosted?.kind === "handled")
128
+ handledText = hosted.message ?? "";
129
+ else if (hosted?.kind === "prompt")
130
+ prompt = hosted.text;
131
+ }
132
+ catch (error) {
133
+ io.stderr(`ama: ${errorText(error)}\n`);
134
+ return ExitCode.RuntimeError;
135
+ }
136
+ }
137
+ let images = [];
117
138
  const resize = runtime.config.images?.resize;
118
139
  try {
119
- images = await promptImages(prompt, context.args.images, io.cwd, sessionModel(runtime.providers, session), resize === undefined ? {} : { resize });
140
+ // handled 不调模型,也就不读图片(读图失败不该让命令失败)
141
+ if (handledText === undefined)
142
+ images = await promptImages(prompt, context.args.images, io.cwd, sessionModel(runtime.providers, session), resize === undefined ? {} : { resize });
120
143
  }
121
144
  catch (error) {
122
145
  io.stderr(`ama: ${errorText(error)}\n`);
@@ -174,9 +197,11 @@ export async function runPrintMode(runtime, context) {
174
197
  });
175
198
  let failure;
176
199
  try {
177
- await session.prompt(prompt, images.length > 0 ? { images } : {});
200
+ if (handledText === undefined)
201
+ await session.prompt(prompt, images.length > 0 ? { images } : {});
178
202
  const ended = lastAssistant(session)?.stopReason;
179
- if (signalled === undefined &&
203
+ if (handledText === undefined &&
204
+ signalled === undefined &&
180
205
  !stdoutClosed &&
181
206
  limit === undefined &&
182
207
  ended !== "error" &&
@@ -191,8 +216,9 @@ export async function runPrintMode(runtime, context) {
191
216
  offEpipe();
192
217
  unsubscribe();
193
218
  }
194
- const last = lastAssistant(session);
195
- const text = session.getLastAssistantText() ?? "";
219
+ // handled 没有模型回合:会话里更早的助手消息不算本次结果
220
+ const last = handledText === undefined ? lastAssistant(session) : undefined;
221
+ const text = handledText ?? session.getLastAssistantText() ?? "";
196
222
  const stopReason = failure !== undefined ? "error" : (last?.stopReason ?? "stop");
197
223
  if (format === "text") {
198
224
  // 部分模型在正文前多发空行:只去前导空行,保留首行缩进;json / stream-json 原样。
@@ -200,7 +226,8 @@ export async function runPrintMode(runtime, context) {
200
226
  if (shown !== "" && last?.stopReason !== "error")
201
227
  io.stdout(shown.endsWith("\n") ? shown : `${shown}\n`);
202
228
  }
203
- else if (format === "json") {
229
+ else if (format === "json" || (format === "stream-json" && handledText !== undefined)) {
230
+ // stream-json 本来只有事件行;handled 没有事件,就给一行与 json 相同的 result 对象
204
231
  const stats = session.getStats();
205
232
  io.stdout(`${toJsonLine({
206
233
  type: "result",
@@ -47,6 +47,8 @@ export interface RpcContext {
47
47
  readonly approvals: RpcApprovals;
48
48
  /** 会话被换掉后调用(模式据此重新订阅)。 */
49
49
  onSessionChanged(next: AgentSession): void;
50
+ /** [#301] 命令(宿主 / 扩展注册的斜杠命令)的文字输出:作 `notification` 事件发给客户端。 */
51
+ notify?(message: string, level: "info" | "warn" | "error"): void;
50
52
  /** 运行开始后提示命令自身的失败(应答已发出)。 */
51
53
  onBackgroundError(error: unknown): void;
52
54
  /** [W5-F] `get_tasks`:子 Agent 任务注册表的只读视图(W5-G 装配;缺省回空表)。 */
@@ -24,7 +24,7 @@ import { switchSession } from "../../cli/compose-session.js";
24
24
  import { AmaError } from "../../errors.js";
25
25
  import { isPermissionMode } from "../../permissions/modes.js";
26
26
  import { PERMISSION_MODES_STRICT_FIRST } from "../../permissions/types.js";
27
- import { availableCommands } from "../commands-core.js";
27
+ import { availableCommands, parseSlash, runHostSlash } from "../commands-core.js";
28
28
  import { msg } from "../../i18n/index.js";
29
29
  import { sessionTrace } from "../../trace/query-session.js";
30
30
  /** 暂存的提前回答与记住的已结算 id 的上限(都按先进先出淘汰)。 */
@@ -167,7 +167,7 @@ function commands(runtime, session) {
167
167
  ...availableCommands(runtime, session).map((c) => ({
168
168
  name: c.name,
169
169
  description: c.description,
170
- source: "builtin",
170
+ source: c.source ?? "builtin",
171
171
  })),
172
172
  ...runtime.resources.prompts.map((p) => ({ name: p.name, source: "template" })),
173
173
  ...runtime.resources.skills.map((s) => ({
@@ -178,11 +178,26 @@ function commands(runtime, session) {
178
178
  ];
179
179
  }
180
180
  export const handlers = {
181
- prompt: (p, ctx) => startRun(ctx, () => ctx.session().prompt(p.message, {
182
- ...(p.images !== undefined ? { images: p.images } : {}),
183
- ...(p.streamingBehavior !== undefined ? { streamingBehavior: p.streamingBehavior } : {}),
184
- ...(interruptFlag(p.interrupt) ? { interrupt: true } : {}),
185
- })),
181
+ prompt: async (p, ctx) => {
182
+ // [#301] `/<名>` 命中宿主 / 扩展注册的命令:先分派;handled 直接应答,prompt 改发其文本
183
+ let message = p.message;
184
+ const parsed = parseSlash(message);
185
+ const hosted = parsed === undefined
186
+ ? undefined
187
+ : await runHostSlash(parsed.name, parsed.args, ctx.runtime, ctx.session());
188
+ if (hosted?.kind === "handled") {
189
+ if (hosted.message !== undefined)
190
+ ctx.notify?.(hosted.message, "info");
191
+ return { disposition: "handled" };
192
+ }
193
+ if (hosted?.kind === "prompt")
194
+ message = hosted.text;
195
+ return startRun(ctx, () => ctx.session().prompt(message, {
196
+ ...(p.images !== undefined ? { images: p.images } : {}),
197
+ ...(p.streamingBehavior !== undefined ? { streamingBehavior: p.streamingBehavior } : {}),
198
+ ...(interruptFlag(p.interrupt) ? { interrupt: true } : {}),
199
+ }));
200
+ },
186
201
  steer: (p, ctx) => startRun(ctx, () => interruptFlag(p.interrupt)
187
202
  ? ctx.session().prompt(p.message, {
188
203
  interrupt: true,
@@ -55,6 +55,9 @@ export async function runRpcMode(runtime, context, options = {}) {
55
55
  session = next;
56
56
  unsubscribe = subscribe(next);
57
57
  },
58
+ notify(message, level) {
59
+ void write({ type: "notification", level, message });
60
+ },
58
61
  onBackgroundError(error) {
59
62
  void write({ type: "notification", level: "error", message: errorText(error) });
60
63
  },
@@ -72,6 +72,17 @@ export function createTextStartupUi(io) {
72
72
  return { trusted: true, remember: true };
73
73
  return { trusted: key === "y" || key === "yes", remember: false };
74
74
  },
75
+ async promptExtensions(files) {
76
+ const m = msg().report.startup;
77
+ const shown = files.slice(0, 6).flatMap((f) => [` ${f.path}`, ` sha256 ${f.sha256}`]);
78
+ if (files.length > 6)
79
+ shown.push(m.more(files.length - 6));
80
+ const answer = await ask([m.extensionsQuestion, ...shown], m.trustChoices);
81
+ const key = answer?.trim().toLowerCase();
82
+ if (key === "a")
83
+ return { trusted: true, remember: true };
84
+ return { trusted: key === "y" || key === "yes", remember: false };
85
+ },
75
86
  async pickSession(items) {
76
87
  if (items.length === 0)
77
88
  return undefined;
package/dist/rpc.d.ts CHANGED
@@ -249,7 +249,8 @@ export interface RpcModelInfo {
249
249
  export interface RpcCommandInfo {
250
250
  name: string;
251
251
  description?: string;
252
- source: "builtin" | "template" | "skill";
252
+ /** `"extension"`:宿主适配器 / 本地扩展经 `commands.register` 注册(#301)。 */
253
+ source: "builtin" | "template" | "skill" | "extension";
253
254
  }
254
255
  export interface RpcSuccessResponse<D = unknown> {
255
256
  id?: string;
@@ -33,6 +33,12 @@ export declare class ToolRegistry implements ToolRegistryApi {
33
33
  private activeNames;
34
34
  register(tool: ToolDefinition, source: ToolSource): void;
35
35
  disable(name: string): void;
36
+ /** [#304] 撤回扩展注册的工具(同时从活动集移除);不存在返回 false。 */
37
+ unregister(name: string): boolean;
38
+ /** [#304] `disable(name)` 会禁用的全部名字(本名 + 伴随工具)。 */
39
+ disableTargets(name: string): readonly string[];
40
+ /** [#304] 只解除这一个名字的禁用(伴随工具各自按名解除,撤回方逐个决定)。 */
41
+ enable(name: string): void;
36
42
  isDisabled(name: string): boolean;
37
43
  get(name: string): ToolDefinition | undefined;
38
44
  sourceOf(name: string): ToolSource | undefined;
@@ -82,6 +82,19 @@ export class ToolRegistry {
82
82
  this.activeNames?.delete(target);
83
83
  }
84
84
  }
85
+ /** [#304] 撤回扩展注册的工具(同时从活动集移除);不存在返回 false。 */
86
+ unregister(name) {
87
+ this.activeNames?.delete(name);
88
+ return this.entries.delete(name);
89
+ }
90
+ /** [#304] `disable(name)` 会禁用的全部名字(本名 + 伴随工具)。 */
91
+ disableTargets(name) {
92
+ return [name, ...(TOOL_COMPANIONS[name] ?? [])];
93
+ }
94
+ /** [#304] 只解除这一个名字的禁用(伴随工具各自按名解除,撤回方逐个决定)。 */
95
+ enable(name) {
96
+ this.disabled.delete(name);
97
+ }
85
98
  isDisabled(name) {
86
99
  return this.disabled.has(name);
87
100
  }
@@ -327,6 +327,13 @@ export interface ToolRegistryApi {
327
327
  /** 同名已存在则抛 AmaError{code:"tool_exists"}。 */
328
328
  register(tool: ToolDefinition, source: ToolSource): void;
329
329
  disable(name: string): void;
330
+ /** [#304] `disable(name)` 会禁用的全部名字(本名 + 伴随工具);缺省视为只有本名。 */
331
+ disableTargets?(name: string): readonly string[];
332
+ /** [#304] 只解除这一个名字的禁用(不含伴随工具);扩展激活失败撤回时用。 */
333
+ enable(name: string): void;
334
+ isDisabled(name: string): boolean;
335
+ /** [#304] 移除已注册的工具(含活动集);不存在返回 false。 */
336
+ unregister(name: string): boolean;
330
337
  get(name: string): ToolDefinition | undefined;
331
338
  /** 已注册且未禁用的名字,按名排序。 */
332
339
  list(): readonly string[];
package/docs/README.md CHANGED
@@ -31,6 +31,7 @@
31
31
  | [codemode](guides/codemode.md) | 模型写脚本批量调用工具,子进程与权限 |
32
32
  | [操作系统级沙箱](guides/sandbox.md) | macOS `sandbox-exec` 与 Linux bubblewrap,codemode 与 bash 接入 |
33
33
  | [界面语言](guides/i18n.md) | 中英双语的选择规则与开发约定 |
34
+ | [本地扩展](guides/extensions.md) | 用户自装的多个宿主适配器:加载、共存规则、斜杠命令、哈希信任、`ama doctor` |
34
35
 
35
36
  ## reference/ 协议与格式
36
37
 
@@ -48,7 +49,6 @@
48
49
  | [总体设计](design/design.md) | 架构、工程约定、缓存保证与决定表;硬约束仍以此为准,细节现状见 `guides/` |
49
50
  | [终端界面视觉规范](design/tui-design.md) | 主题、逐屏样稿与交互细节;已按此实现,作为界面改动的规范 |
50
51
  | [检索与网络搜索](design/search-plan.md) | 只实施了本地检索增强;`web_fetch`、`web_search` 与引用呈现保留为将来的设计 |
51
- | [本地扩展](design/extensions.md) | 设计草案,尚未实现 |
52
52
 
53
53
  ## history/ 已完成的计划与审计
54
54
 
package/docs/en/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  English · [简体中文](../README.md)
4
4
 
5
- Most documents are written in Chinese; seven have English translations, kept in the same layout under `docs/en/`.
5
+ Most documents are written in Chinese; eight have English translations, kept in the same layout under `docs/en/`.
6
6
  When a translation and the Chinese version differ, the Chinese version is authoritative. Relative links and the
7
7
  `docs/…md` paths in source comments are checked by `pnpm check:docs` (`scripts/check-doc-links.mjs`).
8
8
 
@@ -26,6 +26,7 @@ When a translation and the Chinese version differ, the Chinese version is author
26
26
  | [RPC protocol](reference/rpc.md) | `ama --mode rpc`: stdio JSONL commands, responses and events |
27
27
  | [ACP](reference/acp.md) | `ama --mode acp`, the Pi ACP bridge, sign-in methods, deviations, the ACP client |
28
28
  | [Host adapter API](reference/host-api.md) | `@armadra/agent/host`: tools, approvals, injected messages, status |
29
+ | [Local extensions](guides/extensions.md) | User-installed host adapters: loading, coexistence, slash commands, hash trust |
29
30
 
30
31
  ## Chinese only
31
32
 
@@ -34,6 +35,5 @@ When a translation and the Chinese version differ, the Chinese version is author
34
35
  [codemode](../guides/codemode.md), [OS sandbox](../guides/sandbox.md), [interface language](../guides/i18n.md).
35
36
  - Reference: [session file format](../reference/session-format.md).
36
37
  - Design: [overall design](../design/design.md), [terminal UI visual spec](../design/tui-design.md),
37
- [search and web access](../design/search-plan.md) (only local search is implemented),
38
- [local extensions](../design/extensions.md) (draft, not implemented).
38
+ [search and web access](../design/search-plan.md) (only local search is implemented).
39
39
  - History, research and benchmarks: see the [Chinese index](../README.md).
@@ -0,0 +1,141 @@
1
+ # Local extensions
2
+
3
+ English · [简体中文](../../guides/extensions.md)
4
+
5
+ > Translated from the Chinese [docs/guides/extensions.md](../../guides/extensions.md) as of commit `639e66c`. When the two differ, the Chinese
6
+ > version is authoritative.
7
+
8
+ User-installed host adapters, as many as you like: they observe events in-process, register tools and slash commands, and show notifications and status, without taking the host slot (`--host` / profile `host`, e.g. the Armadra canvas). Command hooks ([hooks.md](../../guides/hooks.md), Chinese) only run external commands at fixed points; extensions add the in-process layer.
9
+
10
+ An extension has **the same module shape as a host adapter**: `HostModule` (`hostApi` + `create(api)`) and receives the same `HostApi`; see [host-api.md](../reference/host-api.md) for the types and members. This page covers what is specific to extensions: loading, coexistence rules, slash commands, trust and `ama doctor`.
11
+
12
+ ## Writing one
13
+
14
+ ```js
15
+ // ~/.config/ama/extensions/standup.mjs
16
+ export const hostApi = 1;
17
+
18
+ export function create(api) {
19
+ api.commands.register({
20
+ name: "standup",
21
+ description: "Summarize today's work",
22
+ args: "[day]",
23
+ run(args, ctx) {
24
+ return {
25
+ kind: "prompt",
26
+ text: `Summarize what we did in ${ctx.session.cwd()} ${args || "today"}.`,
27
+ };
28
+ },
29
+ });
30
+ api.events.on("agent_settled", () => api.ui.setStatus("standup", "ready"));
31
+ return { id: "standup" };
32
+ }
33
+ ```
34
+
35
+ A module is `.mjs` (ESM) or `.cjs`; exporting `default` or named `hostApi` + `create` both work. The adapter returned by `create()` must have an `id` and may have `dispose()` (called on exit). Returning `undefined` means "not enabled".
36
+
37
+ ## Location and loading
38
+
39
+ - **User-level directory**: under `<configDir>/extensions/`, single files `*.{mjs,cjs}` and **directory extensions** `<name>/index.{mjs,cjs}` (`index.mjs` wins), sorted together by entry name (file or directory name; default `~/.config/ama/extensions/`, changeable with `AMA_CONFIG_DIR`). Subdirectories without an `index.*` are ignored.
40
+ - **Profile**: `extensions: ["/abs/a.mjs", …]` (absolute paths), after the user-level directory; a path is loaded once.
41
+ - **No project level**: `.ama/extensions/` in a repository is not loaded. An extension runs with the process's permissions and can register tools, which is arbitrary code execution, so it does not ship with repositories.
42
+ - **Order**: the host adapter activates first; extensions come after it and before the session is assembled (startup step 13).
43
+
44
+ ## Coexistence rules
45
+
46
+ Each module gets its own `HostApi` instance (its own tool list and status keys) and they share one tool registry, event bus, approval broker slot, resource registry and warming handlers.
47
+
48
+ | Surface | With several modules |
49
+ | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
50
+ | `tools.register` | First wins; a later duplicate throws `tool_exists` (an extension may catch it; if it does not, `create()` fails and the whole extension is skipped) |
51
+ | `tools.disable` | Cumulative |
52
+ | `instructions.add` | Appended to the system prompt's `host` section in load order (host adapter first) |
53
+ | `events.on` | All receive, called in registration order |
54
+ | `approvals.setBroker` | Only the first setter counts (usually the host adapter); other calls are ignored with a warning. The same module may set it again |
55
+ | `ui.notify` / `ui.setStatus` | All usable; the status bar merges every module's keys, a later module overrides an earlier one on the same key, so prefix your keys |
56
+ | `cache.onWarmingDecision` | The last registered, not yet unregistered handler across modules wins |
57
+ | `commands.register` | See below; command names are global, first registration wins |
58
+ | `runners.provide` / `onDone` | One shared runner table, first wins across modules (a later same-id call throws `runner_exists`; the same module providing again replaces its own); `onDone` fires only for the module's own runners; used by `task` with or without a host adapter |
59
+ | `create()` fails / times out | A host adapter still exits 6; **an extension only produces a warning and is skipped**, startup continues |
60
+ | Load failure / version mismatch | Host adapter still exits 6 / 78; an extension is skipped with a warning |
61
+ | Exit | `dispose` in reverse load order (extensions first, host adapter last); a failure only warns |
62
+
63
+ With no extensions the system prompt and tool table are byte-identical to before. The `host` field in hook context stays the host adapter's id.
64
+
65
+ When an extension's `create()` throws, times out or returns no adapter, everything it registered is revoked: tools (tools it disabled are re-enabled), event subscriptions, commands, instructions, status keys, warming handlers, the broker if it owns it, runners and resources. After that, any registration call from the module (for example a late one after a timeout) is ignored with a warning.
66
+
67
+ ## Sub-agent runners
68
+
69
+ `api.runners.provide(runner)` uses one table shared by the host adapter and extensions; `task(agent=<id>)`, `/agents` and RPC `get_agents` all read it:
70
+
71
+ - Across modules the first provider of an id wins and a later one throws `runner_exists`; the same module providing the same id again replaces its own; after an unsubscribe or a revoke the id can be provided again.
72
+ - Extension runners also work without a host adapter, at the same priority as host-injected ones (the same id replaces a built-in external runner such as `claude`). The "with a host adapter ama starts no external CLI of its own" rule still depends only on the host adapter; extensions do not change it.
73
+ - `api.runners.onDone(handler)` fires only for the module's own runners.
74
+
75
+ ## Slash commands
76
+
77
+ `api.commands.register({ name, description, args?, run(args, ctx) })` (host-api 1.4, optional member: check `api.commands !== undefined`), available to host adapters and extensions, returns an unregister function.
78
+
79
+ - **Name**: `^[a-z][a-z0-9-]{0,63}$`, no slash. Registering a built-in command, an alias (`quit`, `q`, `?`), an interactive-UI command (`tree`, `permissions`) or an already registered name throws.
80
+ - **Dispatch**: after built-in commands, before prompt templates. A prompt template with the same name is shadowed. `/skill:<name>` is unaffected.
81
+ - **`args`**: everything after the command name, trimmed. `description` and `args` (a placeholder such as `"[day]"`) appear in `/help` and completion. No argument completion.
82
+ - **`ctx`**: deliberately small, `{ mode, session: { id(), cwd() } }`. For more (send messages, read state) use the `api` you got at registration.
83
+ - **Result**: `{ kind: "handled", message? }` (`message` is shown to the user and does not enter the conversation) or `{ kind: "prompt", text }` (send this text as the user prompt); `undefined` means `{ kind: "handled" }`; any other shape is an error, and an error thrown by `run` is shown as an error without affecting the session.
84
+ - **Modes**: interactive, line, RPC, `-p` and ACP. A prompt that is entirely `/name args` and matches an extension command is dispatched inside ama; `prompt` always sends its `text` instead, and `handled` delivers `message` per mode, never starting a model turn:
85
+ - RPC: `message` is emitted as a `notification` event and the call returns `disposition: "handled"`.
86
+ - `-p`: `message` is written to stdout and the run exits 0 (`--output-format text` prints it as is; `json` and `stream-json` print one `result` object whose `text` is `message`, with zero usage); if `run` throws, stderr gets one `ama: <error>` line and the exit code is 1. Only a prompt given on the command line is dispatched: with piped stdin the whole text goes to the model as is; `handled` does not read `--image` files.
87
+ - ACP: `message` is emitted as one `agent_message_chunk` and `session/prompt` ends with `end_turn` (zero usage); if `run` throws, `session/prompt` answers with an internal error. `available_commands_update` lists extension commands (`args` becomes `input.hint`), shadowing same-name prompt templates.
88
+ - **Listing**: `/help`, interactive completion, RPC `get_commands` (`source: "extension"`).
89
+
90
+ ## Trust
91
+
92
+ Extensions run with the process's permissions, so they must be trusted before loading. The decision is recorded by the **sha256 of the file content** (for a directory extension, the sha256 of the whole directory tree) in the `extensions` section of the user-level `trust.json`:
93
+
94
+ ```json
95
+ {
96
+ "version": 1,
97
+ "entries": [],
98
+ "extensions": [
99
+ { "path": "/abs/standup.mjs", "sha256": "…", "trusted": true, "at": "2026-11-15T12:00:00.000Z" }
100
+ ]
101
+ }
102
+ ```
103
+
104
+ Decision order:
105
+
106
+ 1. `--no-trust`: no extension loads. `--trust` and the profile's `trustProject` **do not affect** extensions (they only cover project-level resources).
107
+ 2. A record with the same path and the same hash: its decision applies (trusted loads, declined is skipped).
108
+ 3. No record, or the content changed (hash mismatch):
109
+ - interactive / line mode: at startup, **once**, all pending files are listed with path and sha256 and you are asked (this time only / trust and remember / don't trust); remembered answers go into `trust.json`, and a further content change asks again.
110
+ - other modes (`-p`, RPC, ACP): not loaded, with a warning on stderr. To enable, approve once in an interactive session.
111
+
112
+ The hash is computed before loading; a file swapped between hashing and loading is out of scope (the local user directory is already one trust domain).
113
+
114
+ A **directory extension** is hashed as a whole tree. The `trust.json` entry shape is unchanged (`path` is the directory, `sha256` the tree hash), and a change to any file in the tree asks again, so multi-file extensions belong in a directory rather than trusting only the entry:
115
+
116
+ - Every regular file under the directory takes part, sorted by its forward-slash relative path in byte order (independent of platform, traversal and creation order). Each item writes `F <path byte length> <path> <content byte length>\n` followed by the content bytes, after the fixed prefix `armadra-ext-tree-v2\n`. Path and content are length-prefixed, so different trees cannot produce the same byte stream.
117
+ - **Nothing is skipped** (`.git` and `node_modules` included): a skipped file can still be `import`ed, so skipping would open a way around trust.
118
+ - Symlinks are **followed**: hashed by their target's content (also when it lies outside the directory), and directory links are walked into; a cyclic or dangling link counts as unreadable. Sockets, fifos and the like are ignored.
119
+ - Caps: at most 2000 files, 2000 directories, 32 levels deep and 50 MiB in total. Beyond that the extension is skipped with the reason "directory extension is too large"; it is neither asked about nor loaded.
120
+ - The interactive prompt and `ama doctor` mark directories.
121
+
122
+ Single-file extensions are unchanged: only that file is hashed, and files it `import`s are not covered; use a directory extension, or bundle dependencies into one file.
123
+
124
+ ## `ama doctor`
125
+
126
+ `ama doctor` has a "Local extensions" section: each file's path, the first 12 hex digits of its sha256 and its state: **enabled** (a matching trusted record) or **skipped** with the reason (not trusted, content changed since it was trusted, declined, unreadable, directory extension too large, `--no-trust`); directory extensions are marked `[directory]` and the hash prefix is the tree hash. Doctor only reads files and trust records and **never runs extension code**, so reasons that only loading can reveal (load failure, version mismatch, `create()` failure, no adapter returned) are not shown there; they appear as warnings in startup output (stderr for `-p` and RPC, the message area in interactive mode).
127
+
128
+ ## Typical uses
129
+
130
+ | Use | How |
131
+ | --------------- | ---------------------------------------------------------------------------------------------------------------- |
132
+ | Next-step hints | After `events.on("agent_settled")`, derive 2-3 suggestions from the last reply and show them with `ui.notify` |
133
+ | Desktop alerts | On `agent_settled` and `tool_approval_requested`, write an OSC 777 notification sequence to the terminal |
134
+ | Git checkpoints | On `turn_start`, record a checkpoint with `git stash create` (no working-tree change) and roll back with `/undo` |
135
+ | Custom commands | `commands.register({ name: "standup", … })` summarizes today's sessions |
136
+ | Warming policy | `cache.onWarmingDecision` vetoes idle warming by time of day or budget |
137
+
138
+ ## Out of scope
139
+
140
+ - **No rendering layer**: extensions cannot replace or insert UI components or take over keys. They can express themselves only through message-area notifications, status-bar key/values and slash command output.
141
+ - No capability declarations (the trust prompt does not show capabilities), no command argument completion, no dependency order between extensions (only file-name order).
@@ -125,7 +125,7 @@ Session-open answers (new / load / resume) carry `configOptions`, followed by an
125
125
 
126
126
  - `mode` is the same state as `modes` / `session/set_mode`: the spec says a client that gets `configOptions` should use them instead of `modes` (Zed then ignores `modes`), so the mode is a config option too; `modes` is still sent for clients that only know `modes`. Setting `mode` is per session like `session/set_mode`, and a change sends both `current_mode_update` and `config_option_update`. There are no boolean options.
127
127
  - `session/set_config_option`: `model` switches the model, `thinking` changes the thinking level, and the answer is the new state of all options; unknown ids, unknown models and unknown levels answer invalid params (-32602). When the model or level changes during a session (including automatic switches in the plan flow), `config_option_update` is sent.
128
- - Command list: skills are listed as `skill:<name>`, prompt templates as `<name>` (the frontmatter `argument-hint` becomes `input.hint`). Both already expand in prompt text (`/skill:<name> …`, `/<name> …`). Built-in slash commands such as `/new` and `/compact` do not run under ACP and are not listed.
128
+ - Command list: skills are listed as `skill:<name>`, prompt templates as `<name>` (the frontmatter `argument-hint` becomes `input.hint`). Both already expand in prompt text (`/skill:<name> …`, `/<name> …`). Commands registered by host adapters and local extensions (#303) are also listed as `<name>` (`args` becomes `input.hint`), shadowing same-name prompt templates; a `session/prompt` whose text is entirely `/<name> args` and matches one is dispatched by ama: `handled` emits `message` as one `agent_message_chunk` and ends with `end_turn` (no model turn, zero usage), `prompt` sends its `text` instead, and a command that throws answers with an internal error. Built-in slash commands such as `/new` and `/compact` do not run under ACP and are not listed.
129
129
 
130
130
  ### Exit
131
131