@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.
Files changed (157) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/CHANGELOG.zh-CN.md +50 -0
  3. package/README.md +4 -0
  4. package/README.zh-CN.md +4 -0
  5. package/THIRD_PARTY_NOTICES.md +6 -0
  6. package/assets/quickjs/LICENSE +57 -0
  7. package/assets/quickjs/README.md +14 -0
  8. package/assets/quickjs/quickjs.wasm +0 -0
  9. package/dist/agent/recovery-reminder.js +6 -1
  10. package/dist/agent/schema-coerce.d.ts +24 -0
  11. package/dist/agent/schema-coerce.js +157 -0
  12. package/dist/agent/schema.d.ts +1 -1
  13. package/dist/agent/schema.js +1 -1
  14. package/dist/agent/session-cache.js +12 -0
  15. package/dist/agent/tool-runner.js +57 -28
  16. package/dist/agent/types.d.ts +4 -0
  17. package/dist/ai/apis/anthropic-compat.d.ts +3 -1
  18. package/dist/ai/apis/anthropic-compat.js +8 -1
  19. package/dist/ai/apis/anthropic-messages.js +54 -2
  20. package/dist/ai/apis/anthropic-request.d.ts +3 -0
  21. package/dist/ai/apis/anthropic-request.js +7 -1
  22. package/dist/ai/apis/anthropic-threads.d.ts +64 -0
  23. package/dist/ai/apis/anthropic-threads.js +192 -0
  24. package/dist/ai/providers/catalog-data.js +5 -5
  25. package/dist/ai/providers/models-dev-data.js +22 -22
  26. package/dist/ai/types.d.ts +16 -0
  27. package/dist/bundle/ama-sandbox.cjs +96 -2
  28. package/dist/bundle/ama.cjs +29964 -27673
  29. package/dist/cli/bootstrap.js +32 -6
  30. package/dist/cli/compose-agents.js +2 -1
  31. package/dist/cli/compose-extensions-load.d.ts +20 -0
  32. package/dist/cli/compose-extensions-load.js +38 -0
  33. package/dist/cli/compose.js +1 -0
  34. package/dist/cli/deps.d.ts +11 -0
  35. package/dist/cli/runtime.d.ts +7 -0
  36. package/dist/cli/subcommands/config.d.ts +3 -0
  37. package/dist/cli/subcommands/config.js +22 -7
  38. package/dist/cli/subcommands/doctor.js +34 -0
  39. package/dist/cli/subcommands/models-discover.js +6 -2
  40. package/dist/codemode/capability.d.ts +14 -2
  41. package/dist/codemode/capability.js +19 -2
  42. package/dist/codemode/host-side.d.ts +14 -0
  43. package/dist/codemode/host-side.js +81 -10
  44. package/dist/codemode/inner-calls.d.ts +19 -0
  45. package/dist/codemode/inner-calls.js +24 -0
  46. package/dist/codemode/protocol.d.ts +14 -0
  47. package/dist/codemode/protocol.js +9 -1
  48. package/dist/codemode/quickjs/host.d.ts +15 -0
  49. package/dist/codemode/quickjs/host.js +243 -0
  50. package/dist/codemode/quickjs/wasm.d.ts +21 -0
  51. package/dist/codemode/quickjs/wasm.js +39 -0
  52. package/dist/codemode/quickjs/worker.d.ts +55 -0
  53. package/dist/codemode/quickjs/worker.js +457 -0
  54. package/dist/codemode/sandbox-entry.d.ts +4 -0
  55. package/dist/codemode/sandbox-entry.js +95 -3
  56. package/dist/codemode/script-images.d.ts +18 -0
  57. package/dist/codemode/script-images.js +38 -0
  58. package/dist/codemode/script-output.d.ts +19 -0
  59. package/dist/codemode/script-output.js +67 -0
  60. package/dist/codemode/search-tools.d.ts +27 -0
  61. package/dist/codemode/search-tools.js +83 -0
  62. package/dist/codemode/tool.d.ts +4 -0
  63. package/dist/codemode/tool.js +60 -9
  64. package/dist/codemode/worker-pool.d.ts +65 -0
  65. package/dist/codemode/worker-pool.js +131 -0
  66. package/dist/config/extension-tree-hash.d.ts +31 -0
  67. package/dist/config/extension-tree-hash.js +88 -0
  68. package/dist/config/extension-trust.d.ts +70 -0
  69. package/dist/config/extension-trust.js +112 -0
  70. package/dist/config/json-schema.js +3 -1
  71. package/dist/config/key-docs.js +7 -1
  72. package/dist/config/profile.d.ts +2 -0
  73. package/dist/config/profile.js +1 -0
  74. package/dist/config/schema-trust.d.ts +7 -0
  75. package/dist/config/schema-trust.js +46 -0
  76. package/dist/config/schema.d.ts +4 -5
  77. package/dist/config/schema.js +7 -27
  78. package/dist/config/settings-registry.js +2 -0
  79. package/dist/config/trust.d.ts +2 -0
  80. package/dist/config/trust.js +5 -1
  81. package/dist/config/types.d.ts +23 -0
  82. package/dist/config/types.js +1 -0
  83. package/dist/drivers/host-runners.d.ts +15 -4
  84. package/dist/drivers/host-runners.js +31 -17
  85. package/dist/errors.d.ts +1 -1
  86. package/dist/host/api-impl.d.ts +47 -4
  87. package/dist/host/api-impl.js +181 -20
  88. package/dist/host/commands.d.ts +23 -0
  89. package/dist/host/commands.js +76 -0
  90. package/dist/host/extensions.d.ts +43 -0
  91. package/dist/host/extensions.js +117 -0
  92. package/dist/host/resources.d.ts +2 -0
  93. package/dist/host/resources.js +5 -0
  94. package/dist/host/types.d.ts +41 -2
  95. package/dist/host/types.js +4 -2
  96. package/dist/i18n/catalog.d.ts +39 -0
  97. package/dist/i18n/messages/cli.d.ts +24 -0
  98. package/dist/i18n/messages/cli.js +24 -0
  99. package/dist/i18n/messages/config-keys.d.ts +4 -0
  100. package/dist/i18n/messages/config-keys.js +6 -2
  101. package/dist/i18n/messages/config.d.ts +4 -0
  102. package/dist/i18n/messages/drivers.d.ts +22 -0
  103. package/dist/i18n/messages/drivers.js +22 -0
  104. package/dist/i18n/messages/errors.d.ts +1 -1
  105. package/dist/i18n/messages/interactive-startup.d.ts +4 -0
  106. package/dist/i18n/messages/interactive-startup.js +4 -0
  107. package/dist/i18n/messages/interactive-view.d.ts +2 -0
  108. package/dist/i18n/messages/interactive-view.js +2 -0
  109. package/dist/i18n/messages/interactive.d.ts +6 -0
  110. package/dist/i18n/messages/report.d.ts +14 -0
  111. package/dist/i18n/messages/report.js +14 -0
  112. package/dist/i18n/messages/subcommands-config.d.ts +8 -0
  113. package/dist/i18n/messages/subcommands-config.js +8 -0
  114. package/dist/i18n/messages/subcommands.d.ts +8 -0
  115. package/dist/modes/acp/acp-config.d.ts +4 -2
  116. package/dist/modes/acp/acp-config.js +17 -3
  117. package/dist/modes/acp/acp-events.d.ts +2 -0
  118. package/dist/modes/acp/acp-events.js +4 -0
  119. package/dist/modes/acp/acp-server.js +6 -2
  120. package/dist/modes/acp/acp-sessions.d.ts +8 -1
  121. package/dist/modes/acp/acp-sessions.js +18 -0
  122. package/dist/modes/commands-core.d.ts +14 -1
  123. package/dist/modes/commands-core.js +34 -2
  124. package/dist/modes/interactive/startup-ui.js +21 -0
  125. package/dist/modes/interactive/status-area.js +1 -1
  126. package/dist/modes/interactive/tool-view.d.ts +8 -2
  127. package/dist/modes/interactive/tool-view.js +12 -5
  128. package/dist/modes/print/print-mode.d.ts +3 -0
  129. package/dist/modes/print/print-mode.js +35 -8
  130. package/dist/modes/rpc/commands.d.ts +2 -0
  131. package/dist/modes/rpc/commands.js +22 -7
  132. package/dist/modes/rpc/rpc-mode.js +3 -0
  133. package/dist/modes/startup-ui-text.js +11 -0
  134. package/dist/rpc.d.ts +2 -1
  135. package/dist/session/unclean-end.d.ts +8 -0
  136. package/dist/session/unclean-end.js +39 -7
  137. package/dist/tools/registry.d.ts +6 -0
  138. package/dist/tools/registry.js +13 -0
  139. package/dist/tools/types.d.ts +7 -0
  140. package/docs/README.md +1 -1
  141. package/docs/en/README.md +3 -3
  142. package/docs/en/guides/extensions.md +141 -0
  143. package/docs/en/guides/providers.md +27 -7
  144. package/docs/en/guides/tui.md +1 -1
  145. package/docs/en/reference/acp.md +1 -1
  146. package/docs/en/reference/host-api.md +55 -27
  147. package/docs/en/reference/rpc.md +12 -8
  148. package/docs/guides/codemode.md +52 -12
  149. package/docs/guides/extensions.md +136 -0
  150. package/docs/guides/providers.md +21 -1
  151. package/docs/guides/sandbox.md +2 -0
  152. package/docs/guides/tui.md +1 -1
  153. package/docs/reference/acp.md +1 -1
  154. package/docs/reference/host-api.md +55 -27
  155. package/docs/reference/rpc.md +12 -8
  156. package/docs/reference/session-format.md +10 -9
  157. package/package.json +5 -2
@@ -0,0 +1,88 @@
1
+ /**
2
+ * 目录扩展的整棵树哈希(#305):信任以目录为单位,目录里任一文件变化都会让哈希变。
3
+ *
4
+ * 格式(v2,与平台、遍历与创建顺序无关):对 sha256 依次写入
5
+ * `armadra-ext-tree-v2\n`,然后按「正斜杠相对路径」的 UTF-8 字节序排序的每一个文件:
6
+ * `F <相对路径的字节数> <相对路径> <内容字节数>\n` + 内容字节
7
+ * 路径与内容都带长度前缀,所以不同的树不会拼出同一字节流。
8
+ *
9
+ * 不跳过任何项(包括 `.git`):被跳过的文件照样可以被 `import`,就成了绕过信任的口子。符号链接一律跟随,
10
+ * 按目标的内容计入(指向树外的也一样),目录链接递归进去;成环的链接、断开的链接按读不了处理。
11
+ * socket、fifo 等其它类型忽略(不能被 import)。文件数、目录数、总字节与深度都有上限,超出抛
12
+ * {@link TreeLimitError};上限在读内容之前用 stat 检查。
13
+ */
14
+ import { createHash } from "node:crypto";
15
+ import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ export const MAX_TREE_FILES = 2000;
18
+ export const MAX_TREE_BYTES = 50 * 1024 * 1024;
19
+ export const MAX_TREE_DIRS = 2000;
20
+ export const MAX_TREE_DEPTH = 32;
21
+ export const DEFAULT_TREE_LIMITS = {
22
+ maxFiles: MAX_TREE_FILES,
23
+ maxBytes: MAX_TREE_BYTES,
24
+ };
25
+ /** 文件数或总字节数超过上限(与「读不了」区分开)。 */
26
+ export class TreeLimitError extends Error {
27
+ }
28
+ class TreeCycleError extends Error {
29
+ }
30
+ function collect(root, limits) {
31
+ const maxDirs = limits.maxDirs ?? MAX_TREE_DIRS;
32
+ const maxDepth = limits.maxDepth ?? MAX_TREE_DEPTH;
33
+ const items = [];
34
+ let bytes = 0;
35
+ let dirs = 0;
36
+ // 当前递归路径上的目录真实路径:链接指回祖先即成环
37
+ const ancestors = new Set();
38
+ const walk = (abs, rel, depth) => {
39
+ if (depth > maxDepth)
40
+ throw new TreeLimitError(`deeper than ${maxDepth} levels`);
41
+ if (++dirs > maxDirs)
42
+ throw new TreeLimitError(`more than ${maxDirs} directories`);
43
+ const real = realpathSync(abs);
44
+ if (ancestors.has(real))
45
+ throw new TreeCycleError(`symlink cycle at ${abs}`);
46
+ ancestors.add(real);
47
+ for (const entry of readdirSync(abs, { withFileTypes: true })) {
48
+ const childAbs = join(abs, entry.name);
49
+ const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;
50
+ // 跟随符号链接(断开的链接在这里抛错 → 读不了)
51
+ const stat = entry.isSymbolicLink() ? statSync(childAbs) : undefined;
52
+ const isDir = stat !== undefined ? stat.isDirectory() : entry.isDirectory();
53
+ const isFile = stat !== undefined ? stat.isFile() : entry.isFile();
54
+ if (isDir) {
55
+ walk(childAbs, childRel, depth + 1);
56
+ continue;
57
+ }
58
+ if (!isFile)
59
+ continue;
60
+ if (items.length + 1 > limits.maxFiles) {
61
+ throw new TreeLimitError(`more than ${limits.maxFiles} files`);
62
+ }
63
+ bytes += (stat ?? statSync(childAbs)).size;
64
+ if (bytes > limits.maxBytes)
65
+ throw new TreeLimitError(`more than ${limits.maxBytes} bytes`);
66
+ items.push({ rel: childRel, abs: childAbs });
67
+ }
68
+ ancestors.delete(real);
69
+ };
70
+ walk(root, "", 0);
71
+ return items;
72
+ }
73
+ /** 目录树的 sha256(十六进制)。读不了(含断开或成环的链接)抛错,超限抛 {@link TreeLimitError}。 */
74
+ export function sha256OfTree(root, limits = DEFAULT_TREE_LIMITS) {
75
+ const items = collect(root, limits);
76
+ const keyed = items.map((item) => ({ item, key: Buffer.from(item.rel, "utf8") }));
77
+ keyed.sort((a, b) => Buffer.compare(a.key, b.key));
78
+ const hash = createHash("sha256");
79
+ hash.update("armadra-ext-tree-v2\n");
80
+ for (const { item, key } of keyed) {
81
+ const content = readFileSync(item.abs);
82
+ hash.update(`F ${key.length} `);
83
+ hash.update(key);
84
+ hash.update(` ${content.length}\n`);
85
+ hash.update(content);
86
+ }
87
+ return hash.digest("hex");
88
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * 本地扩展的信任(#301、#305,docs/guides/extensions.md):按文件内容(目录扩展为整棵树)sha256 记在 trust.json 的 `extensions` 段。
3
+ *
4
+ * - `--no-trust`:全部不加载;`--trust` 与 profile `trustProject` 都不影响扩展。
5
+ * - 记录的路径与哈希都相同 → 用记录的决定;没有记录或内容变了 → 交互模式一次性列出全部待定文件
6
+ * (路径 + sha256)询问,非交互直接跳过。
7
+ * - 本模块只读文件、算哈希,不执行扩展代码(`ama doctor` 也用它)。
8
+ */
9
+ import { type TreeLimits } from "./extension-tree-hash.js";
10
+ import { type TrustPromptAnswer } from "./trust.js";
11
+ import type { ExtensionTrustEntry } from "./types.js";
12
+ export type ExtensionTrustStatus =
13
+ /** 记录匹配且已信任。 */
14
+ "trusted"
15
+ /** 记录匹配且被拒绝。 */
16
+ | "declined"
17
+ /** 有该路径的记录,但内容已变(哈希不符)。 */
18
+ | "changed"
19
+ /** 没有记录。 */
20
+ | "unknown"
21
+ /** 文件读不了。 */
22
+ | "unreadable"
23
+ /** 目录扩展的文件数或总字节数超过上限(#305)。 */
24
+ | "too-large";
25
+ export interface ExtensionFileInfo {
26
+ path: string;
27
+ /** 读不了文件时缺省。 */
28
+ sha256?: string;
29
+ /** 目录扩展(哈希覆盖整棵树,#305)。 */
30
+ directory?: boolean;
31
+ status: ExtensionTrustStatus;
32
+ }
33
+ export declare function sha256OfFile(path: string): string;
34
+ /** 一个文件当前的信任状态(只读,不询问)。 */
35
+ export declare function inspectExtension(path: string, recorded: readonly ExtensionTrustEntry[], limits?: TreeLimits): ExtensionFileInfo;
36
+ /** 记录决定(同路径的旧记录被替换)。 */
37
+ export declare function recordExtensionTrust(configDir: string, files: readonly {
38
+ path: string;
39
+ sha256: string;
40
+ }[], trusted: boolean, now?: Date): void;
41
+ export type ExtensionSkipReason = "no-trust" | "untrusted" | "changed" | "declined" | "unreadable" | "too-large";
42
+ export interface ExtensionSkipped {
43
+ path: string;
44
+ sha256?: string;
45
+ directory?: boolean;
46
+ reason: ExtensionSkipReason;
47
+ }
48
+ /** 询问时列出的一项;`directory` 标出目录扩展。 */
49
+ export interface ExtensionPromptFile {
50
+ path: string;
51
+ sha256: string;
52
+ directory?: boolean;
53
+ }
54
+ export interface DecideExtensionsInput {
55
+ paths: readonly string[];
56
+ configDir: string;
57
+ /** `--no-trust`。 */
58
+ disabled: boolean;
59
+ interactive: boolean;
60
+ /** 交互询问(一次,列出全部待定文件);不提供按非交互处理。 */
61
+ prompt?: ((files: readonly ExtensionPromptFile[]) => Promise<TrustPromptAnswer>) | undefined;
62
+ /** 目录扩展的树上限(测试可注入小值)。 */
63
+ limits?: TreeLimits | undefined;
64
+ }
65
+ export interface ExtensionDecision {
66
+ /** 按输入顺序的、可以加载的文件。 */
67
+ load: string[];
68
+ skipped: ExtensionSkipped[];
69
+ }
70
+ export declare function decideExtensions(input: DecideExtensionsInput): Promise<ExtensionDecision>;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * 本地扩展的信任(#301、#305,docs/guides/extensions.md):按文件内容(目录扩展为整棵树)sha256 记在 trust.json 的 `extensions` 段。
3
+ *
4
+ * - `--no-trust`:全部不加载;`--trust` 与 profile `trustProject` 都不影响扩展。
5
+ * - 记录的路径与哈希都相同 → 用记录的决定;没有记录或内容变了 → 交互模式一次性列出全部待定文件
6
+ * (路径 + sha256)询问,非交互直接跳过。
7
+ * - 本模块只读文件、算哈希,不执行扩展代码(`ama doctor` 也用它)。
8
+ */
9
+ import { createHash } from "node:crypto";
10
+ import { readFileSync, statSync } from "node:fs";
11
+ import { resolve } from "node:path";
12
+ import { DEFAULT_TREE_LIMITS, sha256OfTree, TreeLimitError, } from "./extension-tree-hash.js";
13
+ import { readTrustFile, writeTrustFile } from "./trust.js";
14
+ function isDirectory(path) {
15
+ try {
16
+ return statSync(path).isDirectory();
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ export function sha256OfFile(path) {
23
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
24
+ }
25
+ /** 一个文件当前的信任状态(只读,不询问)。 */
26
+ export function inspectExtension(path, recorded, limits = DEFAULT_TREE_LIMITS) {
27
+ const abs = resolve(path);
28
+ const directory = isDirectory(abs);
29
+ const kind = directory ? { directory: true } : {};
30
+ let sha256;
31
+ try {
32
+ sha256 = directory ? sha256OfTree(abs, limits) : sha256OfFile(abs);
33
+ }
34
+ catch (error) {
35
+ return {
36
+ path: abs,
37
+ ...kind,
38
+ status: error instanceof TreeLimitError ? "too-large" : "unreadable",
39
+ };
40
+ }
41
+ const own = recorded.filter((e) => resolve(e.path) === abs);
42
+ const match = own.find((e) => e.sha256 === sha256);
43
+ if (match !== undefined) {
44
+ return { path: abs, sha256, ...kind, status: match.trusted ? "trusted" : "declined" };
45
+ }
46
+ return { path: abs, sha256, ...kind, status: own.length > 0 ? "changed" : "unknown" };
47
+ }
48
+ /** 记录决定(同路径的旧记录被替换)。 */
49
+ export function recordExtensionTrust(configDir, files, trusted, now = new Date()) {
50
+ const file = readTrustFile(configDir);
51
+ const paths = new Set(files.map((f) => resolve(f.path)));
52
+ const extensions = (file.extensions ?? []).filter((e) => !paths.has(resolve(e.path)));
53
+ for (const f of files) {
54
+ extensions.push({
55
+ path: resolve(f.path),
56
+ sha256: f.sha256,
57
+ trusted,
58
+ at: now.toISOString(),
59
+ });
60
+ }
61
+ writeTrustFile(configDir, { ...file, extensions });
62
+ }
63
+ export async function decideExtensions(input) {
64
+ if (input.paths.length === 0)
65
+ return { load: [], skipped: [] };
66
+ if (input.disabled) {
67
+ return {
68
+ load: [],
69
+ skipped: input.paths.map((path) => ({ path, reason: "no-trust" })),
70
+ };
71
+ }
72
+ const recorded = readTrustFile(input.configDir).extensions ?? [];
73
+ const infos = input.paths.map((path) => inspectExtension(path, recorded, input.limits));
74
+ const pending = infos.filter((i) => i.status === "unknown" || i.status === "changed");
75
+ let answer;
76
+ if (pending.length > 0 && input.interactive && input.prompt !== undefined) {
77
+ const files = pending.map((i) => ({
78
+ path: i.path,
79
+ sha256: i.sha256,
80
+ ...(i.directory === true ? { directory: true } : {}),
81
+ }));
82
+ answer = await input.prompt(files);
83
+ if (answer.remember)
84
+ recordExtensionTrust(input.configDir, files, answer.trusted);
85
+ }
86
+ const load = [];
87
+ const skipped = [];
88
+ for (const [index, info] of infos.entries()) {
89
+ const original = input.paths[index];
90
+ const base = {
91
+ path: original,
92
+ ...(info.sha256 !== undefined ? { sha256: info.sha256 } : {}),
93
+ ...(info.directory === true ? { directory: true } : {}),
94
+ };
95
+ if (info.status === "trusted")
96
+ load.push(original);
97
+ else if (info.status === "unreadable" || info.status === "too-large") {
98
+ skipped.push({ ...base, reason: info.status });
99
+ }
100
+ else if (info.status === "declined")
101
+ skipped.push({ ...base, reason: "declined" });
102
+ else if (answer !== undefined) {
103
+ if (answer.trusted)
104
+ load.push(original);
105
+ else
106
+ skipped.push({ ...base, reason: "declined" });
107
+ }
108
+ else
109
+ skipped.push({ ...base, reason: info.status === "changed" ? "changed" : "untrusted" });
110
+ }
111
+ return { load, skipped };
112
+ }
@@ -12,7 +12,7 @@ import { msg } from "../i18n/index.js";
12
12
  import { MAX_TIMER_MS } from "../tools/timers.js";
13
13
  import { defaultFor, isDynamicDefault, keyDoc } from "./key-docs.js";
14
14
  import { HOOK_TIMEOUT_MAX_MS, THINKING_LEVELS } from "./schema.js";
15
- import { CACHE_RETENTIONS, CHANNEL_NAME_PATTERN, CHECKPOINT_MODES, SANDBOX_ENABLED_MODES, SANDBOX_NETWORK_MODES, CODEMODE_MODES, IMAGE_RESIZE_MODES, PLAN_BASH_MODES_STRICT_FIRST, PLAN_UNATTENDED_MODES, STATUS_LINE_MODES, TOOLS_PRESET_INPUTS, LANGUAGE_SETTINGS, AGENT_BAR_MODES, CHATGPT_FLAVORS, MEMORY_SCOPES, MEMORY_SUBAGENT_MODES, MIN_CONTEXT_BUDGET, } from "./types.js";
15
+ import { CACHE_RETENTIONS, CHANNEL_NAME_PATTERN, CHECKPOINT_MODES, SANDBOX_ENABLED_MODES, SANDBOX_NETWORK_MODES, CODEMODE_ENGINES, CODEMODE_MODES, IMAGE_RESIZE_MODES, PLAN_BASH_MODES_STRICT_FIRST, PLAN_UNATTENDED_MODES, STATUS_LINE_MODES, TOOLS_PRESET_INPUTS, LANGUAGE_SETTINGS, AGENT_BAR_MODES, CHATGPT_FLAVORS, MEMORY_SCOPES, MEMORY_SUBAGENT_MODES, MIN_CONTEXT_BUDGET, } from "./types.js";
16
16
  import { AGENT_ID_PATTERN } from "./schema-w5.js";
17
17
  import { AGENTS_RESERVED_KEYS, SUBAGENT_BACKGROUND_MODES } from "./types-w5.js";
18
18
  export const CONFIG_SCHEMA_FILE = "config.schema.json";
@@ -279,6 +279,8 @@ function buildBaseSchema() {
279
279
  inlineBudget: num(0),
280
280
  requireStrict: bool(),
281
281
  maxHeapMb: num(0),
282
+ maxWorkers: num(1),
283
+ engine: oneOf(CODEMODE_ENGINES),
282
284
  }),
283
285
  hooks: object({ timeoutMs: num(1, HOOK_TIMEOUT_MAX_MS) }),
284
286
  ui: object({
@@ -21,7 +21,13 @@ const IMPLICIT_DEFAULTS = {
21
21
  permission: { builtinDeny: true, autoSafeCommands: [] },
22
22
  // [#267] 寿命上限;[#266] bashAutoBackgroundAfterMs 的缺省由运行方式决定(dynamicDefaults)
23
23
  tools: { default: [], bashBackgroundMaxMs: 7_200_000 },
24
- codemode: { inlineBudget: DEFAULT_INLINE_BUDGET, requireStrict: false, maxHeapMb: 256 },
24
+ codemode: {
25
+ inlineBudget: DEFAULT_INLINE_BUDGET,
26
+ requireStrict: false,
27
+ maxHeapMb: 256,
28
+ maxWorkers: 2,
29
+ engine: "auto",
30
+ },
25
31
  cache: { ...DEFAULT_CACHE_CONFIG },
26
32
  request: {
27
33
  idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,
@@ -14,6 +14,8 @@ export interface ProfileOptions {
14
14
  promptDirs: string[];
15
15
  /** [W5-C0] 子 Agent 定义目录(W5-G 接入发现)。 */
16
16
  agentDirs?: string[];
17
+ /** [#301] 本地扩展文件(绝对路径)。 */
18
+ extensions?: string[];
17
19
  hooksFile?: string;
18
20
  authFile?: string;
19
21
  /** false:key 只来自 authFile。 */
@@ -48,6 +48,7 @@ function profileToOptions(path, profile, warnings) {
48
48
  instructions: [...(profile.instructions ?? [])],
49
49
  skillDirs: [...(profile.skillDirs ?? [])],
50
50
  promptDirs: [...(profile.promptDirs ?? [])],
51
+ extensions: [...(profile.extensions ?? [])],
51
52
  authEnv: profile.authEnv !== false,
52
53
  trustProject: profile.trustProject === true,
53
54
  warnings: [...warnings],
@@ -0,0 +1,7 @@
1
+ /**
2
+ * trust.json 的校验(从 schema.ts 拆出,#301 加了 `extensions` 段)。
3
+ */
4
+ import { type Diagnostic } from "./checker.js";
5
+ import type { TrustFile } from "./types.js";
6
+ export declare function validateTrustFile(value: unknown): Diagnostic[];
7
+ export declare function asTrustFile(value: unknown): TrustFile;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * trust.json 的校验(从 schema.ts 拆出,#301 加了 `extensions` 段)。
3
+ */
4
+ import { msg } from "../i18n/index.js";
5
+ import { Checker, join } from "./checker.js";
6
+ export function validateTrustFile(value) {
7
+ const c = new Checker();
8
+ if (!c.object(value, ""))
9
+ return c.diagnostics;
10
+ c.version(value, "");
11
+ const entries = value["entries"];
12
+ if (!Array.isArray(entries)) {
13
+ c.error("entries", msg().config.schema.array);
14
+ return c.diagnostics;
15
+ }
16
+ entries.forEach((entry, index) => {
17
+ const p = join("entries", index);
18
+ if (!c.object(entry, p))
19
+ return;
20
+ c.string(entry, "path", p, true);
21
+ c.string(entry, "at", p, true);
22
+ if (typeof entry["trusted"] !== "boolean")
23
+ c.error(join(p, "trusted"), msg().config.schema.boolean);
24
+ });
25
+ const extensions = value["extensions"];
26
+ if (extensions !== undefined) {
27
+ if (!Array.isArray(extensions)) {
28
+ c.error("extensions", msg().config.schema.array);
29
+ return c.diagnostics;
30
+ }
31
+ extensions.forEach((entry, index) => {
32
+ const p = join("extensions", index);
33
+ if (!c.object(entry, p))
34
+ return;
35
+ c.string(entry, "path", p, true);
36
+ c.string(entry, "sha256", p, true);
37
+ c.string(entry, "at", p, true);
38
+ if (typeof entry["trusted"] !== "boolean")
39
+ c.error(join(p, "trusted"), msg().config.schema.boolean);
40
+ });
41
+ }
42
+ return c.diagnostics;
43
+ }
44
+ export function asTrustFile(value) {
45
+ return value;
46
+ }
@@ -5,26 +5,25 @@
5
5
  * 校验结果是诊断列表:`severity: "error"` 拒绝该文件(启动退出码 3),`"warning"` 只提示
6
6
  * (未知字段等)。`path` 是 JSON 指针风格的字段路径(`permission.mode`、`hooks.PreToolUse[0]`)。
7
7
  */
8
- import { type AmaConfig, type AuthFile, type ProfileFile, type TrustFile } from "./types.js";
8
+ import { type AmaConfig, type AuthFile, type ProfileFile } from "./types.js";
9
9
  import { type Diagnostic } from "./checker.js";
10
10
  import type { HookConfig } from "../hooks/types.js";
11
- export type { AmaConfig, AuthFile, ProfileFile, TrustFile, TrustEntry, ProviderConfig, PermissionConfig, CompactionConfig, RetryConfig, ToolsConfig, ToolsPreset, ToolsPresetInput, CodemodeConfig, CodemodeMode, HooksSettings, UiConfig, SkillsConfig, CacheConfig, CheckpointsConfig, ModelConfig, ModelOverride, ChannelConfig, } from "./types.js";
11
+ export type { AmaConfig, AuthFile, ProfileFile, TrustFile, TrustEntry, ExtensionTrustEntry, ProviderConfig, PermissionConfig, CompactionConfig, RetryConfig, ToolsConfig, ToolsPreset, ToolsPresetInput, CodemodeConfig, CodemodeMode, HooksSettings, UiConfig, SkillsConfig, CacheConfig, CheckpointsConfig, ModelConfig, ModelOverride, ChannelConfig, } from "./types.js";
12
12
  export { CONFIG_FILE_VERSION } from "./types.js";
13
13
  export type { HookConfig } from "../hooks/types.js";
14
14
  export type { Diagnostic } from "./checker.js";
15
15
  export { THINKING_LEVELS } from "./checker.js";
16
+ export { asTrustFile, validateTrustFile } from "./schema-trust.js";
16
17
  export declare const HOOK_TIMEOUT_MAX_MS = 600000;
17
18
  export declare function hasErrors(diagnostics: readonly Diagnostic[]): boolean;
18
19
  export declare function validateConfig(value: unknown): Diagnostic[];
19
20
  export declare function validateAuthFile(value: unknown): Diagnostic[];
20
21
  export declare const PROFILE_PATH_FIELDS: readonly ["host", "hooksFile", "authFile", "sessionDir", "config"];
21
- export declare const PROFILE_PATH_LIST_FIELDS: readonly ["instructions", "skillDirs", "promptDirs", "agentDirs"];
22
+ export declare const PROFILE_PATH_LIST_FIELDS: readonly ["instructions", "skillDirs", "promptDirs", "agentDirs", "extensions"];
22
23
  export declare function validateProfile(value: unknown): Diagnostic[];
23
- export declare function validateTrustFile(value: unknown): Diagnostic[];
24
24
  export declare function validateHookConfig(value: unknown): Diagnostic[];
25
25
  /** 校验通过后的类型断言(调用方保证 `hasErrors()` 为 false)。 */
26
26
  export declare function asConfig(value: unknown): AmaConfig;
27
27
  export declare function asAuthFile(value: unknown): AuthFile;
28
28
  export declare function asProfile(value: unknown): ProfileFile;
29
- export declare function asTrustFile(value: unknown): TrustFile;
30
29
  export declare function asHookConfig(value: unknown): HookConfig;
@@ -8,7 +8,7 @@
8
8
  import { isAbsolute } from "node:path";
9
9
  import { msg } from "../i18n/index.js";
10
10
  import { MAX_TIMER_MS } from "../tools/timers.js";
11
- import { MIN_CONTEXT_BUDGET, } from "./types.js";
11
+ import { MIN_CONTEXT_BUDGET } from "./types.js";
12
12
  import { Checker, THINKING_LEVELS, checkSection, join, } from "./checker.js";
13
13
  import { W5_COMPACTION_KEYS, W5_CONFIG_KEYS, W5_UI_KEYS, checkCompactionW5, checkUiW5, validateConfigW5, } from "./schema-w5.js";
14
14
  import { W6_CONFIG_KEYS, W6_UI_KEYS, checkOAuthEntry, checkProfileMemory, checkUiW6, validateConfigW6, } from "./schema-w6.js";
@@ -16,9 +16,10 @@ import { HOOK_EVENTS } from "../hooks/types.js";
16
16
  import { PERMISSION_MODES_STRICT_FIRST } from "../permissions/types.js";
17
17
  import { WARMING_MODES } from "../ai/cache/types.js";
18
18
  import { BUILTIN_PROVIDERS } from "../ai/providers/builtin.js";
19
- import { CACHE_RETENTIONS, CHANNEL_NAME_PATTERN, CHECKPOINT_MODES, SANDBOX_ENABLED_MODES, SANDBOX_NETWORK_MODES, CODEMODE_MODES, TOOLS_PRESET_INPUTS, } from "./types.js";
19
+ import { CACHE_RETENTIONS, CHANNEL_NAME_PATTERN, CHECKPOINT_MODES, SANDBOX_ENABLED_MODES, SANDBOX_NETWORK_MODES, CODEMODE_ENGINES, CODEMODE_MODES, TOOLS_PRESET_INPUTS, } from "./types.js";
20
20
  export { CONFIG_FILE_VERSION } from "./types.js";
21
21
  export { THINKING_LEVELS } from "./checker.js";
22
+ export { asTrustFile, validateTrustFile } from "./schema-trust.js";
22
23
  export const HOOK_TIMEOUT_MAX_MS = 600_000;
23
24
  export function hasErrors(diagnostics) {
24
25
  return diagnostics.some((d) => d.severity === "error");
@@ -266,11 +267,13 @@ export function validateConfig(value) {
266
267
  c.number(s, "bashBackgroundMaxMs", p, 0, MAX_TIMER_MS);
267
268
  c.stringArray(s, "disabled", p);
268
269
  });
269
- checkSection(c, value, "codemode", ["mode", "inlineBudget", "requireStrict", "maxHeapMb"], (s, p) => {
270
+ checkSection(c, value, "codemode", ["mode", "inlineBudget", "requireStrict", "maxHeapMb", "maxWorkers", "engine"], (s, p) => {
270
271
  c.oneOf(s, "mode", p, CODEMODE_MODES);
271
272
  c.number(s, "inlineBudget", p, 0);
272
273
  c.boolean(s, "requireStrict", p);
273
274
  c.number(s, "maxHeapMb", p, 0);
275
+ c.number(s, "maxWorkers", p, 1);
276
+ c.oneOf(s, "engine", p, CODEMODE_ENGINES);
274
277
  });
275
278
  checkSection(c, value, "hooks", ["timeoutMs"], (s, p) => {
276
279
  c.number(s, "timeoutMs", p, 1, HOOK_TIMEOUT_MAX_MS);
@@ -382,6 +385,7 @@ export const PROFILE_PATH_LIST_FIELDS = [
382
385
  "skillDirs",
383
386
  "promptDirs",
384
387
  "agentDirs",
388
+ "extensions",
385
389
  ];
386
390
  export function validateProfile(value) {
387
391
  const c = new Checker();
@@ -408,27 +412,6 @@ export function validateProfile(value) {
408
412
  checkProfileMemory(c, value);
409
413
  return c.diagnostics;
410
414
  }
411
- export function validateTrustFile(value) {
412
- const c = new Checker();
413
- if (!c.object(value, ""))
414
- return c.diagnostics;
415
- c.version(value, "");
416
- const entries = value["entries"];
417
- if (!Array.isArray(entries)) {
418
- c.error("entries", msg().config.schema.array);
419
- return c.diagnostics;
420
- }
421
- entries.forEach((entry, index) => {
422
- const p = join("entries", index);
423
- if (!c.object(entry, p))
424
- return;
425
- c.string(entry, "path", p, true);
426
- c.string(entry, "at", p, true);
427
- if (typeof entry["trusted"] !== "boolean")
428
- c.error(join(p, "trusted"), msg().config.schema.boolean);
429
- });
430
- return c.diagnostics;
431
- }
432
415
  export function validateHookConfig(value) {
433
416
  const c = new Checker();
434
417
  if (!c.object(value, ""))
@@ -488,9 +471,6 @@ export function asAuthFile(value) {
488
471
  export function asProfile(value) {
489
472
  return value;
490
473
  }
491
- export function asTrustFile(value) {
492
- return value;
493
- }
494
474
  export function asHookConfig(value) {
495
475
  return value;
496
476
  }
@@ -58,6 +58,8 @@ const ROWS = [
58
58
  row("codemode.inlineBudget", "tools", "restart", "deny", { prefix: true }),
59
59
  row("codemode.requireStrict", "tools", "restart", "deny"),
60
60
  row("codemode.maxHeapMb", "tools", "restart", "deny"),
61
+ row("codemode.maxWorkers", "tools", "restart", "deny"),
62
+ row("codemode.engine", "tools", "restart", "deny"),
61
63
  row("tools.maxToolResultChars", "tools", "nextSession", "deny"),
62
64
  row("tools.bashTimeoutMs", "tools", "restart", "deny"),
63
65
  // [#266 / #267] 长命令转后台与后台寿命;缺省由运行方式决定的键也是面板行(显示规则)
@@ -19,6 +19,8 @@ export declare function isWithin(dir: string, ancestor: string, platform?: NodeJ
19
19
  export declare function findTrustEntry(entries: readonly TrustEntry[], cwd: string, platform?: NodeJS.Platform): TrustEntry | undefined;
20
20
  /** 记录信任决策(同路径覆盖)。 */
21
21
  export declare function recordTrust(configDir: string, path: string, trusted: boolean, now?: Date): void;
22
+ /** 原子写 trust.json(保留 `extensions` 段)。 */
23
+ export declare function writeTrustFile(configDir: string, file: TrustFile): void;
22
24
  /** cwd 下需要信任才能加载的资源(为空则无需询问)。 */
23
25
  export declare function trustGatedResources(cwd: string): string[];
24
26
  /** cwd 自身与全部祖先(由内向外)。 */
@@ -53,10 +53,14 @@ export function recordTrust(configDir, path, trusted, now = new Date()) {
53
53
  const abs = resolve(path);
54
54
  const entries = file.entries.filter((e) => normalize(e.path, process.platform) !== normalize(abs, process.platform));
55
55
  entries.push({ path: abs, trusted, at: now.toISOString() });
56
+ writeTrustFile(configDir, { ...file, entries });
57
+ }
58
+ /** 原子写 trust.json(保留 `extensions` 段)。 */
59
+ export function writeTrustFile(configDir, file) {
56
60
  const target = trustFilePath(configDir);
57
61
  mkdirSync(dirname(target), { recursive: true, mode: 0o700 });
58
62
  const tmp = `${target}.${process.pid}.tmp`;
59
- writeFileSync(tmp, `${JSON.stringify({ version: CONFIG_FILE_VERSION, entries }, null, 2)}\n`, {
63
+ writeFileSync(tmp, `${JSON.stringify({ ...file, version: CONFIG_FILE_VERSION }, null, 2)}\n`, {
60
64
  mode: 0o600,
61
65
  });
62
66
  renameSync(tmp, target);
@@ -136,6 +136,9 @@ export interface ToolsConfig {
136
136
  /** codemode 调用方式(设计 §5.5):off 不注册;on 全部工具 + codemode;only 只有 codemode。 */
137
137
  export type CodemodeMode = "off" | "on" | "only";
138
138
  export declare const CODEMODE_MODES: readonly CodemodeMode[];
139
+ /** codemode 脚本引擎:node = Node 子进程;quickjs = WebAssembly 里的 QuickJS;auto 按网络隔离能力选。 */
140
+ export type CodemodeEngineSetting = "auto" | "node" | "quickjs";
141
+ export declare const CODEMODE_ENGINES: readonly CodemodeEngineSetting[];
139
142
  export interface CodemodeConfig {
140
143
  /** 命令行 `--codemode`;项目级只接受 "off"。 */
141
144
  mode?: CodemodeMode;
@@ -145,6 +148,13 @@ export interface CodemodeConfig {
145
148
  requireStrict?: boolean;
146
149
  /** [M-F] 脚本子进程的 V8 堆上限(MB,`--max-old-space-size`),缺省 256,0 不加;只认用户级。 */
147
150
  maxHeapMb?: number;
151
+ /**
152
+ * 整个 ama 进程里同时存活的脚本子进程数上限(所有会话共享),缺省 2;正整数。环境变量
153
+ * `AMA_CODEMODE_MAX_WORKERS` 优先于它;只认用户级。
154
+ */
155
+ maxWorkers?: number;
156
+ /** 脚本引擎,缺省 auto:网络已隔离(Node ≥ 25 或 OS 沙箱)用 node,否则用 quickjs;只认用户级。 */
157
+ engine?: CodemodeEngineSetting;
148
158
  }
149
159
  export interface HooksSettings {
150
160
  timeoutMs?: number;
@@ -276,6 +286,8 @@ export interface ProfileFile {
276
286
  promptDirs?: string[];
277
287
  /** [W5-C0] 子 Agent 定义目录(发现顺序在 `--agent-dir` 之后、用户级之前,W5-G)。 */
278
288
  agentDirs?: string[];
289
+ /** [#301] 本地扩展文件(绝对路径),排在用户级 `extensions/` 之后。 */
290
+ extensions?: string[];
279
291
  hooksFile?: string;
280
292
  authFile?: string;
281
293
  /** false:key 只来自 authFile,不读环境变量(§11.2)。 */
@@ -294,8 +306,19 @@ export interface TrustEntry {
294
306
  /** ISO 8601。 */
295
307
  at: string;
296
308
  }
309
+ /** [#301] 本地扩展的信任记录:按文件内容 sha256;内容变了记录不再匹配,重新询问。 */
310
+ export interface ExtensionTrustEntry {
311
+ path: string;
312
+ /** 小写十六进制,64 位。 */
313
+ sha256: string;
314
+ trusted: boolean;
315
+ /** ISO 8601。 */
316
+ at: string;
317
+ }
297
318
  /** trust.json(只在用户级目录)。 */
298
319
  export interface TrustFile {
299
320
  version: typeof CONFIG_FILE_VERSION;
300
321
  entries: TrustEntry[];
322
+ /** [#301] 本地扩展的信任记录;旧文件没有这一段。 */
323
+ extensions?: ExtensionTrustEntry[];
301
324
  }
@@ -39,6 +39,7 @@ export function canonicalPreset(name) {
39
39
  : name;
40
40
  }
41
41
  export const CODEMODE_MODES = ["off", "on", "only"];
42
+ export const CODEMODE_ENGINES = ["auto", "node", "quickjs"];
42
43
  export const CACHE_RETENTIONS = ["none", "short", "long"];
43
44
  export const DEFAULT_CACHE_CONFIG = Object.freeze({
44
45
  warming: "streaming",
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * 宿主注入的 runner(`HostApi.runners.provide` 的底座,docs/history/wave5-plan.md §5.5,D17)。[W5-E → W5-EG]
3
3
  *
4
- * 一个宿主适配器一份(host/api-impl.ts 建,经 {@link ExternalAgents} 的 `hostRunners` 选项交给每个
5
- * 主会话):宿主可以在 `create()` 里或之后任何时候 `provide`,同名替换;返回的函数注销。
4
+ * [#306] 一个 HostContext 一份(宿主适配器与本地扩展共用,经 {@link ExternalAgents} 的 `hostRunners`
5
+ * 选项交给每个主会话):模块可以在 `create()` 里或之后任何时候 `provide`,跨模块同 id 先到先得(后来者
6
+ * `runner_exists`);返回的函数注销。`onDone` 带 {@link RunnerScope} 时只回调该模块提供的 runner。
6
7
  * `onChange` 供 `/agents` / RPC `get_agents` 的缓存刷新。
7
8
  *
8
9
  * [#226] `onDone`(`HostApi.runners.onDone`):任务入口经 {@link HostRunnerRegistry.resolve} 拿到的是
@@ -11,6 +12,11 @@
11
12
  * 同一轮里多次 `wait()` 只发一次,落定后没有新一轮的 `wait()` 不再发。
12
13
  */
13
14
  import type { HostRunner, RunnerDoneEvent } from "../host/types.js";
15
+ /** [#306] 提供方范围:onDone 只回调同一 owner 提供的 runner;log 缺省走注册表的 log。 */
16
+ export interface RunnerScope {
17
+ owner: symbol;
18
+ log?: (message: string, error: unknown) => void;
19
+ }
14
20
  export type RunnerDoneHandler = (event: RunnerDoneEvent) => void | Promise<void>;
15
21
  export interface HostRunnerRegistryOptions {
16
22
  /** 毫秒时钟(测试注入)。 */
@@ -22,11 +28,16 @@ export declare class HostRunnerRegistry {
22
28
  private readonly runners;
23
29
  private readonly listeners;
24
30
  private readonly doneHandlers;
31
+ private readonly owners;
25
32
  private readonly observed;
26
33
  private readonly now;
27
34
  private readonly log;
28
35
  constructor(options?: HostRunnerRegistryOptions);
29
- provide(runner: HostRunner): () => void;
36
+ /**
37
+ * [#306] 跨模块同 id 先到先得,后来者抛 `runner_exists`;同一模块再次提供同 id 照旧替换(旧的注销函数
38
+ * 随之失效)。`owner` 供 onDone 按模块过滤。
39
+ */
40
+ provide(runner: HostRunner, owner?: symbol): () => void;
30
41
  get(id: string): HostRunner | undefined;
31
42
  /** [#226] 任务入口用:同 {@link get},但返回发 `onDone` 的观察包装(同一 runner 包装复用)。 */
32
43
  resolve(id: string): HostRunner | undefined;
@@ -34,7 +45,7 @@ export declare class HostRunnerRegistry {
34
45
  /** 注入 / 注销时回调;返回取消订阅。 */
35
46
  onChange(listener: () => void): () => void;
36
47
  /** [#226] 每轮结束时回调(`HostApi.runners.onDone`);返回注销函数。 */
37
- onDone(handler: RunnerDoneHandler): () => void;
48
+ onDone(handler: RunnerDoneHandler, scope?: RunnerScope): () => void;
38
49
  private changed;
39
50
  private emitDone;
40
51
  private fail;