@armadra/agent 0.17.3 → 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.
- package/CHANGELOG.md +50 -0
- package/CHANGELOG.zh-CN.md +50 -0
- package/README.md +4 -0
- package/README.zh-CN.md +4 -0
- package/THIRD_PARTY_NOTICES.md +6 -0
- package/assets/quickjs/LICENSE +57 -0
- package/assets/quickjs/README.md +14 -0
- package/assets/quickjs/quickjs.wasm +0 -0
- package/dist/agent/recovery-reminder.js +6 -1
- package/dist/agent/schema-coerce.d.ts +24 -0
- package/dist/agent/schema-coerce.js +157 -0
- package/dist/agent/schema.d.ts +1 -1
- package/dist/agent/schema.js +1 -1
- package/dist/agent/session-cache.js +12 -0
- package/dist/agent/tool-runner.js +57 -28
- package/dist/agent/types.d.ts +4 -0
- package/dist/ai/apis/anthropic-compat.d.ts +3 -1
- package/dist/ai/apis/anthropic-compat.js +8 -1
- package/dist/ai/apis/anthropic-messages.js +54 -2
- package/dist/ai/apis/anthropic-request.d.ts +3 -0
- package/dist/ai/apis/anthropic-request.js +7 -1
- package/dist/ai/apis/anthropic-threads.d.ts +64 -0
- package/dist/ai/apis/anthropic-threads.js +192 -0
- package/dist/ai/providers/catalog-data.js +5 -5
- package/dist/ai/providers/models-dev-data.js +22 -22
- package/dist/ai/types.d.ts +16 -0
- package/dist/bundle/ama-sandbox.cjs +96 -2
- package/dist/bundle/ama.cjs +29964 -27673
- package/dist/cli/bootstrap.js +32 -6
- package/dist/cli/compose-agents.js +2 -1
- package/dist/cli/compose-extensions-load.d.ts +20 -0
- package/dist/cli/compose-extensions-load.js +38 -0
- package/dist/cli/compose.js +1 -0
- package/dist/cli/deps.d.ts +11 -0
- package/dist/cli/runtime.d.ts +7 -0
- package/dist/cli/subcommands/config.d.ts +3 -0
- package/dist/cli/subcommands/config.js +22 -7
- package/dist/cli/subcommands/doctor.js +34 -0
- package/dist/cli/subcommands/models-discover.js +6 -2
- package/dist/codemode/capability.d.ts +14 -2
- package/dist/codemode/capability.js +19 -2
- package/dist/codemode/host-side.d.ts +14 -0
- package/dist/codemode/host-side.js +81 -10
- package/dist/codemode/inner-calls.d.ts +19 -0
- package/dist/codemode/inner-calls.js +24 -0
- package/dist/codemode/protocol.d.ts +14 -0
- package/dist/codemode/protocol.js +9 -1
- package/dist/codemode/quickjs/host.d.ts +15 -0
- package/dist/codemode/quickjs/host.js +243 -0
- package/dist/codemode/quickjs/wasm.d.ts +21 -0
- package/dist/codemode/quickjs/wasm.js +39 -0
- package/dist/codemode/quickjs/worker.d.ts +55 -0
- package/dist/codemode/quickjs/worker.js +457 -0
- package/dist/codemode/sandbox-entry.d.ts +4 -0
- package/dist/codemode/sandbox-entry.js +95 -3
- package/dist/codemode/script-images.d.ts +18 -0
- package/dist/codemode/script-images.js +38 -0
- package/dist/codemode/script-output.d.ts +19 -0
- package/dist/codemode/script-output.js +67 -0
- package/dist/codemode/search-tools.d.ts +27 -0
- package/dist/codemode/search-tools.js +83 -0
- package/dist/codemode/tool.d.ts +4 -0
- package/dist/codemode/tool.js +60 -9
- package/dist/codemode/worker-pool.d.ts +65 -0
- package/dist/codemode/worker-pool.js +131 -0
- package/dist/config/extension-tree-hash.d.ts +31 -0
- package/dist/config/extension-tree-hash.js +88 -0
- package/dist/config/extension-trust.d.ts +70 -0
- package/dist/config/extension-trust.js +112 -0
- package/dist/config/json-schema.js +3 -1
- package/dist/config/key-docs.js +7 -1
- package/dist/config/profile.d.ts +2 -0
- package/dist/config/profile.js +1 -0
- package/dist/config/schema-trust.d.ts +7 -0
- package/dist/config/schema-trust.js +46 -0
- package/dist/config/schema.d.ts +4 -5
- package/dist/config/schema.js +7 -27
- package/dist/config/settings-registry.js +2 -0
- package/dist/config/trust.d.ts +2 -0
- package/dist/config/trust.js +5 -1
- package/dist/config/types.d.ts +23 -0
- package/dist/config/types.js +1 -0
- package/dist/drivers/host-runners.d.ts +15 -4
- package/dist/drivers/host-runners.js +31 -17
- package/dist/errors.d.ts +1 -1
- package/dist/host/api-impl.d.ts +47 -4
- package/dist/host/api-impl.js +181 -20
- package/dist/host/commands.d.ts +23 -0
- package/dist/host/commands.js +76 -0
- package/dist/host/extensions.d.ts +43 -0
- package/dist/host/extensions.js +117 -0
- package/dist/host/resources.d.ts +2 -0
- package/dist/host/resources.js +5 -0
- package/dist/host/types.d.ts +41 -2
- package/dist/host/types.js +4 -2
- package/dist/i18n/catalog.d.ts +39 -0
- package/dist/i18n/messages/cli.d.ts +24 -0
- package/dist/i18n/messages/cli.js +24 -0
- package/dist/i18n/messages/config-keys.d.ts +4 -0
- package/dist/i18n/messages/config-keys.js +6 -2
- package/dist/i18n/messages/config.d.ts +4 -0
- package/dist/i18n/messages/drivers.d.ts +22 -0
- package/dist/i18n/messages/drivers.js +22 -0
- package/dist/i18n/messages/errors.d.ts +1 -1
- package/dist/i18n/messages/interactive-startup.d.ts +4 -0
- package/dist/i18n/messages/interactive-startup.js +4 -0
- package/dist/i18n/messages/interactive-view.d.ts +2 -0
- package/dist/i18n/messages/interactive-view.js +2 -0
- package/dist/i18n/messages/interactive.d.ts +6 -0
- package/dist/i18n/messages/report.d.ts +14 -0
- package/dist/i18n/messages/report.js +14 -0
- package/dist/i18n/messages/subcommands-config.d.ts +8 -0
- package/dist/i18n/messages/subcommands-config.js +8 -0
- package/dist/i18n/messages/subcommands.d.ts +8 -0
- package/dist/modes/acp/acp-config.d.ts +4 -2
- package/dist/modes/acp/acp-config.js +17 -3
- package/dist/modes/acp/acp-events.d.ts +2 -0
- package/dist/modes/acp/acp-events.js +4 -0
- package/dist/modes/acp/acp-server.js +6 -2
- package/dist/modes/acp/acp-sessions.d.ts +8 -1
- package/dist/modes/acp/acp-sessions.js +18 -0
- package/dist/modes/commands-core.d.ts +14 -1
- package/dist/modes/commands-core.js +34 -2
- package/dist/modes/interactive/startup-ui.js +21 -0
- package/dist/modes/interactive/status-area.js +1 -1
- package/dist/modes/interactive/tool-view.d.ts +8 -2
- package/dist/modes/interactive/tool-view.js +12 -5
- package/dist/modes/print/print-mode.d.ts +3 -0
- package/dist/modes/print/print-mode.js +35 -8
- package/dist/modes/rpc/commands.d.ts +2 -0
- package/dist/modes/rpc/commands.js +22 -7
- package/dist/modes/rpc/rpc-mode.js +3 -0
- package/dist/modes/startup-ui-text.js +11 -0
- package/dist/rpc.d.ts +2 -1
- package/dist/session/unclean-end.d.ts +8 -0
- package/dist/session/unclean-end.js +39 -7
- package/dist/tools/registry.d.ts +6 -0
- package/dist/tools/registry.js +13 -0
- package/dist/tools/types.d.ts +7 -0
- package/docs/README.md +1 -1
- package/docs/en/README.md +3 -3
- package/docs/en/guides/extensions.md +141 -0
- package/docs/en/guides/providers.md +27 -7
- package/docs/en/guides/tui.md +1 -1
- package/docs/en/reference/acp.md +1 -1
- package/docs/en/reference/host-api.md +55 -27
- package/docs/en/reference/rpc.md +12 -8
- package/docs/guides/codemode.md +52 -12
- package/docs/guides/extensions.md +136 -0
- package/docs/guides/providers.md +21 -1
- package/docs/guides/sandbox.md +2 -0
- package/docs/guides/tui.md +1 -1
- package/docs/reference/acp.md +1 -1
- package/docs/reference/host-api.md +55 -27
- package/docs/reference/rpc.md +12 -8
- package/docs/reference/session-format.md +10 -9
- package/package.json +5 -2
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
200
|
+
if (handledText === undefined)
|
|
201
|
+
await session.prompt(prompt, images.length > 0 ? { images } : {});
|
|
178
202
|
const ended = lastAssistant(session)?.stopReason;
|
|
179
|
-
if (
|
|
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
|
-
|
|
195
|
-
const
|
|
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) =>
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
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
|
-
|
|
252
|
+
/** `"extension"`:宿主适配器 / 本地扩展经 `commands.register` 注册(#301)。 */
|
|
253
|
+
source: "builtin" | "template" | "skill" | "extension";
|
|
253
254
|
}
|
|
254
255
|
export interface RpcSuccessResponse<D = unknown> {
|
|
255
256
|
id?: string;
|
|
@@ -25,6 +25,8 @@ export declare const UNCLEAN_ABORTED_TYPE = "ama.aborted";
|
|
|
25
25
|
export declare const UNCLEAN_REMINDER_TYPE = "ama.reminder";
|
|
26
26
|
/** 与 `trace/types.ts` 的 `TRACE_CUSTOM_TYPE` 相同。 */
|
|
27
27
|
export declare const UNCLEAN_TRACE_TYPE = "ama.trace";
|
|
28
|
+
/** 与 `codemode/inner-calls.ts` 的 `INNER_CALL_CUSTOM_TYPE` 相同。 */
|
|
29
|
+
export declare const UNCLEAN_CODEMODE_CALL_TYPE = "ama.codemode-call";
|
|
28
30
|
/** 工具清单的上限:条数与单项长度。 */
|
|
29
31
|
export declare const UNCLEAN_TOOLS_MAX = 12;
|
|
30
32
|
export declare const UNCLEAN_TARGET_MAX = 80;
|
|
@@ -35,6 +37,12 @@ export interface UncleanEnd {
|
|
|
35
37
|
tools: string[];
|
|
36
38
|
/** 封顶后没列出的条数。 */
|
|
37
39
|
more: number;
|
|
40
|
+
/**
|
|
41
|
+
* 外层 codemode 调用没有结果(脚本被杀)时,它已经完成的内层调用(`name target: ok | failed`,按发生顺序,
|
|
42
|
+
* 已封顶);其余情况为空。
|
|
43
|
+
*/
|
|
44
|
+
innerCalls?: string[];
|
|
45
|
+
innerMore?: number;
|
|
38
46
|
/** T 里已有恢复提醒(第二次 resume 不再注入)。 */
|
|
39
47
|
reminded: boolean;
|
|
40
48
|
}
|
|
@@ -24,6 +24,8 @@ export const UNCLEAN_ABORTED_TYPE = "ama.aborted";
|
|
|
24
24
|
export const UNCLEAN_REMINDER_TYPE = "ama.reminder";
|
|
25
25
|
/** 与 `trace/types.ts` 的 `TRACE_CUSTOM_TYPE` 相同。 */
|
|
26
26
|
export const UNCLEAN_TRACE_TYPE = "ama.trace";
|
|
27
|
+
/** 与 `codemode/inner-calls.ts` 的 `INNER_CALL_CUSTOM_TYPE` 相同。 */
|
|
28
|
+
export const UNCLEAN_CODEMODE_CALL_TYPE = "ama.codemode-call";
|
|
27
29
|
/** 工具清单的上限:条数与单项长度。 */
|
|
28
30
|
export const UNCLEAN_TOOLS_MAX = 12;
|
|
29
31
|
export const UNCLEAN_TARGET_MAX = 80;
|
|
@@ -104,18 +106,40 @@ export function toolTarget(name, args) {
|
|
|
104
106
|
}
|
|
105
107
|
return undefined;
|
|
106
108
|
}
|
|
107
|
-
/**
|
|
108
|
-
function
|
|
109
|
-
let start = 0;
|
|
109
|
+
/** 上一轮的起点:最后一条非 steer 的 user 消息之后。 */
|
|
110
|
+
function turnStart(branch) {
|
|
110
111
|
for (let i = branch.length - 1; i >= 0; i--) {
|
|
111
112
|
const entry = branch[i];
|
|
112
113
|
if (entry?.type === "message" &&
|
|
113
114
|
entry.message.role === "user" &&
|
|
114
115
|
entry.message.origin !== "steer") {
|
|
115
|
-
|
|
116
|
-
break;
|
|
116
|
+
return i + 1;
|
|
117
117
|
}
|
|
118
118
|
}
|
|
119
|
+
return 0;
|
|
120
|
+
}
|
|
121
|
+
/** 上一轮里、外层 codemode 调用没有结果的那些脚本已经完成的内层调用。 */
|
|
122
|
+
function lastTurnInnerCalls(branch, results) {
|
|
123
|
+
const lines = [];
|
|
124
|
+
for (const entry of branch.slice(turnStart(branch))) {
|
|
125
|
+
if (entry.type !== "custom" || entry.customType !== UNCLEAN_CODEMODE_CALL_TYPE)
|
|
126
|
+
continue;
|
|
127
|
+
const data = entry.data;
|
|
128
|
+
if (typeof data !== "object" || data === null)
|
|
129
|
+
continue;
|
|
130
|
+
if (typeof data.parent !== "string" || results.has(data.parent))
|
|
131
|
+
continue;
|
|
132
|
+
if (typeof data.name !== "string")
|
|
133
|
+
continue;
|
|
134
|
+
const head = typeof data.target === "string" ? `${data.name} ${clip(data.target)}` : data.name;
|
|
135
|
+
lines.push(`${clip(head)}: ${data.ok === false ? "failed" : "ok"}`);
|
|
136
|
+
}
|
|
137
|
+
const shown = lines.slice(0, UNCLEAN_TOOLS_MAX);
|
|
138
|
+
return { innerCalls: shown, innerMore: lines.length - shown.length };
|
|
139
|
+
}
|
|
140
|
+
/** 上一轮 = 最后一条非 steer 的 user 消息之后;列出其中全部 assistant 的工具调用。 */
|
|
141
|
+
function lastTurnTools(branch, results) {
|
|
142
|
+
const start = turnStart(branch);
|
|
119
143
|
const seen = new Set();
|
|
120
144
|
const tools = [];
|
|
121
145
|
for (const entry of branch.slice(start)) {
|
|
@@ -148,6 +172,14 @@ export function detectUncleanEnd(branch) {
|
|
|
148
172
|
const reason = reasonOf(branch, at, entry.message, after);
|
|
149
173
|
if (reason === undefined)
|
|
150
174
|
return undefined;
|
|
151
|
-
const
|
|
152
|
-
|
|
175
|
+
const results = resultIds(branch);
|
|
176
|
+
const { tools, more } = lastTurnTools(branch, results);
|
|
177
|
+
const { innerCalls, innerMore } = lastTurnInnerCalls(branch, results);
|
|
178
|
+
return {
|
|
179
|
+
reason,
|
|
180
|
+
tools,
|
|
181
|
+
more,
|
|
182
|
+
...(innerCalls.length > 0 ? { innerCalls, innerMore } : {}),
|
|
183
|
+
reminded: after.some(isRecoveryReminder),
|
|
184
|
+
};
|
|
153
185
|
}
|
package/dist/tools/registry.d.ts
CHANGED
|
@@ -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;
|
package/dist/tools/registry.js
CHANGED
|
@@ -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
|
}
|
package/dist/tools/types.d.ts
CHANGED
|
@@ -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;
|
|
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).
|
|
@@ -423,13 +423,14 @@ compat only records **verified** differences; please attach a docs link or a rea
|
|
|
423
423
|
|
|
424
424
|
Defaults are inferred from the request host (`src/ai/apis/anthropic-compat.ts`); `providers.<id>.compat` and channel- or model-level `compat` override field by field:
|
|
425
425
|
|
|
426
|
-
| Switch | Effect
|
|
427
|
-
| ----------------------------- |
|
|
428
|
-
| `sendInterleavedThinkingBeta` | Send the `interleaved-thinking` beta header for budgeted thinking + tools
|
|
429
|
-
| `sendCacheControl` | Place `cache_control` breakpoints
|
|
430
|
-
| `adaptiveThinking` | `{type:"adaptive"}` + `output_config.effort`
|
|
431
|
-
| `supportsCacheControlOnTools` | Breakpoint on the last tool definition
|
|
432
|
-
| `maxCacheBreakpoints` | Maximum number of breakpoints
|
|
426
|
+
| Switch | Effect | Default |
|
|
427
|
+
| ----------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
428
|
+
| `sendInterleavedThinkingBeta` | Send the `interleaved-thinking` beta header for budgeted thinking + tools | On for `api.anthropic.com`; off for DeepSeek, Zhipu, Kimi, Qwen, MiniMax, StepFun, Tencent, Volcengine; other hosts only for `claude*` models |
|
|
429
|
+
| `sendCacheControl` | Place `cache_control` breakpoints | On; off for DeepSeek (documented as ignored) |
|
|
430
|
+
| `adaptiveThinking` | `{type:"adaptive"}` + `output_config.effort` | Off; enabled per entry in the catalog for new official models |
|
|
431
|
+
| `supportsCacheControlOnTools` | Breakpoint on the last tool definition | On |
|
|
432
|
+
| `maxCacheBreakpoints` | Maximum number of breakpoints | 4 |
|
|
433
|
+
| `messageThreads` | Continue requests as message threads and send only new messages (see below) | On for `api.anthropic.com`; off for every other host (including Anthropic-compatible third parties and relays) |
|
|
433
434
|
|
|
434
435
|
OpenRouter's Messages endpoint only gives cache usage in `message_delta`; parsing already merges non-empty fields, so no switch is needed.
|
|
435
436
|
|
|
@@ -524,6 +525,25 @@ Every real request records an in-memory entry: the prefix fingerprint (the first
|
|
|
524
525
|
|
|
525
526
|
`task` sub-sessions have their own record chain and stats, summarized in the "Sub-tasks" line of `/session`; forked sessions keep using the root session id as `prompt_cache_key` (just a routing hint).
|
|
526
527
|
|
|
528
|
+
### Message threads
|
|
529
|
+
|
|
530
|
+
Default behavior on the official endpoint (beta header `message-threads-2026-08-12`): when a request has a stable session id and `cacheRetention` is not `none`, the server keeps the conversation as a thread and the request carries only the messages after the previous reply instead of resending the whole history every turn. `system` and `tools` are omitted from a continuation; the thread keeps its own. Token usage and cache reads/writes are still reported for the whole conversation, and fingerprints and miss detection look only at the transcript, so a continuation is never reported as a miss.
|
|
531
|
+
|
|
532
|
+
| Item | Rule |
|
|
533
|
+
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
534
|
+
| First request | Full request with `thread: {type:"create"}` and the beta header; the reply's message id becomes the session's continuation point |
|
|
535
|
+
| Continuation | `system` / `tools` removed, `messages` only the new part, `thread: {type:"continue", previous_message_id}`; each reply can be continued once |
|
|
536
|
+
| Fallback to full | The earlier context no longer matches the request item by item (compaction, `/tree` rewind or branch switch, a change to model / system / tools / thinking level / `tool_choice` / betas); the message count does not exceed the continuation point; the previous turn failed or was aborted; the reply came from another endpoint. A new thread is started |
|
|
537
|
+
| Server rejection | `thread_not_found`, `thread_already_continued`, `thread_continue_in_flight`, `thread_fingerprint_mismatch` → resend the full request as a new thread once; `thread_unsupported_request`, or a 400 about the `thread` field without an error code → resend without `thread` **and without the threads beta header** (the endpoint may reject the header value itself), and stop using threads for that session and for that endpoint + model for the rest of the process, so no other session pays an extra 400 on its first request. The first four keep the header on resend. Other errors are not about the thread and surface as usual |
|
|
538
|
+
| Not participating | A request with `StreamOptions.disableContinuation: true` neither continues nor replaces the continuation point: warming replays and compaction / branch summary requests set it (they repeat the previous request's prefix, and continuing would use up the only continuation of that reply); so does a request whose body `onPayload` replaced with a non-object. The threads beta header is still sent so headers match real turns and the cache key stays the same (once an endpoint is switched off, no request carries it) |
|
|
539
|
+
| Switch | `compat.messageThreads: false` turns it off; Anthropic-compatible third parties and relays default to off (a gateway that drops unknown fields would turn a continuation into a request missing its history); set `true` once the gateway is known to forward the `thread` field |
|
|
540
|
+
|
|
541
|
+
Forked sessions share the root's prompt cache key but have their own thread key (`StreamOptions.threadKey`, default `sessionId`), so a fork and its root each continue their own thread.
|
|
542
|
+
|
|
543
|
+
Continuation points live in process memory only (up to 10 000 sessions, released when the session ends). After a restart, or once the thread has expired on the server (a few idle minutes), the first request is rejected and resent in full automatically, costing one extra round trip.
|
|
544
|
+
|
|
545
|
+
Manual live check (real key, not run in CI): `pnpm build:lib && ANTHROPIC_API_KEY=... node scripts/verify-anthropic-threads.mjs [model id]`, default `claude-haiku-5-5`. It uses temporary `AMA_DATA_DIR` / `AMA_CONFIG_DIR`, reads the key from the environment only and never prints it. It runs 3 turns and prints, per turn, the thread action (create / continue), the request body message count and input / cacheRead / cacheWrite / output; it exits 1 if turn 2 did not continue.
|
|
546
|
+
|
|
527
547
|
### Warming
|
|
528
548
|
|
|
529
549
|
While a tool runs for a long time (long tests, `task` sub-tasks, codemode scripts), the prefix may expire before the next request. Warming replays the previous real request before the TTL expires (same model, same context, `maxTokens` at the smallest value the protocol accepts: 16 for `openai-responses`, 1 elsewhere), paying only one read to keep the cache alive.
|