@armadra/agent 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/CHANGELOG.md +99 -0
  2. package/README.md +142 -49
  3. package/dist/agent/retry.d.ts +1 -1
  4. package/dist/agent/retry.js +2 -1
  5. package/dist/agent/session-cache.js +6 -3
  6. package/dist/agent/session-classifier.d.ts +18 -0
  7. package/dist/agent/session-classifier.js +103 -0
  8. package/dist/agent/session-core.d.ts +13 -0
  9. package/dist/agent/session-state.js +2 -1
  10. package/dist/agent/session-sync.js +9 -2
  11. package/dist/agent/session-tools.js +24 -3
  12. package/dist/agent/session.d.ts +3 -0
  13. package/dist/agent/session.js +20 -10
  14. package/dist/agent/tool-runner.js +15 -2
  15. package/dist/agent/types.d.ts +9 -1
  16. package/dist/ai/apis/anthropic-messages.js +3 -2
  17. package/dist/ai/apis/google-generative-ai.js +3 -2
  18. package/dist/ai/apis/openai-completions.js +3 -2
  19. package/dist/ai/apis/openai-responses.js +5 -3
  20. package/dist/ai/cache/fingerprint.d.ts +1 -1
  21. package/dist/ai/cache/fingerprint.js +1 -1
  22. package/dist/ai/cache/reporting.js +2 -1
  23. package/dist/ai/http.d.ts +28 -6
  24. package/dist/ai/http.js +41 -8
  25. package/dist/ai/providers/channels.d.ts +51 -0
  26. package/dist/ai/providers/channels.js +96 -0
  27. package/dist/ai/providers/enrich.d.ts +34 -0
  28. package/dist/ai/providers/enrich.js +86 -0
  29. package/dist/ai/providers/models-dev-cache.d.ts +53 -0
  30. package/dist/ai/providers/models-dev-cache.js +147 -0
  31. package/dist/ai/providers/models-dev.d.ts +99 -0
  32. package/dist/ai/providers/models-dev.js +315 -0
  33. package/dist/ai/providers/registry.d.ts +42 -4
  34. package/dist/ai/providers/registry.js +195 -34
  35. package/dist/ai/providers/suggest.d.ts +18 -0
  36. package/dist/ai/providers/suggest.js +72 -0
  37. package/dist/ai/sse.d.ts +6 -2
  38. package/dist/ai/sse.js +22 -2
  39. package/dist/ai/types.d.ts +30 -3
  40. package/dist/bundle/ama.cjs +17893 -10698
  41. package/dist/cli/args.d.ts +23 -5
  42. package/dist/cli/args.js +113 -13
  43. package/dist/cli/bootstrap.js +28 -3
  44. package/dist/cli/codemode-notice.d.ts +20 -0
  45. package/dist/cli/codemode-notice.js +55 -0
  46. package/dist/cli/compose-providers.js +3 -0
  47. package/dist/cli/compose-session.d.ts +8 -0
  48. package/dist/cli/compose-session.js +32 -1
  49. package/dist/cli/compose-store.d.ts +1 -1
  50. package/dist/cli/compose-store.js +3 -1
  51. package/dist/cli/compose.d.ts +17 -5
  52. package/dist/cli/compose.js +53 -19
  53. package/dist/cli/default-model.d.ts +38 -1
  54. package/dist/cli/default-model.js +96 -9
  55. package/dist/cli/deps.d.ts +38 -0
  56. package/dist/cli/exit-codes.d.ts +2 -0
  57. package/dist/cli/exit-codes.js +3 -0
  58. package/dist/cli/fake-visibility.d.ts +13 -0
  59. package/dist/cli/fake-visibility.js +26 -0
  60. package/dist/cli/from-prompt.d.ts +18 -0
  61. package/dist/cli/from-prompt.js +49 -0
  62. package/dist/cli/main.d.ts +10 -2
  63. package/dist/cli/main.js +88 -2
  64. package/dist/cli/proxy.d.ts +51 -0
  65. package/dist/cli/proxy.js +135 -0
  66. package/dist/cli/startup-screen.d.ts +29 -0
  67. package/dist/cli/startup-screen.js +47 -0
  68. package/dist/cli/startup-steps.d.ts +1 -1
  69. package/dist/cli/startup-steps.js +20 -13
  70. package/dist/cli/subcommands/config.d.ts +29 -4
  71. package/dist/cli/subcommands/config.js +188 -25
  72. package/dist/cli/subcommands/context.js +5 -1
  73. package/dist/cli/subcommands/doctor.js +12 -1
  74. package/dist/cli/subcommands/init.d.ts +6 -0
  75. package/dist/cli/subcommands/init.js +23 -0
  76. package/dist/cli/subcommands/model-meta.d.ts +16 -0
  77. package/dist/cli/subcommands/model-meta.js +54 -0
  78. package/dist/cli/subcommands/models-cache-probe.js +1 -1
  79. package/dist/cli/subcommands/models-discover.d.ts +18 -6
  80. package/dist/cli/subcommands/models-discover.js +87 -52
  81. package/dist/cli/subcommands/models.js +26 -18
  82. package/dist/cli/subcommands/probe-runner.d.ts +96 -0
  83. package/dist/cli/subcommands/probe-runner.js +264 -0
  84. package/dist/cli/subcommands/providers-list.d.ts +8 -0
  85. package/dist/cli/subcommands/providers-list.js +97 -0
  86. package/dist/cli/subcommands/providers-plan.d.ts +79 -0
  87. package/dist/cli/subcommands/providers-plan.js +215 -0
  88. package/dist/cli/subcommands/providers-probe.d.ts +34 -0
  89. package/dist/cli/subcommands/providers-probe.js +87 -0
  90. package/dist/cli/subcommands/providers.d.ts +28 -0
  91. package/dist/cli/subcommands/providers.js +436 -0
  92. package/dist/cli/subcommands/sessions-export.d.ts +10 -0
  93. package/dist/cli/subcommands/sessions-export.js +59 -0
  94. package/dist/cli/subcommands/sessions-search.d.ts +13 -0
  95. package/dist/cli/subcommands/sessions-search.js +103 -0
  96. package/dist/cli/subcommands/sessions.d.ts +3 -2
  97. package/dist/cli/subcommands/sessions.js +22 -1
  98. package/dist/cli/subcommands/stats.d.ts +17 -0
  99. package/dist/cli/subcommands/stats.js +198 -0
  100. package/dist/cli/system-prompt-arg.d.ts +11 -0
  101. package/dist/cli/system-prompt-arg.js +34 -0
  102. package/dist/codemode/modes.d.ts +4 -11
  103. package/dist/codemode/modes.js +5 -27
  104. package/dist/codemode/tool.d.ts +18 -14
  105. package/dist/codemode/tool.js +71 -28
  106. package/dist/config/init.d.ts +34 -0
  107. package/dist/config/init.js +99 -0
  108. package/dist/config/json-schema.d.ts +15 -0
  109. package/dist/config/json-schema.js +215 -0
  110. package/dist/config/key-docs.d.ts +22 -0
  111. package/dist/config/key-docs.js +105 -0
  112. package/dist/config/merge.d.ts +9 -8
  113. package/dist/config/merge.js +22 -7
  114. package/dist/config/schema.d.ts +1 -1
  115. package/dist/config/schema.js +97 -15
  116. package/dist/config/types.d.ts +57 -11
  117. package/dist/config/types.js +19 -1
  118. package/dist/modes/commands-core.js +6 -5
  119. package/dist/modes/image-input.d.ts +27 -0
  120. package/dist/modes/image-input.js +78 -0
  121. package/dist/modes/interactive/approval-dialog.d.ts +21 -5
  122. package/dist/modes/interactive/approval-dialog.js +106 -27
  123. package/dist/modes/interactive/commands.d.ts +11 -2
  124. package/dist/modes/interactive/commands.js +58 -19
  125. package/dist/modes/interactive/interactive-mode.d.ts +2 -1
  126. package/dist/modes/interactive/interactive-mode.js +70 -82
  127. package/dist/modes/interactive/key-dispatch.d.ts +3 -1
  128. package/dist/modes/interactive/key-dispatch.js +5 -6
  129. package/dist/modes/interactive/line/line-mode.d.ts +1 -0
  130. package/dist/modes/interactive/line/line-mode.js +9 -5
  131. package/dist/modes/interactive/line/line-render.d.ts +4 -0
  132. package/dist/modes/interactive/line/line-render.js +28 -6
  133. package/dist/modes/interactive/message-view.d.ts +48 -9
  134. package/dist/modes/interactive/message-view.js +238 -44
  135. package/dist/modes/interactive/panels.d.ts +18 -0
  136. package/dist/modes/interactive/panels.js +143 -0
  137. package/dist/modes/interactive/pickers.d.ts +23 -2
  138. package/dist/modes/interactive/pickers.js +48 -15
  139. package/dist/modes/interactive/run-indicator.d.ts +51 -0
  140. package/dist/modes/interactive/run-indicator.js +189 -0
  141. package/dist/modes/interactive/startup-header.d.ts +40 -0
  142. package/dist/modes/interactive/startup-header.js +169 -0
  143. package/dist/modes/interactive/startup-ui.d.ts +7 -2
  144. package/dist/modes/interactive/startup-ui.js +41 -11
  145. package/dist/modes/interactive/status-bar.d.ts +18 -15
  146. package/dist/modes/interactive/status-bar.js +98 -56
  147. package/dist/modes/interactive/tool-summary.d.ts +46 -0
  148. package/dist/modes/interactive/tool-summary.js +218 -0
  149. package/dist/modes/interactive/tool-view.d.ts +48 -15
  150. package/dist/modes/interactive/tool-view.js +203 -145
  151. package/dist/modes/print/print-mode.d.ts +33 -4
  152. package/dist/modes/print/print-mode.js +128 -8
  153. package/dist/modes/rpc/commands.js +12 -2
  154. package/dist/permissions/auto-safe.d.ts +60 -0
  155. package/dist/permissions/auto-safe.js +529 -0
  156. package/dist/permissions/classifier.d.ts +64 -0
  157. package/dist/permissions/classifier.js +184 -0
  158. package/dist/permissions/dangerous.d.ts +5 -0
  159. package/dist/permissions/dangerous.js +1 -1
  160. package/dist/permissions/modes.d.ts +30 -0
  161. package/dist/permissions/modes.js +78 -0
  162. package/dist/permissions/pipeline.d.ts +31 -4
  163. package/dist/permissions/pipeline.js +196 -6
  164. package/dist/permissions/protected.d.ts +19 -0
  165. package/dist/permissions/protected.js +74 -0
  166. package/dist/permissions/rules.js +3 -0
  167. package/dist/permissions/types.d.ts +50 -3
  168. package/dist/permissions/types.js +3 -0
  169. package/dist/rpc.d.ts +2 -0
  170. package/dist/sdk.d.ts +9 -3
  171. package/dist/sdk.js +10 -2
  172. package/dist/session/export.d.ts +32 -0
  173. package/dist/session/export.js +187 -0
  174. package/dist/session/projection.js +5 -1
  175. package/dist/session/redact.d.ts +15 -0
  176. package/dist/session/redact.js +55 -0
  177. package/dist/session/reuse.d.ts +33 -0
  178. package/dist/session/reuse.js +86 -0
  179. package/dist/session/scan.d.ts +34 -0
  180. package/dist/session/scan.js +140 -0
  181. package/dist/session/search.d.ts +52 -0
  182. package/dist/session/search.js +211 -0
  183. package/dist/session/stats-aggregate.d.ts +63 -0
  184. package/dist/session/stats-aggregate.js +163 -0
  185. package/dist/session/stats-index.d.ts +26 -0
  186. package/dist/session/stats-index.js +91 -0
  187. package/dist/session/stats-scan.d.ts +54 -0
  188. package/dist/session/stats-scan.js +236 -0
  189. package/dist/session/types.d.ts +2 -0
  190. package/dist/tools/image-file.d.ts +31 -0
  191. package/dist/tools/image-file.js +114 -0
  192. package/dist/tools/presets.d.ts +35 -8
  193. package/dist/tools/presets.js +56 -17
  194. package/dist/tools/read.d.ts +4 -8
  195. package/dist/tools/read.js +15 -64
  196. package/dist/tui/component.d.ts +8 -2
  197. package/dist/tui/component.js +3 -1
  198. package/dist/tui/components/box.d.ts +6 -1
  199. package/dist/tui/components/box.js +16 -6
  200. package/dist/tui/components/card.d.ts +23 -0
  201. package/dist/tui/components/card.js +37 -0
  202. package/dist/tui/components/editor-history.d.ts +6 -0
  203. package/dist/tui/components/editor-history.js +45 -0
  204. package/dist/tui/components/editor-paste.d.ts +1 -1
  205. package/dist/tui/components/editor-paste.js +4 -4
  206. package/dist/tui/components/editor.d.ts +11 -5
  207. package/dist/tui/components/editor.js +52 -58
  208. package/dist/tui/components/key-value.d.ts +3 -0
  209. package/dist/tui/components/key-value.js +16 -6
  210. package/dist/tui/components/loader.d.ts +37 -7
  211. package/dist/tui/components/loader.js +84 -21
  212. package/dist/tui/components/markdown.d.ts +5 -1
  213. package/dist/tui/components/markdown.js +45 -21
  214. package/dist/tui/components/meter.d.ts +3 -3
  215. package/dist/tui/components/meter.js +13 -11
  216. package/dist/tui/components/select-list.d.ts +23 -1
  217. package/dist/tui/components/select-list.js +76 -13
  218. package/dist/tui/glyphs.d.ts +68 -0
  219. package/dist/tui/glyphs.js +114 -0
  220. package/dist/tui/theme.d.ts +30 -6
  221. package/dist/tui/theme.js +103 -17
  222. package/dist/tui.d.ts +4 -2
  223. package/dist/tui.js +3 -1
  224. package/docs/codemode.md +23 -9
  225. package/docs/hooks.md +10 -10
  226. package/docs/permissions.md +148 -0
  227. package/docs/providers.md +241 -3
  228. package/docs/rpc.md +38 -38
  229. package/docs/session-format.md +3 -2
  230. package/docs/sessions.md +134 -0
  231. package/docs/tui.md +140 -61
  232. package/package.json +3 -1
@@ -3,16 +3,22 @@
3
3
  *
4
4
  * 会话存储是 B2 的实现,经 RuntimeDeps.sessions 注入;这里只做参数、目录解析与输出格式。
5
5
  * - list [--all]:缺省只列当前目录的会话;`--all` 列全部。
6
- * - show <id>:头信息 + 条目类型统计 + 首条提示。
6
+ * - show <id>:头信息 + 条目类型统计 + 首条提示 + 用户消息编号(`--from <id>#<编号>` 复用)。
7
+ * - search / export:见 sessions-search.ts、sessions-export.ts(只读扫描,不经会话存储)。
7
8
  * - prune [--older-than <天>] [--dry-run]:缺省 30 天,移到 trash(不删除)。
8
9
  */
9
10
  import { resolve } from "node:path";
10
11
  import { expandHome, resolveDataDir } from "../../config/paths.js";
11
12
  import { parseSubArgs, UsageError } from "../args.js";
12
13
  import { ExitCode } from "../exit-codes.js";
14
+ import { numberUserMessages } from "../../session/reuse.js";
15
+ import { runSessionsExport } from "./sessions-export.js";
16
+ import { runSessionsSearch } from "./sessions-search.js";
13
17
  export const SESSIONS_USAGE = `用法:ama sessions list [--all] [--session-dir <目录>]
14
18
  ama sessions show <id> [--session-dir <目录>]
15
19
  ama sessions prune [--older-than <天>] [--dry-run] [--all] [--session-dir <目录>]
20
+ ama sessions search <关键词|/正则/> [--all] [--role user|assistant|tool] [--since 7d] [--limit N]
21
+ ama sessions export <id> [--format md|json|jsonl] [--output <文件>] [--branch leaf|all]
16
22
  `;
17
23
  function shortTime(iso) {
18
24
  return iso.replace("T", " ").replace(/\.\d+Z$|Z$/, "");
@@ -24,6 +30,10 @@ function oneLine(text, max = 60) {
24
30
  return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
25
31
  }
26
32
  export async function runSessions(argv, io, deps) {
33
+ if (argv[0] === "search")
34
+ return runSessionsSearch(argv.slice(1), io);
35
+ if (argv[0] === "export")
36
+ return runSessionsExport(argv.slice(1), io);
27
37
  const { positionals, values, flags } = parseSubArgs(argv, ["session-dir", "older-than"], ["all", "dry-run"]);
28
38
  const action = positionals[0];
29
39
  if (flags.has("help") || action === undefined) {
@@ -73,6 +83,17 @@ export async function runSessions(argv, io, deps) {
73
83
  ? [`首条提示:${oneLine(item.firstPrompt, 200)}`]
74
84
  : []),
75
85
  ].join("\n") + "\n");
86
+ const users = numberUserMessages(entries);
87
+ if (users.length > 0) {
88
+ io.stdout(`用户消息(ama --from ${item.id.slice(0, 8)}#<编号> 复用):\n`);
89
+ for (const user of users) {
90
+ const tags = [
91
+ ...(user.origin !== undefined ? [`[${user.origin}]`] : []),
92
+ ...(user.images.length > 0 ? [`[图片 ${user.images.length}]`] : []),
93
+ ];
94
+ io.stdout(` #${String(user.n).padEnd(3)} ${shortTime(user.timestamp)} ${[...tags, oneLine(user.text, 100)].join(" ")}\n`);
95
+ }
96
+ }
76
97
  return ExitCode.Ok;
77
98
  }
78
99
  case "prune": {
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `ama stats`:跨会话的用量统计(只读扫描会话 JSONL)。[W4-D]
3
+ *
4
+ * - 范围:缺省当前目录的会话;`--project <目录>` 指定项目;`--all` 全部(`--by project` 未指定范围时也看全部)。
5
+ * - 时间:`--since` / `--until` 接受 `7d`(含今天的最近 7 天)、`today`、`YYYY-MM-DD`(本地日期,含当天)。
6
+ * - 分组:`--by day|week|month|provider|channel|model|project`。
7
+ * - 缓存:`<数据目录>/stats-index.json`,按文件 mtime / size 失效;`--no-cache` 不读也不写。
8
+ * - 口径见 session/stats-aggregate.ts 与 docs/sessions.md「统计」。
9
+ */
10
+ import { type StatsReport } from "../../session/stats-aggregate.js";
11
+ import type { CliIo } from "../deps.js";
12
+ export declare const STATS_USAGE = "\u7528\u6CD5\uFF1Aama stats [--since 7d|30d|today|YYYY-MM-DD] [--until \u2026]\n [--by day|week|month|provider|channel|model|project]\n [--project <\u76EE\u5F55> | --all] [--top N] [--json] [--no-cache] [--session-dir <\u76EE\u5F55>]\n";
13
+ /** `7d` / `today` / `YYYY-MM-DD` → 本地日期。 */
14
+ export declare function parseDaySpec(option: string, raw: string, now?: Date): string;
15
+ export declare function formatTokens(count: number): string;
16
+ export declare function renderStats(report: StatsReport, scope: string): string;
17
+ export declare function runStats(argv: readonly string[], io: CliIo): Promise<number>;
@@ -0,0 +1,198 @@
1
+ /**
2
+ * `ama stats`:跨会话的用量统计(只读扫描会话 JSONL)。[W4-D]
3
+ *
4
+ * - 范围:缺省当前目录的会话;`--project <目录>` 指定项目;`--all` 全部(`--by project` 未指定范围时也看全部)。
5
+ * - 时间:`--since` / `--until` 接受 `7d`(含今天的最近 7 天)、`today`、`YYYY-MM-DD`(本地日期,含当天)。
6
+ * - 分组:`--by day|week|month|provider|channel|model|project`。
7
+ * - 缓存:`<数据目录>/stats-index.json`,按文件 mtime / size 失效;`--no-cache` 不读也不写。
8
+ * - 口径见 session/stats-aggregate.ts 与 docs/sessions.md「统计」。
9
+ */
10
+ import { join, resolve } from "node:path";
11
+ import { expandHome, resolveDataDir } from "../../config/paths.js";
12
+ import { sessionFilesInScope } from "../../session/scan.js";
13
+ import { STATS_GROUPS, aggregateStats, } from "../../session/stats-aggregate.js";
14
+ import { STATS_INDEX_FILE, collectSummaries } from "../../session/stats-index.js";
15
+ import { localDay } from "../../session/stats-scan.js";
16
+ import { parseSubArgs, UsageError } from "../args.js";
17
+ import { ExitCode } from "../exit-codes.js";
18
+ export const STATS_USAGE = `用法:ama stats [--since 7d|30d|today|YYYY-MM-DD] [--until …]
19
+ [--by day|week|month|provider|channel|model|project]
20
+ [--project <目录> | --all] [--top N] [--json] [--no-cache] [--session-dir <目录>]
21
+ `;
22
+ /** `7d` / `today` / `YYYY-MM-DD` → 本地日期。 */
23
+ export function parseDaySpec(option, raw, now = new Date()) {
24
+ if (raw === "today")
25
+ return localDay(now.toISOString()) ?? "";
26
+ const rel = /^(\d+)d$/.exec(raw);
27
+ if (rel !== null) {
28
+ const days = Number(rel[1]);
29
+ if (days < 1)
30
+ throw new UsageError(`--${option} 的天数至少为 1(收到 ${raw})`);
31
+ const d = new Date(now);
32
+ d.setDate(d.getDate() - (days - 1));
33
+ return localDay(d.toISOString()) ?? "";
34
+ }
35
+ if (/^\d{4}-\d{2}-\d{2}$/.test(raw) && Number.isFinite(Date.parse(`${raw}T00:00:00`)))
36
+ return raw;
37
+ throw new UsageError(`--${option} 应为 7d、today 或 YYYY-MM-DD(收到 ${raw})`);
38
+ }
39
+ export function formatTokens(count) {
40
+ const trim = (text) => text.replace(/\.?0+$/, "");
41
+ if (count < 1000)
42
+ return String(Math.round(count));
43
+ if (count < 100_000)
44
+ return `${trim((count / 1000).toFixed(1))}k`;
45
+ if (count < 1_000_000)
46
+ return `${Math.round(count / 1000)}k`;
47
+ return `${trim((count / 1_000_000).toFixed(2))}M`;
48
+ }
49
+ const percent = (rate) => rate === undefined ? "—" : `${(rate * 100).toFixed(1)}%`;
50
+ const usd = (t) => {
51
+ if (t.cost === undefined)
52
+ return "—";
53
+ return t.cost >= 1 || t.cost === 0 ? `$${t.cost.toFixed(2)}` : `$${t.cost.toFixed(4)}`;
54
+ };
55
+ function seconds(ms) {
56
+ if (ms === undefined)
57
+ return "—";
58
+ return ms < 60_000 ? `${(ms / 1000).toFixed(1)}s` : `${(ms / 60_000).toFixed(1)}m`;
59
+ }
60
+ function width(text) {
61
+ let w = 0;
62
+ for (const ch of text)
63
+ w += (ch.codePointAt(0) ?? 0) > 0x2e7f ? 2 : 1;
64
+ return w;
65
+ }
66
+ function table(rows, rightAlign) {
67
+ const widths = [];
68
+ for (const row of rows)
69
+ row.forEach((cell, i) => (widths[i] = Math.max(widths[i] ?? 0, width(cell))));
70
+ return rows
71
+ .map((row) => row
72
+ .map((cell, i) => {
73
+ const padding = " ".repeat((widths[i] ?? 0) - width(cell));
74
+ return rightAlign(i) ? padding + cell : cell + padding;
75
+ })
76
+ .join(" ")
77
+ .trimEnd())
78
+ .join("\n");
79
+ }
80
+ export function renderStats(report, scope) {
81
+ const t = report.totals;
82
+ const range = report.since === undefined && report.until === undefined
83
+ ? "全部时间"
84
+ : `${report.since ?? "最早"} – ${report.until ?? "今天"}`;
85
+ const lines = [`${range} · ${scope} · ${report.sessions} 个会话`];
86
+ if (t.requests === 0) {
87
+ lines.push("没有模型请求");
88
+ return lines.join("\n") + "\n";
89
+ }
90
+ const kinds = Object.entries(report.byKind)
91
+ .sort((a, b) => b[1] - a[1])
92
+ .map(([kind, n]) => `${kind === "turn" ? "对话" : kind} ${n}`)
93
+ .join(" · ");
94
+ const costLine = t.cost === undefined
95
+ ? "— (所有请求的模型都无价格,见 token)"
96
+ : t.unpriced > 0
97
+ ? `${usd(t)}(另有 ${t.unpriced} 次请求无价,未计入)`
98
+ : usd(t);
99
+ const rows = [
100
+ ["请求", `${t.requests}(${kinds})`],
101
+ ["回合", `${t.turns} · 平均耗时 ${seconds(t.avgTurnMs)}`],
102
+ [
103
+ "Token",
104
+ `输入 ${formatTokens(t.input)} · 输出 ${formatTokens(t.output)} · 缓存读 ${formatTokens(t.cacheRead)} · 缓存写 ${formatTokens(t.cacheWrite)}`,
105
+ ],
106
+ [
107
+ "缓存命中率",
108
+ `${percent(t.hitRate)}(报告缓存的端点 ${report.endpoints.reported}/${report.endpoints.total},其余不进分母)`,
109
+ ],
110
+ ["费用", costLine],
111
+ ["错误 / 重试", `${t.errors} / ${t.retries}`],
112
+ ];
113
+ lines.push(table(rows, () => false));
114
+ if (report.groups !== undefined && report.groups.length > 0) {
115
+ const head = ["", "会话", "请求", "回合", "输入", "输出", "缓存读", "缓存写", "命中率", "费用"];
116
+ const body = report.groups.map((g) => [
117
+ g.key,
118
+ String(g.sessions),
119
+ String(g.requests),
120
+ String(g.turns),
121
+ formatTokens(g.input),
122
+ formatTokens(g.output),
123
+ formatTokens(g.cacheRead),
124
+ formatTokens(g.cacheWrite),
125
+ percent(g.hitRate),
126
+ usd(g) + (g.cost !== undefined && g.unpriced > 0 ? "+" : ""),
127
+ ]);
128
+ lines.push("", table([head, ...body], (i) => i > 0));
129
+ }
130
+ if (report.tools.length > 0) {
131
+ lines.push("", `工具调用 Top ${report.tools.length}`);
132
+ lines.push(table(report.tools.map((tool) => [` ${tool.name}`, String(tool.count)]), (i) => i > 0));
133
+ }
134
+ return lines.join("\n") + "\n";
135
+ }
136
+ export async function runStats(argv, io) {
137
+ const { positionals, values, flags } = parseSubArgs(argv, ["since", "until", "by", "project", "session-dir", "top"], ["all", "json", "no-cache"]);
138
+ if (flags.has("help")) {
139
+ io.stdout(STATS_USAGE);
140
+ return ExitCode.Ok;
141
+ }
142
+ if (positionals.length > 0)
143
+ throw new UsageError(`ama stats 不接受位置参数:${positionals[0]}`);
144
+ const now = new Date();
145
+ const since = values.has("since") ? parseDaySpec("since", values.get("since"), now) : undefined;
146
+ const until = values.has("until") ? parseDaySpec("until", values.get("until"), now) : undefined;
147
+ const byRaw = values.get("by");
148
+ if (byRaw !== undefined && !STATS_GROUPS.includes(byRaw)) {
149
+ throw new UsageError(`--by 的取值应为 ${STATS_GROUPS.join(" | ")}(收到 ${byRaw})`);
150
+ }
151
+ const by = byRaw;
152
+ const top = Number(values.get("top") ?? "10");
153
+ if (!Number.isInteger(top) || top < 0)
154
+ throw new UsageError("--top 应为非负整数");
155
+ if (flags.has("all") && values.has("project")) {
156
+ throw new UsageError("--project 与 --all 不能同时使用");
157
+ }
158
+ const dataDir = resolveDataDir({ env: io.env });
159
+ const dirFlag = values.get("session-dir");
160
+ const root = dirFlag !== undefined
161
+ ? resolve(io.cwd, expandHome(dirFlag, { env: io.env }))
162
+ : join(dataDir, "sessions");
163
+ const projectFlag = values.get("project");
164
+ const project = projectFlag !== undefined
165
+ ? resolve(io.cwd, expandHome(projectFlag, { env: io.env }))
166
+ : flags.has("all") || by === "project"
167
+ ? undefined
168
+ : io.cwd;
169
+ const files = sessionFilesInScope(root, project);
170
+ const useCache = !flags.has("no-cache");
171
+ const collected = collectSummaries(files, {
172
+ ...(useCache ? { indexFile: join(dataDir, STATS_INDEX_FILE) } : {}),
173
+ prune: project === undefined,
174
+ });
175
+ const report = aggregateStats(collected.summaries, {
176
+ ...(since !== undefined ? { since } : {}),
177
+ ...(until !== undefined ? { until } : {}),
178
+ ...(by !== undefined ? { by } : {}),
179
+ topTools: top,
180
+ });
181
+ if (flags.has("json")) {
182
+ io.stdout(JSON.stringify({
183
+ scope: project === undefined ? { all: true } : { project },
184
+ ...report,
185
+ files: {
186
+ total: files.length,
187
+ scanned: collected.scanned,
188
+ cached: collected.cached,
189
+ invalid: collected.invalid,
190
+ },
191
+ }, null, 2) + "\n");
192
+ return ExitCode.Ok;
193
+ }
194
+ io.stdout(renderStats(report, project === undefined ? "全部项目" : `项目 ${project}`));
195
+ if (collected.invalid > 0)
196
+ io.stderr(`ama: 跳过 ${collected.invalid} 个无法读取的会话文件\n`);
197
+ return ExitCode.Ok;
198
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `--system-prompt <文本|@文件>` 与 `--system-prompt-mode append|replace`(W4-C)。
3
+ *
4
+ * - `append`(缺省):作为最后一条规则追加进系统提示的 rules 节——preamble 与工具表在它前面,
5
+ * 缓存前缀里最长的那段不受影响;同一段文本每次都逐字节相同。
6
+ * - `replace`:替换开头的 preamble(「You are ama…」那一段);工具表、规则、AGENTS.md、Skill 索引、
7
+ * cwd 等节照常保留,工具仍然可用。
8
+ * - `@文件`:相对当前目录读取(UTF-8);文件不存在或为空 → 配置错误(退出码 3,同 `--instructions`)。
9
+ */
10
+ import type { SystemPromptOverride } from "./deps.js";
11
+ export declare function resolveSystemPromptArg(value: string | undefined, mode: "append" | "replace" | undefined, cwd: string): SystemPromptOverride | undefined;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * `--system-prompt <文本|@文件>` 与 `--system-prompt-mode append|replace`(W4-C)。
3
+ *
4
+ * - `append`(缺省):作为最后一条规则追加进系统提示的 rules 节——preamble 与工具表在它前面,
5
+ * 缓存前缀里最长的那段不受影响;同一段文本每次都逐字节相同。
6
+ * - `replace`:替换开头的 preamble(「You are ama…」那一段);工具表、规则、AGENTS.md、Skill 索引、
7
+ * cwd 等节照常保留,工具仍然可用。
8
+ * - `@文件`:相对当前目录读取(UTF-8);文件不存在或为空 → 配置错误(退出码 3,同 `--instructions`)。
9
+ */
10
+ import { readFileSync, statSync } from "node:fs";
11
+ import { isAbsolute, resolve } from "node:path";
12
+ import { StartupError } from "../errors.js";
13
+ import { ExitCode } from "./exit-codes.js";
14
+ export function resolveSystemPromptArg(value, mode, cwd) {
15
+ if (value === undefined)
16
+ return undefined;
17
+ let text = value;
18
+ if (value.startsWith("@")) {
19
+ const raw = value.slice(1);
20
+ const path = isAbsolute(raw) ? raw : resolve(cwd, raw);
21
+ try {
22
+ if (!statSync(path).isFile())
23
+ throw new Error("not a file");
24
+ text = readFileSync(path, "utf8");
25
+ }
26
+ catch {
27
+ throw new StartupError("config_invalid", `--system-prompt 文件不存在:${path}`, ExitCode.Config);
28
+ }
29
+ }
30
+ text = text.trim();
31
+ if (text === "")
32
+ throw new StartupError("config_invalid", "--system-prompt 的内容为空", ExitCode.Config);
33
+ return { text, mode: mode ?? "append" };
34
+ }
@@ -4,20 +4,13 @@
4
4
  * | 模式 | 模型看到的工具 |
5
5
  * | ------ | -------------------------------------------------------------------------- |
6
6
  * | `off` | 不注册 codemode(工厂返回 undefined) |
7
- * | `on` | 预设的工具 + codemode;其它工具描述末尾加一行「也可在 codemode 脚本里调用」 |
7
+ * | `on` | 预设的工具 + codemode;codemode 描述一行列出可在脚本里调用的直接工具 |
8
8
  * | `only` | 只有 codemode(宿主 / SDK 工具也不直接暴露);其它工具的声明列在它的描述里 |
9
9
  *
10
- * 活动集由 B6 的 `resolvePreset` 决定(`only` → `["codemode"]`);这里补两件事:`on` 模式下的描述
11
- * 追加(在注册前包一层,描述在会话开始时就确定、字节稳定)与 `only` 模式的独占活动集
12
- * (`PresetToolRegistry.setPresetTools(names, { exclusive: true })`)。
10
+ * 活动集由 B6 的 `resolvePreset` 决定(`only` → `["codemode"]`);这里落 `only` 模式的独占活动集
11
+ * (`PresetToolRegistry.setPresetTools(names, { exclusive: true })`)。`on` 模式不再给其它工具的描述
12
+ * 追加提示:直接工具的描述与 off 模式逐字节相同,codemode 描述里一行列出它们(codemode/tool.ts)。
13
13
  */
14
- import type { CodemodeMode } from "../config/types.js";
15
14
  import { type PresetResolution, type PresetToolRegistry } from "../tools/presets.js";
16
- import type { ToolDefinition } from "../tools/types.js";
17
- export declare function codemodeHint(name: string): string;
18
- /** 复制工具(保留 getter 与方法),描述末尾追加一行 codemode 提示。 */
19
- export declare function withCodemodeHint<I>(tool: ToolDefinition<I>): ToolDefinition<I>;
20
- /** 注册前的包装:`on` 模式给 codemode 以外的工具加提示,其它模式原样返回。 */
21
- export declare function decorateForMode(mode: CodemodeMode): <I>(tool: ToolDefinition<I>) => ToolDefinition<I>;
22
15
  /** 把预设结果落到注册表:`only` 时活动集独占(宿主 / SDK 工具也只能在脚本里调用)。 */
23
16
  export declare function applyCodemodeMode(registry: PresetToolRegistry, resolution: Pick<PresetResolution, "builtin" | "codemode">): void;
@@ -4,36 +4,14 @@
4
4
  * | 模式 | 模型看到的工具 |
5
5
  * | ------ | -------------------------------------------------------------------------- |
6
6
  * | `off` | 不注册 codemode(工厂返回 undefined) |
7
- * | `on` | 预设的工具 + codemode;其它工具描述末尾加一行「也可在 codemode 脚本里调用」 |
7
+ * | `on` | 预设的工具 + codemode;codemode 描述一行列出可在脚本里调用的直接工具 |
8
8
  * | `only` | 只有 codemode(宿主 / SDK 工具也不直接暴露);其它工具的声明列在它的描述里 |
9
9
  *
10
- * 活动集由 B6 的 `resolvePreset` 决定(`only` → `["codemode"]`);这里补两件事:`on` 模式下的描述
11
- * 追加(在注册前包一层,描述在会话开始时就确定、字节稳定)与 `only` 模式的独占活动集
12
- * (`PresetToolRegistry.setPresetTools(names, { exclusive: true })`)。
10
+ * 活动集由 B6 的 `resolvePreset` 决定(`only` → `["codemode"]`);这里落 `only` 模式的独占活动集
11
+ * (`PresetToolRegistry.setPresetTools(names, { exclusive: true })`)。`on` 模式不再给其它工具的描述
12
+ * 追加提示:直接工具的描述与 off 模式逐字节相同,codemode 描述里一行列出它们(codemode/tool.ts)。
13
13
  */
14
- import { CODEMODE_TOOL } from "../tools/presets.js";
15
- export function codemodeHint(name) {
16
- return `Also callable inside codemode scripts as tools.${name}(args).`;
17
- }
18
- /** 复制工具(保留 getter 与方法),描述末尾追加一行 codemode 提示。 */
19
- export function withCodemodeHint(tool) {
20
- const copy = Object.create(Object.getPrototypeOf(tool), {
21
- ...Object.getOwnPropertyDescriptors(tool),
22
- });
23
- Object.defineProperty(copy, "description", {
24
- value: `${tool.description}\n${codemodeHint(tool.name)}`,
25
- enumerable: true,
26
- writable: false,
27
- configurable: true,
28
- });
29
- return copy;
30
- }
31
- /** 注册前的包装:`on` 模式给 codemode 以外的工具加提示,其它模式原样返回。 */
32
- export function decorateForMode(mode) {
33
- if (mode !== "on")
34
- return (tool) => tool;
35
- return (tool) => (tool.name === CODEMODE_TOOL ? tool : withCodemodeHint(tool));
36
- }
14
+ import {} from "../tools/presets.js";
37
15
  /** 把预设结果落到注册表:`only` 时活动集独占(宿主 / SDK 工具也只能在脚本里调用)。 */
38
16
  export function applyCodemodeMode(registry, resolution) {
39
17
  registry.setPresetTools(resolution.builtin, { exclusive: resolution.codemode === "only" });
@@ -12,7 +12,11 @@
12
12
  * - store 只在脚本成功时提交(store.ts);
13
13
  * - 描述(含工具声明)在第一次读取时确定并冻结:同一会话内字节稳定(设计 §9.1),之后注册的宿主
14
14
  * 工具仍可在脚本里调用(`ALL_TOOLS` / `describeTool` 是执行时的清单)。
15
+ * - 描述分两种(`buildCodemodeDescription` 的 `layout`):`only` 模式按预算内联全部工具声明;`on`
16
+ * 模式不重复已直接暴露给模型的工具(它们的 schema 已在工具表里),只用一行列出名字,「仅脚本可
17
+ * 调用」的工具也只列名字(`describeTool(name)` 取签名),把 on 模式的前缀增量压在约 400 token。
15
18
  */
19
+ import type { AmaConfig } from "../config/types.js";
16
20
  import type { ToolDefinition, ToolResult } from "../tools/types.js";
17
21
  import { type SandboxCapability } from "./capability.js";
18
22
  import { type DeclarableTool } from "./declarations.js";
@@ -25,6 +29,8 @@ export interface CallableTool {
25
29
  tool: DeclarableTool;
26
30
  /** 内置工具(非 bash)解析为文本;宿主 / SDK 工具可能返回结构化值。 */
27
31
  textResult: boolean;
32
+ /** 模型也能直接调用(在活动集里);`on` 模式的描述只列名字。 */
33
+ direct?: boolean;
28
34
  }
29
35
  export interface CodemodeToolOptions {
30
36
  /** 脚本里可调用的工具(不含 codemode 本身);描述冻结时与每次执行时各调用一次。 */
@@ -37,6 +43,8 @@ export interface CodemodeToolOptions {
37
43
  maxResultChars?: number;
38
44
  /** `only` 模式:其它工具不直接暴露,系统提示的工具行与规则写明只能在脚本里调用。 */
39
45
  exclusive?: boolean;
46
+ /** 描述的写法:缺省 `only`(按预算内联声明);`on` 只列名字(见 `buildCodemodeDescription`)。 */
47
+ layout?: DescriptionLayout;
40
48
  /** 子进程入口(测试 / 嵌入方覆盖)。 */
41
49
  entry?: string;
42
50
  nodePath?: string;
@@ -68,7 +76,8 @@ export declare const CODEMODE_EXAMPLE: readonly string[];
68
76
  * (实测模型常见的两种错误)。其它错误原样返回。
69
77
  */
70
78
  export declare function scriptErrorHint(error: string, toolNames: readonly string[]): string;
71
- export declare function buildCodemodeDescription(tools: readonly CallableTool[], inlineBudget: number, capability: SandboxCapability): string;
79
+ export type DescriptionLayout = "only" | "on";
80
+ export declare function buildCodemodeDescription(tools: readonly CallableTool[], inlineBudget: number, capability: SandboxCapability, layout?: DescriptionLayout): string;
72
81
  /** 结果文本:状态行 + 输出(超限保留首尾)+ 失败原因。 */
73
82
  export declare function formatCodemodeResult(run: Pick<SandboxRunResult, "ok" | "error" | "outputs" | "elapsedMs" | "droppedChars">, limitChars: number, saveFull: (text: string) => string | undefined): {
74
83
  text: string;
@@ -79,27 +88,22 @@ export declare const CODEMODE_ONLY_GUIDELINE = "read, edit, write, bash and the
79
88
  export declare function createCodemodeTool(options: CodemodeToolOptions): ToolDefinition<CodemodeInput>;
80
89
  /** 组装根用:从 ToolFactoryContext 的形状取所需(避免 codemode → cli 的依赖)。 */
81
90
  export interface CodemodeFactoryContext {
82
- config: {
83
- codemode?: {
84
- mode?: "off" | "on" | "only";
85
- inlineBudget?: number;
86
- requireStrict?: boolean;
87
- };
88
- tools?: {
89
- preset?: string;
90
- maxToolResultChars?: number;
91
- };
92
- };
91
+ config: Pick<AmaConfig, "tools" | "codemode">;
93
92
  registry: {
94
93
  list(): readonly string[];
95
94
  get(name: string): ToolDefinition | undefined;
96
95
  } & {
97
96
  sourceOf?(name: string): string | undefined;
97
+ /** 活动集(coordinator 预设下脚本只能调这些)。 */
98
+ active?(): readonly {
99
+ name: string;
100
+ }[];
98
101
  };
99
102
  warn(message: string): void;
100
103
  }
101
104
  /**
102
- * codemode 工具工厂:`codemode.mode` 生效值为 off → 不注册;`requireStrict` 而运行时不隔离网络
103
- * → 不注册并 warning(预设随之回退到 default)。
105
+ * codemode 工具工厂:生效模式(显式 `codemode.mode`,否则跟随预设,见 tools/presets.ts)为 off →
106
+ * 不注册;`requireStrict` 而运行时不隔离网络 → 不注册并 warning(预设随之回退到 default)。
107
+ * `coordinator` 预设下脚本可调用的工具限于活动集(不含 codemode 本身)。
104
108
  */
105
109
  export declare function codemodeToolFactory(overrides?: Partial<Pick<CodemodeToolOptions, "capability" | "entry" | "nodePath">>): (ctx: CodemodeFactoryContext) => ToolDefinition | undefined;
@@ -12,14 +12,17 @@
12
12
  * - store 只在脚本成功时提交(store.ts);
13
13
  * - 描述(含工具声明)在第一次读取时确定并冻结:同一会话内字节稳定(设计 §9.1),之后注册的宿主
14
14
  * 工具仍可在脚本里调用(`ALL_TOOLS` / `describeTool` 是执行时的清单)。
15
+ * - 描述分两种(`buildCodemodeDescription` 的 `layout`):`only` 模式按预算内联全部工具声明;`on`
16
+ * 模式不重复已直接暴露给模型的工具(它们的 schema 已在工具表里),只用一行列出名字,「仅脚本可
17
+ * 调用」的工具也只列名字(`describeTool(name)` 取签名),把 on 模式的前缀增量压在约 400 token。
15
18
  */
16
19
  import { mkdirSync, writeFileSync } from "node:fs";
17
20
  import { tmpdir } from "node:os";
18
21
  import { join } from "node:path";
22
+ import { codemodeCallableFilter, resolveCodemodeMode } from "../tools/presets.js";
19
23
  import { codemodeAvailability, detectSandboxCapability, } from "./capability.js";
20
- import { DEFAULT_INLINE_BUDGET, buildDeclarationBlock, toolDeclaration, } from "./declarations.js";
24
+ import { BASH_RESULT_DECLARATION, DEFAULT_INLINE_BUDGET, buildDeclarationBlock, toolDeclaration, } from "./declarations.js";
21
25
  import { runSandbox } from "./host-side.js";
22
- import { codemodeHint } from "./modes.js";
23
26
  import { parseOptionsLine } from "./protocol.js";
24
27
  import { commitStore, readStore } from "./store.js";
25
28
  export const CODEMODE_TOOL_NAME = "codemode";
@@ -54,13 +57,6 @@ export function toScriptValue(name, result) {
54
57
  throw new Error(textOf(result.content) || `Tool ${name} failed`);
55
58
  return result.structured !== undefined ? result.structured : textOf(result.content);
56
59
  }
57
- /** on 模式下其它工具描述末尾的提示不进声明。 */
58
- function declarable(tool) {
59
- const suffix = `\n${codemodeHint(tool.name)}`;
60
- if (!tool.description.endsWith(suffix))
61
- return tool;
62
- return { ...tool, description: tool.description.slice(0, -suffix.length) };
63
- }
64
60
  /** 描述里的示例脚本(6 行):并发两个 read、过滤、return。 */
65
61
  export const CODEMODE_EXAMPLE = [
66
62
  "const [a, b] = await Promise.all([",
@@ -86,7 +82,39 @@ export function scriptErrorHint(error, toolNames) {
86
82
  }
87
83
  return error;
88
84
  }
89
- export function buildCodemodeDescription(tools, inlineBudget, capability) {
85
+ /**
86
+ * `on` 模式的描述:规则压成三行 + 示例;已直接暴露的工具只列名字(参数同直接调用),仅脚本可调用的
87
+ * 工具也只列名字。不内联任何声明,字节只依赖工具名与沙箱能力。
88
+ */
89
+ function buildOnDescription(tools, capability) {
90
+ const names = (list) => list
91
+ .map(({ tool }) => tool.name)
92
+ .sort()
93
+ .join(", ");
94
+ const direct = tools.filter((t) => t.direct === true);
95
+ const scriptOnly = tools.filter((t) => t.direct !== true);
96
+ const lines = [
97
+ "Run a JavaScript script that calls tools; only its output comes back to you. Use it to batch many tool calls (Promise.all), filter or summarize large results, or loop, in one step.",
98
+ "Input: raw JavaScript (not JSON, no code fence), the body of an async function (top-level await and return work). Only tools.<name>(args) exists: no require, import, process, fetch or timers.",
99
+ "Example:",
100
+ ...CODEMODE_EXAMPLE,
101
+ "tools.<name>(args) returns a Promise that rejects when the call fails or is denied (Promise.allSettled keeps the rest); text(v) / console.log(...) append output; return v is text(v); store(key, v) / load(key) keep small JSON values across scripts; describeTool(name) returns a signature. At most 8 calls run at once, each through the normal permissions.",
102
+ ];
103
+ if (!capability.strict)
104
+ lines.push(`Sandbox: ${capability.reason}.`);
105
+ if (direct.length > 0) {
106
+ const bash = direct.some(({ tool }) => tool.name === "bash");
107
+ lines.push(`Your direct tools are callable here too, same arguments: ${names(direct)}${bash ? " (tools.bash resolves to BashResult; the others to text)" : ""}.`);
108
+ if (bash)
109
+ lines.push(BASH_RESULT_DECLARATION);
110
+ }
111
+ if (scriptOnly.length > 0)
112
+ lines.push(`Callable only from scripts: ${names(scriptOnly)}.`);
113
+ return lines.join("\n");
114
+ }
115
+ export function buildCodemodeDescription(tools, inlineBudget, capability, layout = "only") {
116
+ if (layout === "on")
117
+ return buildOnDescription(tools, capability);
90
118
  const lines = [
91
119
  "Run a JavaScript script that calls tools; only the script's output comes back to you. Use it to batch many tool calls (Promise.all), filter or summarize large results, or loop, in one step.",
92
120
  "Only tools.<name>(args) is available. There is no require, import, process, fetch or timers; do not call tools directly as functions.",
@@ -98,7 +126,7 @@ export function buildCodemodeDescription(tools, inlineBudget, capability) {
98
126
  if (!capability.strict) {
99
127
  lines.push(`Sandbox: ${capability.reason}.`);
100
128
  }
101
- const block = buildDeclarationBlock(tools.map(({ tool, textResult }) => ({ tool: declarable(tool), textResult })), inlineBudget);
129
+ const block = buildDeclarationBlock(tools.map(({ tool, textResult }) => ({ tool, textResult })), inlineBudget);
102
130
  if (block.text !== "")
103
131
  lines.push(block.text);
104
132
  return lines.join("\n");
@@ -151,7 +179,7 @@ export function createCodemodeTool(options) {
151
179
  name: CODEMODE_TOOL_NAME,
152
180
  label: "Codemode",
153
181
  get description() {
154
- frozenDescription ??= buildCodemodeDescription(options.listTools(), inlineBudget, capability);
182
+ frozenDescription ??= buildCodemodeDescription(options.listTools(), inlineBudget, capability, options.layout);
155
183
  return frozenDescription;
156
184
  },
157
185
  parameters: {
@@ -179,8 +207,10 @@ export function createCodemodeTool(options) {
179
207
  }
180
208
  const tools = options.listTools().map(({ tool: t, textResult }) => ({
181
209
  name: t.name,
182
- declaration: toolDeclaration(declarable(t), textResult ? {} : { textResult: false }),
210
+ declaration: toolDeclaration(t, textResult ? {} : { textResult: false }),
183
211
  }));
212
+ // 只有清单里的工具可调(coordinator 预设的清单只含活动集);脚本拼出别的名字也不放行。
213
+ const callable = new Set(tools.map((t) => t.name));
184
214
  let tail = "";
185
215
  const run = await runSandbox({
186
216
  script: input.script,
@@ -190,7 +220,11 @@ export function createCodemodeTool(options) {
190
220
  signal: ctx.signal,
191
221
  ...(options.entry !== undefined ? { entry: options.entry } : {}),
192
222
  ...(options.nodePath !== undefined ? { nodePath: options.nodePath } : {}),
193
- callTool: async (name, args, signal) => toScriptValue(name, await ctx.tools.executeTool(name, args, { signal })),
223
+ callTool: async (name, args, signal) => {
224
+ if (!callable.has(name))
225
+ throw new Error(`Tool ${name} is not available in codemode`);
226
+ return toScriptValue(name, await ctx.tools.executeTool(name, args, { signal }));
227
+ },
194
228
  onOutput: (text) => {
195
229
  tail = `${tail}${tail === "" ? "" : "\n"}${text}`.slice(-TAIL_CHARS);
196
230
  ctx.onUpdate(tail);
@@ -240,33 +274,42 @@ export function createCodemodeTool(options) {
240
274
  return tool;
241
275
  }
242
276
  /**
243
- * codemode 工具工厂:`codemode.mode` 生效值为 off → 不注册;`requireStrict` 而运行时不隔离网络
244
- * → 不注册并 warning(预设随之回退到 default)。
277
+ * codemode 工具工厂:生效模式(显式 `codemode.mode`,否则跟随预设,见 tools/presets.ts)为 off →
278
+ * 不注册;`requireStrict` 而运行时不隔离网络 → 不注册并 warning(预设随之回退到 default)。
279
+ * `coordinator` 预设下脚本可调用的工具限于活动集(不含 codemode 本身)。
245
280
  */
246
281
  export function codemodeToolFactory(overrides = {}) {
247
282
  return (ctx) => {
248
- const explicit = ctx.config.codemode?.mode;
249
- const mode = explicit ?? (ctx.config.tools?.preset === "codemode" ? "only" : "off");
283
+ const capability = overrides.capability ?? detectSandboxCapability();
284
+ const mode = resolveCodemodeMode(ctx.config, capability.strict).mode;
250
285
  if (mode === "off")
251
286
  return undefined;
252
- const availability = codemodeAvailability(ctx.config.codemode?.requireStrict, overrides.capability ?? detectSandboxCapability());
287
+ const availability = codemodeAvailability(ctx.config.codemode?.requireStrict, capability);
253
288
  if (!availability.available) {
254
289
  ctx.warn(availability.warning);
255
290
  return undefined;
256
291
  }
257
292
  const registry = ctx.registry;
293
+ const onlyActive = codemodeCallableFilter(ctx.config) === "active";
294
+ const allowed = (name) => !onlyActive || (registry.active?.() ?? []).some((tool) => tool.name === name);
295
+ const direct = () => new Set(mode === "on" ? (registry.active?.() ?? []).map((tool) => tool.name) : []);
258
296
  const options = {
259
297
  capability: availability.capability,
260
298
  exclusive: mode === "only",
261
- listTools: () => registry
262
- .list()
263
- .filter((name) => name !== CODEMODE_TOOL_NAME)
264
- .map((name) => registry.get(name))
265
- .filter((t) => t !== undefined)
266
- .map((t) => ({
267
- tool: t,
268
- textResult: (registry.sourceOf?.(t.name) ?? "builtin") === "builtin",
269
- })),
299
+ layout: mode === "on" ? "on" : "only",
300
+ listTools: () => {
301
+ const active = direct();
302
+ return registry
303
+ .list()
304
+ .filter((name) => name !== CODEMODE_TOOL_NAME && allowed(name))
305
+ .map((name) => registry.get(name))
306
+ .filter((t) => t !== undefined)
307
+ .map((t) => ({
308
+ tool: t,
309
+ textResult: (registry.sourceOf?.(t.name) ?? "builtin") === "builtin",
310
+ ...(active.has(t.name) ? { direct: true } : {}),
311
+ }));
312
+ },
270
313
  };
271
314
  const budget = ctx.config.codemode?.inlineBudget;
272
315
  if (budget !== undefined)