@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
package/docs/en/guides/tui.md
CHANGED
|
@@ -50,7 +50,7 @@ Accept edits | shift+tab to cycle claude-opus-5-5 medium | Ctx 3.0% 8.2k/272k
|
|
|
50
50
|
- **Notices**: `✗` errors, `↻ retry n/m`, `!` warnings (cache misses, remaining context), `⛔` hook blocks, host notifications, explanations of denied or timed-out approvals; compaction / branch summaries are left-bar cards (`▎ context compacted 128k → 24k tokens`).
|
|
51
51
|
- **Running**: `⠋ verb · elapsed · …`, with the verb taken from the deepest current state: waiting for confirmation (approval open), `running bash` / `running 3 tools`, `retry 2/3 · in 2s`, compacting context, replying `· ↓≈1.2k` (estimated tokens of this output), thinking. While a foreground sub-agent task blocks the turn, `Ctrl+B to background` is appended; while the agent bar has tasks, `↓ Agent bar` is appended (`↓ handle approval` instead when an approval is docked): `⠏ running task · 4s · Esc to interrupt · Ctrl+B to background · ↓ Agent bar`; items are dropped whole from the end when the line does not fit. With text in the input box, `Enter queue · Ctrl+X interrupt & send` comes first (`Enter interrupt & send · Ctrl+X queue` with `ui.enterWhileRunning: "interrupt"`); with queued steers the queue's last line reads `Alt+↑ take back · Ctrl+X send now · Esc refill and interrupt`.
|
|
52
52
|
- **Status bar**: the mode is always on the far left; `full` splits into two sides — the left column holds state and switches (permission mode, the `shift+tab` hint, codemode, sandbox, preset, fallback), the right column holds metrics and the model (tps, usage, model, Ctx, git, cost, duration, quota), right-aligned, and a line with nothing on the left sits flush right; the status bar is the last line except for the subscription quota line in the `full` layout (`compact` always keeps it last). In `compact` the separator is always `·` (embedding hosts parse it), in `full` it is `|`. The layout follows `ui.statusLine`: `full` (two lines) by default in a standalone terminal, `compact` (one line, same layout as before) by default in an embedding host with a profile; `Ctrl+G` or `/statusline [full|compact]` switches at runtime for this session only. With `full` the input box is the 4th line from the bottom (`compact` keeps it 3rd from the bottom).
|
|
53
|
-
- **`full` top line (rate line)**: the left side holds switches: `codemode on|only` (with `net!` when the network is not isolated) · `sandbox` · `preset <name>` (when not default) · `→ <fallback model>` (during a fallback, yellow) · queue count · host status; it is empty when there are none. The right side is `tps: <rate> tok/s • <output tokens> tok / <elapsed> (avg <session average> · ttft <time to first token>) · Σ↑<input> ↓<output> R<cache read> W<cache write> · cache · re-billing · [-]`. While streaming the rate is the instantaneous value over the last 2 s (`tps:` in the accent color); afterwards it is the request's average; whole replies generated in under 0.25 s get no rate and show `—`; elapsed time starts at the first token; `Σ` marks the **session total** of billed tokens (not context usage), `↑` input includes cache reads and writes, which are also listed as `R` / `W` (hidden when 0; `Σ` is `sum ` in ASCII); in ASCII `•` becomes `*` and `→` becomes `->`; `[-]` at the end hints that it folds. Only chat requests count (compaction summaries, warming and the classifier do not). When narrow, the right-side metrics drop first (output / elapsed, tokens, cache, re-billing, avg, ttft), then the left-side switches (host status, queue count, preset, fallback, sandbox, codemode); `tps` and `[-]` never drop.
|
|
53
|
+
- **`full` top line (rate line)**: the left side holds switches: `codemode on|only` (with `net!` when the network is not isolated, only with `codemode.engine: "node"`) · `sandbox` · `preset <name>` (when not default) · `→ <fallback model>` (during a fallback, yellow) · queue count · host status; it is empty when there are none. The right side is `tps: <rate> tok/s • <output tokens> tok / <elapsed> (avg <session average> · ttft <time to first token>) · Σ↑<input> ↓<output> R<cache read> W<cache write> · cache · re-billing · [-]`. While streaming the rate is the instantaneous value over the last 2 s (`tps:` in the accent color); afterwards it is the request's average; whole replies generated in under 0.25 s get no rate and show `—`; elapsed time starts at the first token; `Σ` marks the **session total** of billed tokens (not context usage), `↑` input includes cache reads and writes, which are also listed as `R` / `W` (hidden when 0; `Σ` is `sum ` in ASCII); in ASCII `•` becomes `*` and `→` becomes `->`; `[-]` at the end hints that it folds. Only chat requests count (compaction summaries, warming and the classifier do not). When narrow, the right-side metrics drop first (output / elapsed, tokens, cache, re-billing, avg, ttft), then the left-side switches (host status, queue count, preset, fallback, sandbox, codemode); `tps` and `[-]` never drop.
|
|
54
54
|
- **`full` bottom line**: on the left `permission mode | shift+tab to switch`, on the right `model thinking-level | Ctx 3.0% 8.2k/272k auto | <dir name> ⎇ <branch> <short commit> ↑N ↓N (+a,-d) | $cost | session duration` (Ctx with one decimal, no meter even when wide). The Ctx part is the current context: the percentage, used / window, and `auto` while auto-compaction is on (hidden when it is off, tripped after repeated failures, or the window is unknown); the numbers get a leading `≈` when they do not come from usage reported by the model (the baseline estimated from the system prompt and tool declarations before the first request, or the full estimate after a compaction until the next request); without a window it reads `Ctx ? 8.2k`. When narrow, these drop in order: `auto`, the switch hint, thinking level, `/window`, line changes, directory name, branch and commit, used tokens, duration, cost, the context percentage, model.
|
|
55
55
|
- **Subscription quota line** (third `full` line, below the status bar): when the current model uses a ChatGPT subscription (the `chatgpt` provider) it shows `Session: <used %> | Reset: <time to reset> | Weekly: <used %> | Weekly Reset: <time to reset>` (Chinese labels in the Chinese interface), from the latest `quota_update` (the codex flavor's `x-codex-primary/secondary-*` response headers and `codex.rate_limits` events; siwc only has it after a 429). Reset times are relative (`2h 18m`, `6d 5h`) and refresh once a minute. Before the first request the codex flavor shows "Quota: shown after the first request" (the first request brings the quota back, so holding the line avoids the row count jumping); siwc without data takes no line (it only gets a quota when over the limit, so a placeholder would stay forever); non-subscription models show nothing. Below 80 columns it compresses to `5h 10% ↻2h18m · wk 31% ↻6d5h`, dropping the reset times first when narrower. The quota line is right-aligned. Labels follow the window length rather than the primary / secondary slot: 300 minutes is `Session`, 10080 minutes is `Weekly`, any other length shows the length itself (`1d: `); without a length, primary counts as Session and secondary as Weekly (or the other one if that name is taken); windows are ordered shortest first. A window with 0 % used, no length and no reset time is the server saying "no such window" and is not shown (some plans get a single weekly window from codex, sent as primary). `Ctrl+G` / `/statusline compact` folds the quota line together with the rate line (`compact` stays a single line; hosts anchor on "last line = status bar").
|
|
56
56
|
- **Colors** (`full`): labels, units, separators and parentheses dim gray; the rate number purple, output / elapsed / avg blue, ttft purple; model and thinking level blue; Ctx by threshold green / yellow / red (yellow once past the tier-one pruning threshold — 0.7 × (window − reserve), a little under 70%; red at ≥ 90%; ≥ 70% yellow when there is no threshold), quota percentages yellow at ≥ 70% and red at ≥ 90%; directory and branch green, short commit dim, `↑N` ahead orange, `↓N` behind red, `(+a,-d)` green / red; cost yellow; duration and reset times purple. All come from theme semantic colors with dark / light and 16-color mappings; `NO_COLOR` and ASCII drop the colors and keep the structure. `compact` colors are unchanged.
|
package/docs/en/reference/acp.md
CHANGED
|
@@ -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
|
|
|
@@ -5,7 +5,7 @@ English · [简体中文](../../reference/host-api.md)
|
|
|
5
5
|
> Translated from the Chinese [docs/reference/host-api.md](../../reference/host-api.md) as of commit `979608b`. When the two differ, the Chinese
|
|
6
6
|
> version is authoritative.
|
|
7
7
|
|
|
8
|
-
A host adapter is a local JS module that ama loads at startup and hands a `HostApi`. With it the adapter can register tools, append to the system prompt, observe events, answer approvals, inject user messages and show notifications and status in the interface. The Armadra canvas plugs in as a host adapter (the canvas tools `canvas_*` / `context_*` are all registered by the adapter). The types are defined in `src/host/types.ts` and exported from `@armadra/agent/host`; `HOST_API_VERSION = 1`, `HOST_API_MINOR =
|
|
8
|
+
A host adapter is a local JS module that ama loads at startup and hands a `HostApi`. With it the adapter can register tools, append to the system prompt, observe events, answer approvals, inject user messages and show notifications and status in the interface. The Armadra canvas plugs in as a host adapter (the canvas tools `canvas_*` / `context_*` are all registered by the adapter). The types are defined in `src/host/types.ts` and exported from `@armadra/agent/host`; `HOST_API_VERSION = 1`, `HOST_API_MINOR = 4` (host-api 1.4, see "Versioning"). The design rationale is in [design.md](../../design/design.md) §6.2, §6.3 and §11.1 step 13 (Chinese).
|
|
9
9
|
|
|
10
10
|
## Module shape
|
|
11
11
|
|
|
@@ -61,34 +61,37 @@ export function create(api) {
|
|
|
61
61
|
| ----- | ----------------- | -------------------------------------------------------------------------------------------------- |
|
|
62
62
|
| 0 | — | Every existing member (optional facets such as `cache?` and `runners?.provide` still need a check) |
|
|
63
63
|
| 1 | 0.11.0 | `minor`, `runners?.onDone` (see "Runner done event") |
|
|
64
|
-
| 2 |
|
|
65
|
-
| 3 |
|
|
64
|
+
| 2 | 0.16.0 | `resources?.register` / `resources?.list` (see "Host resources") |
|
|
65
|
+
| 3 | 0.16.0 | `session_start.uncleanEnd` (with `reason: "resume"`, #268) |
|
|
66
|
+
| 4 | Unreleased | `commands?.register` / `commands?.list` (see "Slash commands", #301) |
|
|
66
67
|
|
|
67
68
|
## HostApi
|
|
68
69
|
|
|
69
|
-
| Member | Description
|
|
70
|
-
| ----------------------------------------------- |
|
|
71
|
-
| `version` | `HOST_API_VERSION`
|
|
72
|
-
| `agent` | `{ name: "ama", version }`
|
|
73
|
-
| `env` | A frozen copy of the environment variables at startup
|
|
74
|
-
| `mode` | `interactive` / `line` / `print` / `rpc`
|
|
75
|
-
| `session.id()` / `file()` / `cwd()` / `model()` | The current session (follows the new session after a switch); `file()` is `undefined` until the first request is written to disk
|
|
76
|
-
| `tools.register(tool)` | Register a tool (shape below); the name must match `^[a-z][a-z0-9_]{1,63}$`, and an existing name throws `tool_exists`. A prefix is recommended (`canvas_*`)
|
|
77
|
-
| `tools.disable(name)` | Hide a built-in tool (Armadra disables `task`, for example); the tools section of the system prompt stops listing it
|
|
78
|
-
| `tools.list()` | All current tool names
|
|
79
|
-
| `instructions.add(source)` | Append to the final `host` section of the system prompt; `{ kind: "file", path }` or `{ kind: "text", text, name? }`
|
|
80
|
-
| `events.on(name, handler)` | Observe events (table below); returns an unsubscribe function
|
|
81
|
-
| `approvals.setBroker(broker)` | Set the approval answerer (see "Approvals")
|
|
82
|
-
| `messages.sendUser(text, origin?)` | Inject a user message: when idle it starts a run (`"started"`), while running it is queued as a steer (`"queued"`); `origin` defaults to `"host"`, is persisted on the message and shown as `↳ host`
|
|
83
|
-
| `ui.notify(message, level?)` | Goes to the message area in interactive / line mode; becomes a `notification` event in rpc mode (with a copy on stderr); written to stderr in print mode
|
|
84
|
-
| `ui.setStatus(key, text?)` | A host item in the status bar; an empty or missing `text` removes the key
|
|
85
|
-
| `log(level, message, detail?)` | Logging; `warn` / `error` go to stderr
|
|
86
|
-
| `cache?.onWarmingDecision(handler)` | Veto hook for cache warming (see "Cache warming"); an optional facet missing in older runtimes, so check `api.cache !== undefined` before use
|
|
87
|
-
| `runners?.provide(runner)` | Injects a sub-agent runner: `id` is the name in `task(agent=<id>)` and `description` goes into the task tool description; with a host, ama starts no external CLI of its own and only uses runners injected here; returns an unsubscribe function |
|
|
88
|
-
| `runners?.onDone(handler)` | Called whenever a round of
|
|
89
|
-
| `resources?.register(resource)` | Registers a read-only resource namespace `scheme://…` that the built-in `read` reads (see "Host resources"); only callable inside `create()`. Since host-api 1.2, so check `api.resources !== undefined` before use
|
|
90
|
-
| `resources?.list()` | The registered schemes, sorted by name
|
|
91
|
-
| `
|
|
70
|
+
| Member | Description |
|
|
71
|
+
| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
72
|
+
| `version` | `HOST_API_VERSION` |
|
|
73
|
+
| `agent` | `{ name: "ama", version }` |
|
|
74
|
+
| `env` | A frozen copy of the environment variables at startup |
|
|
75
|
+
| `mode` | `interactive` / `line` / `print` / `rpc` |
|
|
76
|
+
| `session.id()` / `file()` / `cwd()` / `model()` | The current session (follows the new session after a switch); `file()` is `undefined` until the first request is written to disk |
|
|
77
|
+
| `tools.register(tool)` | Register a tool (shape below); the name must match `^[a-z][a-z0-9_]{1,63}$`, and an existing name throws `tool_exists`. A prefix is recommended (`canvas_*`) |
|
|
78
|
+
| `tools.disable(name)` | Hide a built-in tool (Armadra disables `task`, for example); the tools section of the system prompt stops listing it |
|
|
79
|
+
| `tools.list()` | All current tool names |
|
|
80
|
+
| `instructions.add(source)` | Append to the final `host` section of the system prompt; `{ kind: "file", path }` or `{ kind: "text", text, name? }` |
|
|
81
|
+
| `events.on(name, handler)` | Observe events (table below); returns an unsubscribe function |
|
|
82
|
+
| `approvals.setBroker(broker)` | Set the approval answerer (see "Approvals") |
|
|
83
|
+
| `messages.sendUser(text, origin?)` | Inject a user message: when idle it starts a run (`"started"`), while running it is queued as a steer (`"queued"`); `origin` defaults to `"host"`, is persisted on the message and shown as `↳ host` |
|
|
84
|
+
| `ui.notify(message, level?)` | Goes to the message area in interactive / line mode; becomes a `notification` event in rpc mode (with a copy on stderr); written to stderr in print mode |
|
|
85
|
+
| `ui.setStatus(key, text?)` | A host item in the status bar; an empty or missing `text` removes the key |
|
|
86
|
+
| `log(level, message, detail?)` | Logging; `warn` / `error` go to stderr |
|
|
87
|
+
| `cache?.onWarmingDecision(handler)` | Veto hook for cache warming (see "Cache warming"); an optional facet missing in older runtimes, so check `api.cache !== undefined` before use |
|
|
88
|
+
| `runners?.provide(runner)` | Injects a sub-agent runner: `id` is the name in `task(agent=<id>)` and `description` goes into the task tool description; with a host adapter, ama starts no external CLI of its own and only uses runners injected here; the host adapter and local extensions share one table, across modules the first provider of an id wins and a later one throws `runner_exists`, while a module providing the same id again replaces its own (#306); returns an unsubscribe function |
|
|
89
|
+
| `runners?.onDone(handler)` | Called whenever a round of one of this module's own runners ends (see "Runner done event"); returns an unsubscribe function. Since host-api 1.1, so check `typeof api.runners?.onDone === "function"` before use |
|
|
90
|
+
| `resources?.register(resource)` | Registers a read-only resource namespace `scheme://…` that the built-in `read` reads (see "Host resources"); only callable inside `create()`. Since host-api 1.2, so check `api.resources !== undefined` before use |
|
|
91
|
+
| `resources?.list()` | The registered schemes, sorted by name |
|
|
92
|
+
| `commands?.register(command)` | Register a slash command (see "Slash commands"); available to host adapters and local extensions, returns an unregister function; since host-api 1.4, check `api.commands !== undefined` first |
|
|
93
|
+
| `commands?.list()` | Registered command names (all modules), in registration order |
|
|
94
|
+
| `minor?` | `HOST_API_MINOR` (see "Versioning"); missing in older runtimes |
|
|
92
95
|
|
|
93
96
|
During `create()` the session is not assembled yet: `session.*` returns the values fixed at startup, and `sendUser` is rejected with `busy`. To send a message at startup, wait for the `session_start` event.
|
|
94
97
|
|
|
@@ -124,6 +127,31 @@ Host tools take the same path as built-in tools: schema validation → command h
|
|
|
124
127
|
|
|
125
128
|
The exported `ToolPermission` type gains `"network"` (used by the built-in `web_fetch`; judged as execute and asks in plan, see [permissions.md](../guides/permissions.md) "Network class"); tools registered by a host through `tools.register` still accept only `read` / `write` / `execute`, and `HOST_API_VERSION` is unchanged.
|
|
126
129
|
|
|
130
|
+
## Slash commands
|
|
131
|
+
|
|
132
|
+
`api.commands.register({ name, description, args?, run(args, ctx) })` (host-api 1.4): registers a `/name` command and returns an unregister function.
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
interface HostCommand {
|
|
136
|
+
name: string; // ^[a-z][a-z0-9-]{0,63}$, no slash
|
|
137
|
+
description: string; // shown in /help and completion
|
|
138
|
+
args?: string; // argument placeholder, e.g. "[day]"
|
|
139
|
+
run(args: string, ctx: HostCommandContext): HostCommandResult | Promise<HostCommandResult>;
|
|
140
|
+
}
|
|
141
|
+
interface HostCommandContext {
|
|
142
|
+
mode: "interactive" | "line" | "print" | "rpc";
|
|
143
|
+
session: { id(): string; cwd(): string };
|
|
144
|
+
}
|
|
145
|
+
type HostCommandResult =
|
|
146
|
+
{ kind: "handled"; message?: string } | { kind: "prompt"; text: string } | undefined;
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
- `register` throws (`command_exists`) for a built-in command, an alias (`quit`, `q`, `?`), an interactive-UI command (`tree`, `permissions`) or an already registered name; a bad name format, `description` or `run` throws `invalid_arguments`.
|
|
150
|
+
- Dispatch is after built-in commands and before prompt templates; `args` is everything after the command name, trimmed.
|
|
151
|
+
- A `handled` `message` is shown to the user (message area in interactive / line, a `notification` event in RPC) and does not enter the conversation; `prompt` sends `text` as the user prompt; `undefined` means `{ kind: "handled" }`; any other shape, or an empty `text`, throws and is shown as a command error.
|
|
152
|
+
- Dispatched in interactive, line and RPC modes; `-p` and ACP do not dispatch slash commands. Listed by `/help`, completion and RPC `get_commands` (`source: "extension"`).
|
|
153
|
+
- Host adapters and local extensions share one table, so command names are globally unique.
|
|
154
|
+
|
|
127
155
|
## Events
|
|
128
156
|
|
|
129
157
|
`events.on` handlers only observe: a throw is just logged and does not affect the run; handlers are called and awaited in order, and `session_shutdown` is awaited (so you can clean up before exit).
|
|
@@ -156,7 +184,7 @@ For token-level streaming content or the full event stream, use RPC or the SDK's
|
|
|
156
184
|
- `ask` answers by returning `"allow"` / `"deny"` / `"allow_session"`; returning `undefined` passes to the next answerer; a throw counts as deny.
|
|
157
185
|
- `request`: `requestId`, `toolName`, `input`, `reason: "mode" | "dangerous" | "hook"`, `hookReason?`, `preview?` (the pre-execution preview, see [rpc.md](rpc.md) "Approvals"), `context?` (`depth > 0` means it comes from a `task` sub-agent; codemode inner calls carry `parentToolCallId`).
|
|
158
186
|
- On timeout (10 minutes by default, `AMA_APPROVAL_TIMEOUT_MS`) or when the run is interrupted, `signal` aborts and the decision is deny. Approvals are serial: only one request waits at a time.
|
|
159
|
-
- Timing: the broker is looked up at each approval, so it can be set in `create()` or set / replaced at any later time; the last `setBroker` wins.
|
|
187
|
+
- Timing: the broker is looked up at each approval, so it can be set in `create()` or set / replaced at any later time; within one module the last `setBroker` wins. With several modules (a host adapter plus [local extensions](../guides/extensions.md)) only the first setter counts; later calls are ignored with a warning.
|
|
160
188
|
- The host broker only decides "who answers an ask"; it cannot loosen deny rules, command hook denies or dangerous-command detection ([design.md](../../design/design.md) §6.3, Chinese).
|
|
161
189
|
|
|
162
190
|
## Cache warming
|
package/docs/en/reference/rpc.md
CHANGED
|
@@ -49,6 +49,8 @@ A command has the shape `{ "id"?: string, "type": <command name>, ...parameters
|
|
|
49
49
|
| `abort` | — | `{}` (answered once idle again; the queue is not cleared) |
|
|
50
50
|
| `clear_queue` | — | `{ steering: string[], followUp: string[] }` (the cleared text) |
|
|
51
51
|
|
|
52
|
+
When the `message` of a `prompt` looks like `/name args` and matches a command registered by a host adapter or local extension (`source: "extension"` in `get_commands`), ama dispatches it first: `handled` emits the command's `message` as a `notification` (`level: "info"`) and answers `disposition: "handled"` without starting a turn; `prompt` sends the text the command returned instead; a command error is answered as a failure.
|
|
53
|
+
|
|
52
54
|
Prompt commands **do not wait for the run to finish**: they are answered as soon as the session starts running (`before_agent_start` / `agent_start`), or the message is queued or handled (for example a slash command, or a hook block); progress arrives as events. Sending `prompt` while running without `streamingBehavior` fails with `code: "busy"`; with `steer` / `followUp` it is queued. Run failures after the response are reported as `{"type":"notification","level":"error","message":…}`.
|
|
53
55
|
|
|
54
56
|
**Interrupt and send now**: with `interrupt: true` on `prompt` / `steer` (it takes precedence over `streamingBehavior`), a running session first takes the queued steers, stops the current turn (the model stream is cut, running tools finish as interrupted so every tool call has exactly one `aborted by user` result, and the interrupted assistant message is persisted with `stopReason: "aborted"`), then immediately starts a new turn with "queued steers… + this message" (joined by blank lines) and answers `{ disposition: "started" }`; the new user message has `origin: "interrupt"`. followUp messages stay queued and are delivered after the new turn; background sub-agents are not affected. When idle it is the same as leaving it out. A non-boolean `interrupt` → `invalid_arguments`; running with both the message and the queued steers empty → `invalid_arguments` (nothing is interrupted). Event order: `queue_update` (steers taken) → the old turn's `message_end` (aborted) → `agent_settled` → `agent_start` → the response → the new user `message_end` … (golden record `test/fixtures/rpc/interrupt.out.jsonl`). The new request starts with every message of the interrupted request, so the cache keeps hitting. In the SDK: `session.prompt(text, { interrupt: true })` / `session.steer(text, { interrupt: true })`.
|
|
@@ -124,13 +126,13 @@ After a session switch the server re-subscribes to events and sends `session_sta
|
|
|
124
126
|
|
|
125
127
|
### Tools, permissions, discovery
|
|
126
128
|
|
|
127
|
-
| Command | Parameters | `data`
|
|
128
|
-
| --------------------- | ---------------------------------------------------------------------- |
|
|
129
|
-
| `get_tools` | — | `{ tools: { name, description, parameters, permission, active }[] }` (every tool in the registry; `active` means the model sees it now)
|
|
130
|
-
| `set_active_tools` | `names: string[]` | `{ names }` (active tool names after the change)
|
|
131
|
-
| `set_permission_mode` | `mode: plan \| allowlist \| default \| auto-edit \| auto \| full-auto` | `{ mode }` (unknown mode → `invalid_arguments`)
|
|
132
|
-
| `get_commands` | — | `{ commands: { name, description?, source: "builtin" \| "template" \| "skill" }[] }`; Skill names are written `skill:<name>`; only built-in commands that are currently available are listed (no `memory` while memory is off, no `tasks` when task cannot be called) |
|
|
133
|
-
| `get_skills` | — | `{ skills: { name, description, location, … }[] }` (discovered Skills; `location` is the SKILL.md path)
|
|
129
|
+
| Command | Parameters | `data` |
|
|
130
|
+
| --------------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
131
|
+
| `get_tools` | — | `{ tools: { name, description, parameters, permission, active }[] }` (every tool in the registry; `active` means the model sees it now) |
|
|
132
|
+
| `set_active_tools` | `names: string[]` | `{ names }` (active tool names after the change) |
|
|
133
|
+
| `set_permission_mode` | `mode: plan \| allowlist \| default \| auto-edit \| auto \| full-auto` | `{ mode }` (unknown mode → `invalid_arguments`) |
|
|
134
|
+
| `get_commands` | — | `{ commands: { name, description?, source: "builtin" \| "template" \| "skill" \| "extension" }[] }`; Skill names are written `skill:<name>`; `extension` is a command registered through `commands.register` by a host adapter or local extension (#301); only built-in commands that are currently available are listed (no `memory` while memory is off, no `tasks` when task cannot be called) |
|
|
135
|
+
| `get_skills` | — | `{ skills: { name, description, location, … }[] }` (discovered Skills; `location` is the SKILL.md path) |
|
|
134
136
|
|
|
135
137
|
### Plans and tasks (wave 5)
|
|
136
138
|
|
|
@@ -204,7 +206,7 @@ Events are the in-process `SessionEvent` (`src/agent/types.ts`); only `message_u
|
|
|
204
206
|
| `agent_settled` | `warning?` (the run has fully ended, retries and followUps included) |
|
|
205
207
|
| `message_start` / `message_end` | `message` (`AgentMessage`) |
|
|
206
208
|
| `message_update` | `assistantMessageEvent`, `usage?` (see below) |
|
|
207
|
-
| `tool_execution_start` | `toolCallId`, `toolName`, `args`, `parentToolCallId?`
|
|
209
|
+
| `tool_execution_start` | `toolCallId`, `toolName`, `args`, `coercedArguments?`, `parentToolCallId?` |
|
|
208
210
|
| `tool_execution_update` | `toolCallId`, `toolName`, `partial` (output text while running), `parentToolCallId?` |
|
|
209
211
|
| `tool_execution_end` | `toolCallId`, `toolName`, `result`, `isError`, `parentToolCallId?`, `autoDecision?` (auto mode: `{ layer: rule \| static \| classifier, decision, reason, cached? }`), `denied?` (`true`: not executed because permissions / a hook / approval denied it; the reason is in `result`) |
|
|
210
212
|
| `queue_update` | `steering: string[]`, `followUp: string[]` |
|
|
@@ -225,6 +227,8 @@ Events are the in-process `SessionEvent` (`src/agent/types.ts`); only `message_u
|
|
|
225
227
|
|
|
226
228
|
There is also the non-session event `{"type":"notification","level":"info"|"warn"|"error","message":…}`: the host's `ui.notify` and run failures after the response.
|
|
227
229
|
|
|
230
|
+
`coercedArguments` is an optional additive field: when the model's arguments failed strict validation but passed after lenient coercion, it holds the arguments the permission gate, hooks and the tool actually received (`args` stays as the model sent it, as does the session history); it is absent when the arguments were valid as sent. Older clients can ignore it; `RPC_PROTOCOL_VERSION` is unchanged.
|
|
231
|
+
|
|
228
232
|
`parentToolCallId` appears only on inner calls made through `tools.*` inside codemode scripts; its value is the id of the outer `codemode` call, which clients use to fold the display. Inner calls do not enter the transcript.
|
|
229
233
|
|
|
230
234
|
Assistant messages in `message_end`, `turn_end`, `done` / `error` and in replays (`get_messages`, `get_entries`) may carry two optional fields (model efficiency batch, docs/history/model-efficiency-plan.md §1.10, Chinese): `retryAfterMs` on failed messages (`Retry-After`, in ms) and `rawArguments` on tool-call blocks (the raw argument string the model produced). `subagent_*` events are unchanged; `TaskInfo` from `get_tasks` may carry `context?: "fork" | "fresh"` (the sub-session's actual context mode). All are new optional fields, `RPC_PROTOCOL_VERSION` is unchanged, and clients can ignore fields they do not know.
|
package/docs/guides/codemode.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
设计依据见 [design.md](../design/design.md) §5.5、§5.6、§9.1。
|
|
4
4
|
|
|
5
|
-
`codemode` 工具让模型写一段 JavaScript,在脚本里经 `tools.*` 编排多次工具调用,只有脚本输出回到模型。长流程、工具密集的任务里,它把多次往返合成一次,减少往返次数与缓存读取;短任务里模型照常直接调用工具,codemode 只多占约 400 token 前缀,所以 `default`
|
|
5
|
+
`codemode` 工具让模型写一段 JavaScript,在脚本里经 `tools.*` 编排多次工具调用,只有脚本输出回到模型。长流程、工具密集的任务里,它把多次往返合成一次,减少往返次数与缓存读取;短任务里模型照常直接调用工具,codemode 只多占约 400 token 前缀,所以 `default` 预设缺省开着它(脚本总是被隔离,见下文「引擎」)。
|
|
6
6
|
|
|
7
7
|
## 打开
|
|
8
8
|
|
|
@@ -14,13 +14,13 @@
|
|
|
14
14
|
|
|
15
15
|
`codemode.mode` 不写时**跟随预设**:
|
|
16
16
|
|
|
17
|
-
| 预设 |
|
|
18
|
-
| ------------------------- |
|
|
19
|
-
| `default` | `on`
|
|
20
|
-
| `codemode-only` | `only`
|
|
21
|
-
| `minimal` / `coordinator` | `off`
|
|
17
|
+
| 预设 | 脚本被隔离(缺省的 `codemode.engine: "auto"` 下总是如此) | `codemode.engine: "node"` 且 Node 22 / 24 没有操作系统沙箱 |
|
|
18
|
+
| ------------------------- | --------------------------------------------------------- | ---------------------------------------------------------------------- |
|
|
19
|
+
| `default` | `on` | `off`,启动时提示一次(每个配置目录一次,记在数据目录 `notices.json`) |
|
|
20
|
+
| `codemode-only` | `only` | `only`(`execute` 类,见下) |
|
|
21
|
+
| `minimal` / `coordinator` | `off` | `off` |
|
|
22
22
|
|
|
23
|
-
操作系统沙箱指 macOS 的 `sandbox-exec`、Linux 的 bubblewrap(退而 `unshare -r -n`),见下文沙箱与 [sandbox.md](sandbox.md);Windows
|
|
23
|
+
操作系统沙箱指 macOS 的 `sandbox-exec`、Linux 的 bubblewrap(退而 `unshare -r -n`),见下文沙箱与 [sandbox.md](sandbox.md);Windows 没有。没有它、Node 也低于 25 时,`auto` 引擎改用 WebAssembly 里的 QuickJS(见下文「引擎」),脚本同样被隔离,所以这些平台也缺省开着 codemode。
|
|
24
24
|
|
|
25
25
|
缺省配置里不写 `codemode.mode`(`ama init` 生成的 `config.json` 也不写),所以这张映射以后调整时老用户同样生效。`ama config show` / `ama doctor` 显示生效模式与原因(跟随哪个预设、网络由 Node 还是操作系统沙箱隔离);`ama doctor` 另列操作系统沙箱能力。
|
|
26
26
|
|
|
@@ -28,13 +28,13 @@
|
|
|
28
28
|
|
|
29
29
|
`coordinator` 预设即使显式 `on`,脚本里能调用的工具也只限它的活动集(read 与宿主工具):`tools.bash`、`tools.write` 在脚本里同样不存在,协调者「不写文件、不跑 bash」的约定不能经 codemode 绕过。
|
|
30
30
|
|
|
31
|
-
`codemode`
|
|
31
|
+
`codemode` 本身的权限类随沙箱能力:脚本被隔离(Node ≥ 25、有操作系统沙箱,或用 QuickJS 引擎,见下文沙箱与引擎)时是 `read` 类,`default` 权限模式下免审批——脚本只能经 `tools.*` 做事,每次内层调用仍逐个经过权限管线;网络未隔离(显式 `codemode.engine: "node"`,且 Node 22 / 24 没有操作系统沙箱)时是 `execute` 类,`default` 模式下每次都要审批,`-p` 等无人值守场景直接拒绝,此时常用做法是在配置里放行它:
|
|
32
32
|
|
|
33
33
|
```json
|
|
34
34
|
{ "version": 1, "tools": { "preset": "codemode-only" }, "permission": { "allow": ["codemode"] } }
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
-
其它配置:`codemode.inlineBudget`(`only` 模式在描述里内联声明的预算,估算 token,缺省 3000,超出只列名字;`on` 模式不内联)、`codemode.requireStrict`(见下文沙箱)、`codemode.maxHeapMb
|
|
37
|
+
其它配置:`codemode.inlineBudget`(`only` 模式在描述里内联声明的预算,估算 token,缺省 3000,超出只列名字;`on` 模式不内联)、`codemode.requireStrict`(见下文沙箱)、`codemode.maxHeapMb`(脚本引擎的内存上限,见下文沙箱)、`codemode.maxWorkers`(同时存活的脚本子进程数,见下文「并发」)、`codemode.engine`(`auto` / `node` / `quickjs`,见下文「引擎」;只认用户级)。项目级配置只能把 `codemode.mode` 设为 `off`。
|
|
38
38
|
|
|
39
39
|
`on` 模式的前缀开销:去重前 `codemode` 描述把已直接暴露的六个工具的声明又内联一遍,其它工具各追加一行提示,系统提示 + 工具表比 `off` 多约 1356 token;现在只多约 390 token(字符 / 4 估算,测试锁定 ≤ 500)。升级后续接的旧会话因为描述字节变化会有一次缓存未命中。
|
|
40
40
|
|
|
@@ -57,6 +57,8 @@
|
|
|
57
57
|
| `store(key, v)` / `load(key)` | 跨次保留小块 JSON;`store(key, undefined)` 删除 |
|
|
58
58
|
| `ALL_TOOLS` | 可调用工具名(执行时的清单,含描述冻结之后才注册的宿主工具) |
|
|
59
59
|
| `describeTool(name)` | 单个工具的 TypeScript 声明 |
|
|
60
|
+
| `searchTools(query, opts?)` | 在可调用工具里按 BM25(名字 + 描述)排序,见下 |
|
|
61
|
+
| `image(value)` | 把一张图附在脚本结果后面,见下 |
|
|
60
62
|
|
|
61
63
|
没有 `require`、`import`、`process`、`fetch`、定时器;`eval` 与 `new Function` 被拒绝。工具只能写成 `tools.read({ path })`,不能直接 `read(...)`。
|
|
62
64
|
|
|
@@ -70,11 +72,16 @@
|
|
|
70
72
|
|
|
71
73
|
### 返回值
|
|
72
74
|
|
|
73
|
-
- `bash` 解析为 `{ output, truncated, fullOutputPath?, exitCode, wallTimeMs }
|
|
75
|
+
- `bash` 解析为 `{ output, truncated, fullOutputPath?, exitCode, wallTimeMs }`,非零退出码同样解析。脚本里的 `output` 放宽到 1 MiB:全文不超过 1 MiB 时就是全文(`truncated` 为假);更长时保留首尾各 512 KiB,中间是 `[... N bytes omitted; full output: <路径> ...]`,`truncated` 为真,`fullOutputPath` 指向全文文件(可再 `tools.read` 或自己切片)。模型直接调用 bash 的结果不变(2000 行 / 50 KB 尾截断)。脚本最终输出仍按 `max_output_tokens` 截断。
|
|
74
76
|
- 其它内置工具解析为文本;宿主 / SDK 工具返回 `structured` 时解析为它,否则为文本。
|
|
75
77
|
- 工具失败、被 Hook / 权限 / 用户拒绝、参数非法 → 以 `Error` reject,消息是工具的错误文本;用 `Promise.allSettled` 保留其余结果。
|
|
76
78
|
- 同一脚本内最多 8 个调用同时进行,多出的排队;脚本里不能调用 `codemode`。
|
|
77
79
|
|
|
80
|
+
### searchTools 与 image
|
|
81
|
+
|
|
82
|
+
- `await searchTools(query, { limit?, namespace? })`:在本次执行可调用的工具里按 BM25(名字 + 描述)排序,解析为 `{ name, description }[]`(描述取首段、≤ 240 字符);`limit` 缺省 8、上限 50;`namespace` 是工具名前缀(`_` `.` `:` `-` 之前的部分,如 `canvas` 匹配 `canvas_add`)。没有命中为空数组;参数不合法时 reject。它不是工具调用,不过权限也不发事件。工具多、描述里只列了名字时先搜再 `describeTool(name)`。
|
|
83
|
+
- `image(value)`:`value` 可以是 base64 的 `data:` URL、`{ image_url }`(字符串或 `{ url }`)、或 `{ type: "image", data, mimeType }`(`tools.read` 读一张图时解析为后者,可直接传入)。只收 PNG / JPEG / GIF / WebP,MIME 由文件头决定(声明的 MIME 被忽略),远程 URL 一律拒绝;不合法时同步抛 `TypeError`。每个脚本最多 8 张,单张受当前端点的上限约束(超限的跳过并在结果里说明)。图片作为图片块附在脚本结果之后,同时存成 `<会话目录>/outputs/<toolCallId>-image-<n>.<扩展名>`(与超长文本同目录),结果文本里写明路径;模型不收图片时协议层会丢掉图片块,路径仍在。
|
|
84
|
+
|
|
78
85
|
### 结果
|
|
79
86
|
|
|
80
87
|
`Script completed` / `Script failed` + 用时 + 输出;失败时保留已产生的输出,末尾附 `Script error: …`(带脚本行号)。已完成的工具调用不回滚;脚本结束时仍在跑的调用被取消,未 await 的 Promise 被丢弃。
|
|
@@ -83,21 +90,54 @@
|
|
|
83
90
|
|
|
84
91
|
脚本成功结束且写过 store 时,追加一条 `custom{customType:"ama.codemode-store"}` 条目,内容是完整快照;读取取活动分支上最近一条,所以 `/resume` 后值仍在,切分支、fork 后只看本分支写过的值。单值 JSON ≤ 262 144 字符,合计 ≤ 1 048 576 字符;超限时 `store()` 抛 `RangeError`。失败的脚本不提交。
|
|
85
92
|
|
|
93
|
+
### 并发
|
|
94
|
+
|
|
95
|
+
整个 ama 进程(所有会话与子 Agent)同时存活的脚本子进程不超过 2 个;多出的脚本按先来先到排队,最多等 60 s,也不超过脚本自己的 `timeout_ms`(等待计入 `timeout_ms`),到点失败且**没有运行**(错误文本说明名额一直被占)。等待期间被取消立即结束。名额在子进程真正退出时才归还,不是结果落定时。
|
|
96
|
+
|
|
97
|
+
上限:配置 `codemode.maxWorkers`(正整数,缺省 2,只认用户级)< 环境变量 `AMA_CODEMODE_MAX_WORKERS`(正整数,每次执行时读取,不合法的值被忽略)。
|
|
98
|
+
|
|
99
|
+
### 脚本被杀之后
|
|
100
|
+
|
|
101
|
+
脚本每完成一个内层调用就追加一条 `custom{customType:"ama.codemode-call"}`(`{ parent, name, target?, ok }`,不进上下文;`target` 与恢复提醒共用规则:bash 只取命令第一个词,write / edit 取路径,不含参数正文与结果)。进程在脚本跑到一半时被杀,下次 `resume` 的恢复提醒会列出外层 `codemode` 调用没有结果时它已经完成的内层调用(`write src/a.ts: ok`),并要求先核实现场、不要盲目重复。被脚本结束取消的调用不记。
|
|
102
|
+
|
|
86
103
|
## Hook 与事件
|
|
87
104
|
|
|
88
105
|
- `codemode` 本身作为一次工具调用经过 PreToolUse、权限与 PostToolUse。
|
|
89
106
|
- 脚本里的每次 `tools.*` 再各自经过完整流程,Hook 按**真实工具名**匹配(`bash`,不是 `codemode`);Hook 输入多两个字段:`viaCodemode: true` 与 `parentToolCallId`(外层 `codemode` 调用的 id)。
|
|
90
107
|
- 事件:`tool_execution_update` 透传脚本输出(最近 4000 字符);内层调用发 `tool_execution_start / end`,带 `parentToolCallId`,不进转录、不进模型上下文。`ama --mode acp` 把每次内层调用单列为一条 `tool_call`(标题前缀 `codemode › `,`_meta.ama.parentToolCallId` 指向外层),其权限请求关联到这条内层调用(见 [acp.md](../reference/acp.md))。
|
|
91
108
|
|
|
109
|
+
## 引擎
|
|
110
|
+
|
|
111
|
+
脚本有两种运行方式,工具描述、全局、结果格式与权限管线完全相同:
|
|
112
|
+
|
|
113
|
+
| `codemode.engine` | 运行方式 |
|
|
114
|
+
| ----------------- | ------------------------------------------------------------------------------------------------------- |
|
|
115
|
+
| `node` | 每次执行起一个 Node 子进程(下文「沙箱」) |
|
|
116
|
+
| `quickjs` | 每次执行起一个 worker 线程,脚本跑在 WebAssembly 里的 QuickJS(QuickJS-ng)中 |
|
|
117
|
+
| `auto`(缺省) | 网络已隔离(Node ≥ 25,或有操作系统沙箱)用 `node`,否则(Node 22 / 24 无沙箱,含 Windows)用 `quickjs` |
|
|
118
|
+
|
|
119
|
+
`ama config show` 与 `ama doctor` 显示生效的引擎与原因(`codemode.engine` 行与 `codemode engine:` 行)。
|
|
120
|
+
|
|
121
|
+
QuickJS 引擎:
|
|
122
|
+
|
|
123
|
+
- 零依赖:引擎是随包分发的一个 wasm 文件(`assets/quickjs/`,`ama.cjs` 里内联),用 `WebAssembly` 与 `node:worker_threads` 自己驱动;来源、版本与哈希见该目录的 README。
|
|
124
|
+
- 隔离:VM 里没有 `require`、`import`、`process`、`fetch`、定时器、文件与网络;WASI 只给时钟与随机数,stdout / stderr 丢弃;与外界只有一个宿主函数,脚本只能经 `tools.*` 触达外界,所以 `codemode` 是 `read` 类,每次内层调用仍逐个过权限管线。内建对象在脚本运行前冻结(Error 原型除外,子类里 `this.name = …` 要能赋值);`eval` / `new Function` 留在 VM 内,拿不到宿主。
|
|
125
|
+
- 期限:脚本总超时与外层 abort 先写共享的中断标志(空转的 `while (true) {}`、`while (true) await null` 都会被打断),随后 `worker.terminate()`。
|
|
126
|
+
- 内存:`codemode.maxHeapMb`(缺省 256 MB,0 不设上限)限制 QuickJS 堆,超出时与 node 引擎同一条脚本错误。
|
|
127
|
+
- 栈:引擎的 JS 调用栈上限设为 320 KB(`qjs_set_max_stack_size`,wasm 的 C 栈约 400 KB),无界递归抛出可捕获的 `RangeError: Maximum call stack size exceeded`,与 node 引擎同一句话,`try { f() } catch {}` 之后脚本继续运行;约 1300 层简单调用,比 node 引擎浅得多。例外:不经 JS 调用的原生递归(超深嵌套的 JSON、嵌套字面量)会直接让实例陷阱,无法在脚本里捕获,结果是以 `RangeError: Maximum call stack size exceeded (QuickJS engine trap: …)` 开头的脚本错误,此前已产生的输出保留,宿主不受影响。
|
|
128
|
+
- 与 node 引擎共用同一套宿主行为:QuickJS worker 与子进程一起计入进程级名额(`codemode.maxWorkers`,排队规则与超时文案相同,名额在 worker 真正退出时归还);`searchTools()`、`image()`(校验、最多 8 张、存进 outputs 目录)、脚本里 `tools.bash` 放宽的输出与 `ama.codemode-call` 恢复记录在两种引擎下一致。
|
|
129
|
+
- 脚本等待一个永远不会落定的 Promise(没有未完成的工具调用)时立即失败,不拖到超时。
|
|
130
|
+
- 与 node 引擎的差异:解释执行,纯计算慢约 6 倍(工具调用主导的脚本几乎没差别);每次执行启动更快(约 15 ms,对比约 50 ms);`Date` 用宿主时区;没有 V8 特有的 API(`Error.captureStackTrace` 等);错误文案按 QuickJS 的写法(如动态 `import()` 报 `could not load module`)。
|
|
131
|
+
|
|
92
132
|
## 沙箱
|
|
93
133
|
|
|
94
|
-
|
|
134
|
+
每次执行起一个子进程(`node` 引擎):
|
|
95
135
|
|
|
96
136
|
```text
|
|
97
137
|
<node> --max-old-space-size=256 --permission --allow-fs-read=<ama-sandbox.cjs> --disallow-code-generation-from-strings <ama-sandbox.cjs> --ama-codemode-sandbox
|
|
98
138
|
```
|
|
99
139
|
|
|
100
|
-
- 堆上限:`--max-old-space-size` 取 `codemode.maxHeapMb`(缺省 256 MB,0
|
|
140
|
+
- 堆上限:`--max-old-space-size` 取 `codemode.maxHeapMb`(缺省 256 MB,0 不加;只认用户级;`quickjs` 引擎同一个键限制 QuickJS 堆)。脚本超出时子进程 OOM 退出,工具结果是脚本错误 `Script exceeded the codemode memory limit (256 MB); process the data in smaller pieces`,宿主进程内存不受影响;需要一次处理大数据时调大或分片。
|
|
101
141
|
|
|
102
142
|
- 空环境启动,拿不到密钥、会话文件与环境变量(Windows 上 libuv 会从父进程补入 PATH、SYSTEMROOT、USERPROFILE 等系统变量,不含密钥);不授予文件写、子进程、worker、addon、inspector 权限;Node 22.0–22.12 用 `--experimental-permission`;嵌入 Electron 时设 `ELECTRON_RUN_AS_NODE=1`。
|
|
103
143
|
- 子进程里用 `node:vm` 建只含 ECMAScript 内建对象的上下文(`codeGeneration: { strings: false, wasm: false }`,沙箱对象空原型);全局函数都在上下文内定义,只经一个宿主函数交换 JSON 字符串;子进程主 realm 也禁止字符串生成代码,经构造器链逃逸拿不到 `Function("return process")`。
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# 本地扩展
|
|
2
|
+
|
|
3
|
+
用户自己安装、可以有多个的宿主适配器:在进程内观察事件、注册工具与斜杠命令、在界面上给出通知与状态,而不占用宿主(`--host` / profile `host`,如 Armadra 画布)的位置。命令式 Hook([hooks.md](hooks.md))只能在固定时机跑外部命令,扩展补上进程内的这一层。
|
|
4
|
+
|
|
5
|
+
扩展与宿主适配器是**同一个模块形状**:`HostModule`(`hostApi` + `create(api)`),拿到的是同一个 `HostApi`,类型与各成员的细节见 [host-api.md](../reference/host-api.md)。本文只讲扩展特有的部分:加载、共存规则、斜杠命令、信任与 `ama doctor`。
|
|
6
|
+
|
|
7
|
+
## 写一个扩展
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
// ~/.config/ama/extensions/standup.mjs
|
|
11
|
+
export const hostApi = 1;
|
|
12
|
+
|
|
13
|
+
export function create(api) {
|
|
14
|
+
api.commands.register({
|
|
15
|
+
name: "standup",
|
|
16
|
+
description: "Summarize today's work",
|
|
17
|
+
args: "[day]",
|
|
18
|
+
run(args, ctx) {
|
|
19
|
+
return {
|
|
20
|
+
kind: "prompt",
|
|
21
|
+
text: `Summarize what we did in ${ctx.session.cwd()} ${args || "today"}.`,
|
|
22
|
+
};
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
api.events.on("agent_settled", () => api.ui.setStatus("standup", "ready"));
|
|
26
|
+
return { id: "standup" };
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
模块可以是 `.mjs`(ESM)或 `.cjs`;导出 `default` 或具名的 `hostApi` + `create` 都行。`create()` 返回的适配器必须有 `id`,可以带 `dispose()`(退出时调用)。返回 `undefined` 表示不启用。
|
|
31
|
+
|
|
32
|
+
## 位置与加载
|
|
33
|
+
|
|
34
|
+
- **用户级目录**:`<configDir>/extensions/` 下的单文件 `*.{mjs,cjs}` 与**目录扩展** `<名>/index.{mjs,cjs}`(`index.mjs` 优先),一起按入口名(文件名或目录名)排序(缺省 `~/.config/ama/extensions/`,`AMA_CONFIG_DIR` 可改)。没有 `index.*` 的子目录忽略。
|
|
35
|
+
- **profile**:`extensions: ["/abs/a.mjs", "/abs/dir-ext", …]`(绝对路径,可以是目录扩展),排在用户级目录之后;同一路径只加载一次。
|
|
36
|
+
- **不支持项目级**:仓库里的 `.ama/extensions/` 不加载。扩展以进程权限运行、能注册工具,等同于执行任意代码,不随仓库分发。
|
|
37
|
+
- **顺序**:宿主适配器最先激活;扩展在它之后、组装会话之前(启动第 13 步)。
|
|
38
|
+
|
|
39
|
+
## 共存规则
|
|
40
|
+
|
|
41
|
+
每个模块有独立的 `HostApi` 实例(各自的工具清单与状态键),共享同一个工具注册表、事件总线、审批 broker 槽、资源注册表与保温处理器。
|
|
42
|
+
|
|
43
|
+
| 面 | 多个模块共存时 |
|
|
44
|
+
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
45
|
+
| `tools.register` | 先到先得;同名时后来者抛 `tool_exists`(扩展可以自己捕获;不捕获则 `create()` 失败,整个扩展被跳过) |
|
|
46
|
+
| `tools.disable` | 累加 |
|
|
47
|
+
| `instructions.add` | 按加载顺序(宿主适配器在前)追加到系统提示的 `host` 节 |
|
|
48
|
+
| `events.on` | 都收到,按注册顺序依次调用 |
|
|
49
|
+
| `approvals.setBroker` | 只认第一个设置者(通常是宿主适配器);其余调用忽略并 warning。同一个模块可以再次设置覆盖自己 |
|
|
50
|
+
| `ui.notify` / `ui.setStatus` | 都可用;状态栏把各模块的键合并显示,同名键后加载的覆盖先加载的,所以键名建议带自己的前缀 |
|
|
51
|
+
| `cache.onWarmingDecision` | 跨模块最后注册且未注销的处理器生效 |
|
|
52
|
+
| `commands.register` | 见下节;命令名全局唯一,先注册先得 |
|
|
53
|
+
| `runners.provide` / `onDone` | 共享一张 runner 表,模块之间先到先得(同 id 后来者抛 `runner_exists`,同一模块再次提供替换自己的);`onDone` 只回调本模块的 runner;有无宿主适配器都被 `task` 使用 |
|
|
54
|
+
| `create()` 失败 / 超时 | 宿主适配器失败仍是退出码 6;**扩展失败只记 warning 并跳过**,不阻止启动 |
|
|
55
|
+
| 加载失败 / `hostApi` 版本不等 | 宿主适配器仍是退出码 78 / 6;扩展跳过并 warning |
|
|
56
|
+
| 退出 | 按加载的逆序 `dispose`(扩展先、宿主适配器最后),某个失败只记 warning |
|
|
57
|
+
|
|
58
|
+
没有扩展时,系统提示与工具表与以前逐字节相同。Hook 公共字段里的 `host` 仍是宿主适配器的 id,扩展不改它。
|
|
59
|
+
|
|
60
|
+
扩展的 `create()` 抛错、超时或没有返回适配器时,它此前注册的全部内容都会被撤回:工具(禁用的工具恢复)、事件订阅、命令、指令、状态键、保温处理器、自己持有的 broker、runner 与资源。撤回之后该模块再调用注册类方法(例如超时后迟到的注册)一律忽略并写 warning。
|
|
61
|
+
|
|
62
|
+
## 子 Agent runner
|
|
63
|
+
|
|
64
|
+
`api.runners.provide(runner)` 在宿主适配器与扩展之间共用一张表,`task(agent=<id>)`、`/agents` 与 RPC `get_agents` 都读它:
|
|
65
|
+
|
|
66
|
+
- 模块之间同 id 先到先得,后来者抛 `runner_exists`;同一模块再次提供同 id 替换自己的;注销或模块被撤回后 id 可再提供。
|
|
67
|
+
- 没有宿主适配器时扩展的 runner 同样生效,与宿主注入的同等优先(同 id 会替换内置的外部 runner,如 `claude`);“有宿主适配器时 ama 不自起外部 CLI”的判定仍只看宿主适配器,扩展不改变它。
|
|
68
|
+
- `api.runners.onDone(handler)` 只回调本模块自己提供的 runner。
|
|
69
|
+
|
|
70
|
+
## 斜杠命令
|
|
71
|
+
|
|
72
|
+
`api.commands.register({ name, description, args?, run(args, ctx) })`(host-api 1.4,可选成员,用前判断 `api.commands !== undefined`),宿主适配器与扩展都可用,返回注销函数。
|
|
73
|
+
|
|
74
|
+
- **名字**:`^[a-z][a-z0-9-]{0,63}$`,不带斜杠。与内置命令、别名(`quit`、`q`、`?`)、交互界面命令(`tree`、`permissions`)同名,或与已注册的命令同名,注册时抛错。
|
|
75
|
+
- **分派**:内置命令之后、提示模板之前。同名的提示模板被扩展命令遮住。`/skill:<名>` 不受影响。
|
|
76
|
+
- **`args`**:命令名之后的整段文本(已去掉首尾空白);`description` 与 `args`(占位提示,如 `"[day]"`)显示在 `/help` 与补全里。不做参数补全。
|
|
77
|
+
- **`ctx`**:刻意很小——`{ mode, session: { id(), cwd() } }`。要更多能力(发消息、读状态)用注册时拿到的 `api`。
|
|
78
|
+
- **返回值**:`{ kind: "handled", message? }`(`message` 显示给用户,不进对话)或 `{ kind: "prompt", text }`(改发这段文本作为用户提示);返回 `undefined` 等同 `{ kind: "handled" }`;其它形状按错误处理,`run` 自己抛的错也按错误显示,不影响会话。
|
|
79
|
+
- **在哪些模式可用**:交互、line、RPC、`-p`、ACP。提示整段形如 `/名 参数` 且命中扩展命令时在 ama 内分派,`prompt` 一律改发其 `text`;`handled` 按模式给出 `message`,都不开模型回合:
|
|
80
|
+
- RPC:`message` 作为 `notification` 事件发出,返回 `disposition: "handled"`。
|
|
81
|
+
- `-p`:`message` 写到 stdout 后退出 0(`--output-format text` 原样输出,`json` 与 `stream-json` 给一行 `result` 对象,`text` 是 `message`、用量为 0);`run` 抛错时 stderr 一行 `ama: <错误>`,退出码 1。只看命令行给的提示:有管道 stdin 时不分派,整段原样发给模型;`handled` 不读 `--image` 图片。
|
|
82
|
+
- ACP:`message` 作为一条 `agent_message_chunk` 发出,`session/prompt` 以 `end_turn` 结束(用量为 0);`run` 抛错时 `session/prompt` 答复 internal error。`available_commands_update` 列出扩展命令(`args` → `input.hint`),遮住同名提示模板。
|
|
83
|
+
- **列出**:`/help`、交互补全、RPC `get_commands`(`source: "extension"`)。
|
|
84
|
+
|
|
85
|
+
## 信任
|
|
86
|
+
|
|
87
|
+
扩展以进程权限运行,必须先被信任才加载。决定按**文件内容的 sha256**(目录扩展为整棵目录树的 sha256) 记在用户级 `trust.json` 的 `extensions` 段:
|
|
88
|
+
|
|
89
|
+
```json
|
|
90
|
+
{
|
|
91
|
+
"version": 1,
|
|
92
|
+
"entries": [],
|
|
93
|
+
"extensions": [
|
|
94
|
+
{ "path": "/abs/standup.mjs", "sha256": "…", "trusted": true, "at": "2026-11-15T12:00:00.000Z" }
|
|
95
|
+
]
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
决定顺序:
|
|
100
|
+
|
|
101
|
+
1. `--no-trust`:全部扩展都不加载。`--trust` 与 profile 的 `trustProject` **不影响**扩展(它们只管项目级资源)。
|
|
102
|
+
2. 记录里有同路径且哈希相同的条目:按记录的决定(信任则加载,拒绝则跳过)。
|
|
103
|
+
3. 没有记录,或文件内容变了(哈希不符):
|
|
104
|
+
- 交互 / line 模式:启动时**一次性**列出全部待定文件的路径与 sha256 询问(仅本次 / 信任并记住 / 不信任);记住的写入 `trust.json`,内容再变就重新询问。
|
|
105
|
+
- 其它模式(`-p`、RPC、ACP):不加载,写 warning(RPC / `-p` 的 stderr)。要启用,先在交互会话里确认一次。
|
|
106
|
+
|
|
107
|
+
哈希在加载前计算;加载之间文件被替换的竞争不在防护范围内(本地用户目录已是同一信任域)。
|
|
108
|
+
|
|
109
|
+
**目录扩展**的哈希覆盖整棵目录树,`trust.json` 记录形状不变(`path` 是目录,`sha256` 是树哈希),目录里任何文件改了都会重新询问,所以多文件扩展应写成目录,而不是只信任入口:
|
|
110
|
+
|
|
111
|
+
- 参与哈希的是目录下每个常规文件,按「正斜杠相对路径」的字节序排序(与平台、遍历与创建顺序无关),每项依次写入 `F <路径字节数> <路径> <内容字节数>\n` 与内容字节,前面加固定前缀 `armadra-ext-tree-v2\n`。路径与内容都带长度前缀,不会拼出歧义。
|
|
112
|
+
- **不跳过任何项**(包括 `.git` 与 `node_modules`):被跳过的文件照样能被 `import`,跳过就成了绕过信任的口子。
|
|
113
|
+
- 符号链接**跟随**:按目标的内容计入(指向目录外也一样),指向目录的链接递归进去;成环或断开的链接按「读不了」跳过。socket、fifo 等忽略。
|
|
114
|
+
- 上限:最多 2000 个文件、2000 个目录、32 层深、总计 50 MiB。超出时该扩展被跳过,原因是「目录扩展过大」,不会询问也不会加载。
|
|
115
|
+
- 交互询问与 `ama doctor` 都会把目录标出来。
|
|
116
|
+
|
|
117
|
+
单文件扩展照旧:只校验该文件本身,它 `import` 的其它文件不计入哈希;需要多文件时请改用目录扩展,或把依赖打包进单个文件。
|
|
118
|
+
|
|
119
|
+
## `ama doctor`
|
|
120
|
+
|
|
121
|
+
`ama doctor` 有「本地扩展」一节:列出每个文件的路径、sha256 前 12 位与状态——**启用**(记录匹配且已信任),或**跳过**及原因(未信任、内容自信任后已改变、已拒绝、读不了文件、目录扩展过大、`--no-trust`);目录扩展标 `[目录]`,哈希前缀是树哈希。doctor 只读文件与信任记录,**不执行扩展代码**,所以「加载失败 / 版本不等 / `create()` 失败 / 未返回适配器」这类只有加载时才知道的原因不在 doctor 里,它们作为 warning 出现在启动输出里(`-p` 与 RPC 写 stderr,交互模式显示在消息区)。
|
|
122
|
+
|
|
123
|
+
## 典型用例
|
|
124
|
+
|
|
125
|
+
| 用例 | 做法 |
|
|
126
|
+
| ---------- | ------------------------------------------------------------------------------------ |
|
|
127
|
+
| 下一步建议 | `events.on("agent_settled")` 后根据最后的回复给出 2–3 条建议,`ui.notify` 显示 |
|
|
128
|
+
| 桌面通知 | `agent_settled` 与 `tool_approval_requested` 时向终端写 OSC 777 通知序列 |
|
|
129
|
+
| git 检查点 | `turn_start` 时 `git stash create` 记录一个不改工作区的检查点,配合 `/undo` 命令回滚 |
|
|
130
|
+
| 自定义命令 | `commands.register({ name: "standup", … })` 汇总今天的会话 |
|
|
131
|
+
| 保温策略 | `cache.onWarmingDecision` 按时段或预算否决空闲保温 |
|
|
132
|
+
|
|
133
|
+
## 不做的事
|
|
134
|
+
|
|
135
|
+
- **不开放渲染层**:扩展不能替换或插入界面组件、不能接管按键。界面上的表达只有消息区通知、状态栏键值与斜杠命令的输出文本。
|
|
136
|
+
- 不做能力声明(信任对话框不按能力展示)、不做命令参数补全、不做扩展之间的依赖顺序(只有文件名排序)。
|
package/docs/guides/providers.md
CHANGED
|
@@ -607,6 +607,7 @@ compat 只记录**已验证**的差异;新增条目请附文档链接或真实
|
|
|
607
607
|
| `adaptiveThinking` | `{type:"adaptive"}` + `output_config.effort` | 关;官方新模型在目录里逐条开 |
|
|
608
608
|
| `supportsCacheControlOnTools` | 最后一个工具定义上打断点 | 开 |
|
|
609
609
|
| `maxCacheBreakpoints` | 断点个数上限 | 4 |
|
|
610
|
+
| `messageThreads` | 请求按 message threads 续接,只发新增消息(见下节) | `api.anthropic.com` 开;其它主机(含 Anthropic 兼容的第三方与中转)关 |
|
|
610
611
|
|
|
611
612
|
OpenRouter 的 Messages 接口只在 `message_delta` 里给缓存 usage,解析本就按非空字段合并,不需要开关。
|
|
612
613
|
|
|
@@ -732,7 +733,26 @@ xAI、Mistral、OpenRouter、Google 没有承诺的 TTL,留空:不保温、
|
|
|
732
733
|
- **不算未命中**:压缩、分支摘要、档一裁剪之后的首个请求(上下文合法地变了);前缀低于最小可缓存长度。切换模型**不**豁免。
|
|
733
734
|
- **三态**:按 `(provider, baseUrl 主机名, model)` 在进程内维护。`unknown`:还没有足够长的可比请求;`reported`:出现过 cacheRead 或 cacheWrite > 0;`silent`:连续 3 个可比请求(前缀 ≥ minTokens、指纹未变、间隔 < TTL)读写都是 0,或 `compat.cacheReporting: "silent"`。只有 `reported` 时显示命中率、检测未命中并保温;`unknown` / `silent` 的请求不进命中率分母,界面显示 `—` / `未报告` 而不是 0%。
|
|
734
735
|
|
|
735
|
-
`task` 子会话有自己的记录链与统计,`/session` 的「子任务」行汇总;fork 出的会话沿用根会话 id 作 `prompt_cache_key
|
|
736
|
+
`task` 子会话有自己的记录链与统计,`/session` 的「子任务」行汇总;fork 出的会话沿用根会话 id 作 `prompt_cache_key`(只是路由提示);消息线程另有线程键(`StreamOptions.threadKey`,缺省 `sessionId`),每个会话用自己的 id,fork 与根会话各续各的线程。
|
|
737
|
+
|
|
738
|
+
### 消息线程(message threads)
|
|
739
|
+
|
|
740
|
+
官方端点的缺省行为(beta 头 `message-threads-2026-08-12`):请求带稳定的会话 id 且 `cacheRetention` 不是 `none` 时,服务端保存对话线程,请求只发上一条回复之后的新增消息,不再每轮重发整段历史。`system` 与 `tools` 在续接请求里省略,由线程沿用。token 用量与缓存读写仍按整段对话上报,指纹与未命中检测只看转录,续接不会被误报成未命中。
|
|
741
|
+
|
|
742
|
+
| 项 | 规则 |
|
|
743
|
+
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
744
|
+
| 首条请求 | 整请求,加 `thread: {type:"create"}` 与 beta 头;回复的 message id 记为该会话的续接点 |
|
|
745
|
+
| 续接 | 去掉 `system` / `tools`,`messages` 只留新增部分,`thread: {type:"continue", previous_message_id}`;一条回复只能续接一次 |
|
|
746
|
+
| 回落整请求 | 续接点以内的前文与本次请求不逐项一致(压缩、`/tree` 回退或分支切换、改模型 / system / tools / 思考级别 / `tool_choice` / beta);消息数没有超过续接点;上一回合出错或中止;回复来自别的端点。回落时新开线程 |
|
|
747
|
+
| 服务端拒收 | `thread_not_found`、`thread_already_continued`、`thread_continue_in_flight`、`thread_fingerprint_mismatch` → 整请求新开线程重发一次;`thread_unsupported_request`,或端点对 `thread` 字段 400 且无错误码 → 去掉 `thread` **和线程 beta 头**重发(端点可能连该头的值都拒收),该会话与该端点 + 模型在本进程内之后不再用线程、不再带头,其它会话的首条请求不会再多吃一次 400。前四类重发保留 beta 头。其它错误与线程无关,照常报错 |
|
|
748
|
+
| 不参与 | `StreamOptions.disableContinuation: true` 的请求既不续接也不替换续接点:保温重放与压缩 / 分支摘要请求都置位(它们重复上一条请求的前缀,续接会占掉那条回复唯一的续接点);`onPayload` 换成非对象请求体的请求同理。线程 beta 头照发,保证请求头与真实回合一致、缓存键不变(端点已被关掉线程时,所有请求都不带) |
|
|
749
|
+
| 开关 | `compat.messageThreads: false` 关闭;Anthropic 兼容的第三方与中转缺省关(丢弃未知字段的网关会把续接变成缺前文的请求),确认网关转发 `thread` 字段后可显式写 `true` |
|
|
750
|
+
|
|
751
|
+
续接点只在进程内保存(容量 10 000 个会话,会话结束释放);
|
|
752
|
+
|
|
753
|
+
手工实测(真 key,不进 CI):`pnpm build:lib && ANTHROPIC_API_KEY=… node scripts/verify-anthropic-threads.mjs [模型 id]`,缺省 `claude-haiku-5-5`。脚本用临时 `AMA_DATA_DIR` / `AMA_CONFIG_DIR`,key 只从环境变量读、不打印;连发 3 轮,表格逐轮列出线程动作(create / continue)、请求体消息条数与 input / cacheRead / cacheWrite / output,第 2 轮没有 continue 时退出码为 1。
|
|
754
|
+
|
|
755
|
+
重启、线程在服务端过期(空闲数分钟)后的第一条请求会被拒收并自动整请求重发,多花一次往返。
|
|
736
756
|
|
|
737
757
|
### 保温
|
|
738
758
|
|