@armadra/agent 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/CHANGELOG.zh-CN.md +20 -0
  3. package/README.md +4 -0
  4. package/README.zh-CN.md +4 -0
  5. package/dist/bundle/ama.cjs +25956 -25161
  6. package/dist/cli/bootstrap.js +32 -6
  7. package/dist/cli/compose-agents.js +2 -1
  8. package/dist/cli/compose-extensions-load.d.ts +20 -0
  9. package/dist/cli/compose-extensions-load.js +38 -0
  10. package/dist/cli/compose.js +1 -0
  11. package/dist/cli/deps.d.ts +11 -0
  12. package/dist/cli/runtime.d.ts +7 -0
  13. package/dist/cli/subcommands/doctor.js +33 -0
  14. package/dist/config/extension-tree-hash.d.ts +31 -0
  15. package/dist/config/extension-tree-hash.js +88 -0
  16. package/dist/config/extension-trust.d.ts +70 -0
  17. package/dist/config/extension-trust.js +112 -0
  18. package/dist/config/profile.d.ts +2 -0
  19. package/dist/config/profile.js +1 -0
  20. package/dist/config/schema-trust.d.ts +7 -0
  21. package/dist/config/schema-trust.js +46 -0
  22. package/dist/config/schema.d.ts +4 -5
  23. package/dist/config/schema.js +3 -25
  24. package/dist/config/trust.d.ts +2 -0
  25. package/dist/config/trust.js +5 -1
  26. package/dist/config/types.d.ts +13 -0
  27. package/dist/drivers/host-runners.d.ts +15 -4
  28. package/dist/drivers/host-runners.js +31 -17
  29. package/dist/errors.d.ts +1 -1
  30. package/dist/host/api-impl.d.ts +47 -4
  31. package/dist/host/api-impl.js +181 -20
  32. package/dist/host/commands.d.ts +23 -0
  33. package/dist/host/commands.js +76 -0
  34. package/dist/host/extensions.d.ts +43 -0
  35. package/dist/host/extensions.js +117 -0
  36. package/dist/host/resources.d.ts +2 -0
  37. package/dist/host/resources.js +5 -0
  38. package/dist/host/types.d.ts +41 -2
  39. package/dist/host/types.js +4 -2
  40. package/dist/i18n/catalog.d.ts +31 -0
  41. package/dist/i18n/messages/cli.d.ts +24 -0
  42. package/dist/i18n/messages/cli.js +24 -0
  43. package/dist/i18n/messages/drivers.d.ts +22 -0
  44. package/dist/i18n/messages/drivers.js +22 -0
  45. package/dist/i18n/messages/errors.d.ts +1 -1
  46. package/dist/i18n/messages/interactive-startup.d.ts +4 -0
  47. package/dist/i18n/messages/interactive-startup.js +4 -0
  48. package/dist/i18n/messages/interactive.d.ts +4 -0
  49. package/dist/i18n/messages/report.d.ts +12 -0
  50. package/dist/i18n/messages/report.js +12 -0
  51. package/dist/modes/acp/acp-config.d.ts +4 -2
  52. package/dist/modes/acp/acp-config.js +17 -3
  53. package/dist/modes/acp/acp-events.d.ts +2 -0
  54. package/dist/modes/acp/acp-events.js +4 -0
  55. package/dist/modes/acp/acp-server.js +6 -2
  56. package/dist/modes/acp/acp-sessions.d.ts +8 -1
  57. package/dist/modes/acp/acp-sessions.js +18 -0
  58. package/dist/modes/commands-core.d.ts +14 -1
  59. package/dist/modes/commands-core.js +34 -2
  60. package/dist/modes/interactive/startup-ui.js +21 -0
  61. package/dist/modes/interactive/status-area.js +1 -1
  62. package/dist/modes/print/print-mode.d.ts +3 -0
  63. package/dist/modes/print/print-mode.js +35 -8
  64. package/dist/modes/rpc/commands.d.ts +2 -0
  65. package/dist/modes/rpc/commands.js +22 -7
  66. package/dist/modes/rpc/rpc-mode.js +3 -0
  67. package/dist/modes/startup-ui-text.js +11 -0
  68. package/dist/rpc.d.ts +2 -1
  69. package/dist/tools/registry.d.ts +6 -0
  70. package/dist/tools/registry.js +13 -0
  71. package/dist/tools/types.d.ts +7 -0
  72. package/docs/README.md +1 -1
  73. package/docs/en/README.md +3 -3
  74. package/docs/en/guides/extensions.md +141 -0
  75. package/docs/en/reference/acp.md +1 -1
  76. package/docs/en/reference/host-api.md +55 -27
  77. package/docs/en/reference/rpc.md +9 -7
  78. package/docs/guides/extensions.md +136 -0
  79. package/docs/reference/acp.md +1 -1
  80. package/docs/reference/host-api.md +55 -27
  81. package/docs/reference/rpc.md +9 -7
  82. package/package.json +4 -2
@@ -17,17 +17,20 @@ import { decideTrust } from "../config/trust.js";
17
17
  import { AmaError, StartupError, isAmaError } from "../errors.js";
18
18
  import { loadHookConfigs } from "../hooks/config.js";
19
19
  import { HookDispatcher } from "../hooks/dispatcher.js";
20
- import { AgentEventBus, createHostApi } from "../host/api-impl.js";
20
+ import { AgentEventBus, createHostApi, createHostContext, mergedHostStatus, } from "../host/api-impl.js";
21
+ import { disposeExtensions } from "../host/extensions.js";
21
22
  import { activateHost, disposeHost } from "../host/loader.js";
22
23
  import { HostResourceRegistry } from "../host/resources.js";
23
24
  import { normalizeResourceRef } from "../tools/resource-ref.js";
24
25
  import { helpText, parseArgs, UsageError } from "./args.js";
25
26
  import { hostSessionStart } from "./compose-events.js";
27
+ import { loadExtensions } from "./compose-extensions-load.js";
26
28
  import { applyFromOption } from "./from-prompt.js";
27
29
  import { ExitCode } from "./exit-codes.js";
28
30
  import { applyProfile, applyToolFilters, decideMode, defaultSendUser, instructionSources, resolveModel, sessionRequestOf, sourceOf, step, thinkingOf, toStartupError, } from "./startup-steps.js";
29
31
  import { resolveSystemPromptArg } from "./system-prompt-arg.js";
30
32
  import { memoryEnvOverride, resolveMemory } from "./compose-memory.js";
33
+ import { isReservedCommandName } from "../modes/commands-core.js";
31
34
  import { msg, resolveLocale, setLocale } from "../i18n/index.js";
32
35
  /** §11.1 第 3–14 步。 */
33
36
  export async function bootstrap(argsIn, deps, io) {
@@ -201,7 +204,8 @@ export async function bootstrap(argsIn, deps, io) {
201
204
  if (level === "warn" || level === "error")
202
205
  warn(m().eventWarning(message, detail instanceof Error ? detail.message : undefined));
203
206
  });
204
- const binding = createHostApi({
207
+ const hostContext = createHostContext({ reservedCommand: isReservedCommandName });
208
+ const hostDeps = {
205
209
  mode,
206
210
  env: io.env,
207
211
  session: {
@@ -219,14 +223,31 @@ export async function bootstrap(argsIn, deps, io) {
219
223
  },
220
224
  stderr: io.stderr,
221
225
  resources: hostResources,
222
- });
226
+ };
227
+ const binding = createHostApi(hostDeps, hostContext);
223
228
  let uiBroker;
224
229
  const hostSpec = args.host;
225
230
  let host;
226
231
  if (hostSpec !== undefined) {
227
232
  host = await step(ExitCode.HostOrHook, m().steps.host, () => activateHost({ module: hostSpec, binding, cwd: io.cwd }));
228
233
  }
234
+ // [#301] 本地扩展:宿主适配器之后、组装会话之前;失败只 warning
235
+ const extensions = await loadExtensions({
236
+ configDir: paths.configDir,
237
+ profileExtensions: profile?.extensions ?? [],
238
+ deps: hostDeps,
239
+ context: hostContext,
240
+ noTrust: args.trust === false,
241
+ interactive,
242
+ prompt: deps.ui?.promptExtensions,
243
+ warn,
244
+ });
229
245
  hostResources.freeze();
246
+ // 扩展按加载逆序先 dispose,宿主适配器最后(各自失败只 warning)
247
+ const disposeAll = async () => {
248
+ await disposeExtensions(extensions, (h, e) => warn(m().extensionDisposeFailed(h.source, String(e))));
249
+ await disposeHost(host, (e) => warn(m().hostDisposeFailed(String(e))));
250
+ };
230
251
  let shutdown;
231
252
  try {
232
253
  applyToolFilters(args, tools);
@@ -287,9 +308,11 @@ export async function bootstrap(argsIn, deps, io) {
287
308
  host: {
288
309
  handle: host,
289
310
  broker: binding.broker,
290
- instructions: binding.instructions,
311
+ instructions: hostContext.instructions,
312
+ extensions,
291
313
  warmingDecider: binding.warmingDecider,
292
314
  resources: hostResources.list(),
315
+ runners: hostContext.runners,
293
316
  },
294
317
  uiBroker: () => uiBroker,
295
318
  onSessionReplaced: (next) => {
@@ -323,7 +346,7 @@ export async function bootstrap(argsIn, deps, io) {
323
346
  disposed ??= (async () => {
324
347
  await events.emit("session_shutdown", {});
325
348
  await hooks.run("SessionEnd", { reason }).catch(() => undefined);
326
- await disposeHost(host, (e) => warn(m().hostDisposeFailed(String(e))));
349
+ await disposeAll();
327
350
  // 会话被替换过时 dispose 当前那个(旧会话由替换方负责)
328
351
  await session?.dispose();
329
352
  })();
@@ -358,6 +381,9 @@ export async function bootstrap(argsIn, deps, io) {
358
381
  },
359
382
  hooks,
360
383
  host,
384
+ extensions,
385
+ hostCommands: hostContext.commands,
386
+ hostStatus: () => mergedHostStatus(hostContext),
361
387
  permission,
362
388
  tools,
363
389
  approvals: {
@@ -374,7 +400,7 @@ export async function bootstrap(argsIn, deps, io) {
374
400
  if (shutdown !== undefined)
375
401
  await shutdown("exit").catch(() => undefined);
376
402
  else
377
- await disposeHost(host);
403
+ await disposeAll();
378
404
  throw toStartupError(error, ExitCode.RuntimeError, m().steps.startup);
379
405
  }
380
406
  }
@@ -79,7 +79,8 @@ export function subagentEnvironment(deps, catalog) {
79
79
  export function externalWiring(deps) {
80
80
  const { assembly } = deps;
81
81
  const api = assembly.host.handle?.api;
82
- const hostRunners = api === undefined ? undefined : hostRunnersOf(api);
82
+ // [#306] 共享注册表(宿主适配器与扩展);`hosted` 仍只看宿主适配器
83
+ const hostRunners = assembly.host.runners ?? (api === undefined ? undefined : hostRunnersOf(api));
83
84
  const config = assembly.config;
84
85
  const wiring = {
85
86
  env: deps.env,
@@ -0,0 +1,20 @@
1
+ /**
2
+ * 启动第 13 步的扩展部分(#301):发现 → 按哈希信任决定 → 激活(失败只 warning)。宿主适配器先于它激活,
3
+ * 资源注册表在它之后冻结。
4
+ */
5
+ import { type ExtensionPromptFile } from "../config/extension-trust.js";
6
+ import type { TrustPromptAnswer } from "../config/trust.js";
7
+ import { type HostApiDeps, type HostContext } from "../host/api-impl.js";
8
+ import type { HostAdapterHandle } from "../host/types.js";
9
+ export interface LoadExtensionsInput {
10
+ configDir: string;
11
+ profileExtensions: readonly string[];
12
+ deps: HostApiDeps;
13
+ context: HostContext;
14
+ /** `--no-trust`。 */
15
+ noTrust: boolean;
16
+ interactive: boolean;
17
+ prompt?: ((files: readonly ExtensionPromptFile[]) => Promise<TrustPromptAnswer>) | undefined;
18
+ warn(message: string): void;
19
+ }
20
+ export declare function loadExtensions(input: LoadExtensionsInput): Promise<HostAdapterHandle[]>;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * 启动第 13 步的扩展部分(#301):发现 → 按哈希信任决定 → 激活(失败只 warning)。宿主适配器先于它激活,
3
+ * 资源注册表在它之后冻结。
4
+ */
5
+ import { decideExtensions } from "../config/extension-trust.js";
6
+ import { createHostApi } from "../host/api-impl.js";
7
+ import { activateExtensions, discoverExtensions } from "../host/extensions.js";
8
+ import { msg } from "../i18n/index.js";
9
+ export async function loadExtensions(input) {
10
+ const found = discoverExtensions(input.configDir, input.profileExtensions);
11
+ if (found.length === 0)
12
+ return [];
13
+ // 读 / 写 trust.json 或询问界面出错:全部跳过并 warning,不让扩展的问题变成启动失败(宿主已激活)
14
+ let decision;
15
+ try {
16
+ decision = await decideExtensions({
17
+ paths: found,
18
+ configDir: input.configDir,
19
+ disabled: input.noTrust,
20
+ interactive: input.interactive,
21
+ prompt: input.prompt,
22
+ });
23
+ }
24
+ catch (error) {
25
+ input.warn(msg().cli.bootstrap.extensionsTrustFailed(error instanceof Error ? error.message : String(error)));
26
+ return [];
27
+ }
28
+ const m = msg().cli.bootstrap;
29
+ for (const skipped of decision.skipped) {
30
+ input.warn(m.extensionSkipped(skipped.path, m.extensionReason[skipped.reason]));
31
+ }
32
+ const { handles } = await activateExtensions({
33
+ paths: decision.load,
34
+ createBinding: () => createHostApi(input.deps, input.context),
35
+ warn: input.warn,
36
+ });
37
+ return handles;
38
+ }
@@ -200,6 +200,7 @@ function lazyUi(load) {
200
200
  const get = () => (ui ??= load());
201
201
  return {
202
202
  promptTrust: async (cwd, resources) => (await get()).promptTrust(cwd, resources),
203
+ promptExtensions: async (files) => (await get()).promptExtensions(files),
203
204
  pickSession: async (items) => (await get()).pickSession(items),
204
205
  pickModel: async (providers, reason) => (await get()).pickModel(providers, reason),
205
206
  askCwd: async (missing) => (await get()).askCwd(missing),
@@ -17,6 +17,7 @@ import type { TrustPromptAnswer } from "../config/trust.js";
17
17
  import type { HookDispatcherApi } from "../hooks/types.js";
18
18
  import type { MemoryRuntime } from "../memory/runtime.js";
19
19
  import type { WarmingDecisionHandler } from "../ai/cache/types.js";
20
+ import type { HostRunnerRegistry } from "../drivers/host-runners.js";
20
21
  import type { AgentEventBus } from "../host/api-impl.js";
21
22
  import type { ApprovalBroker, HostAdapterHandle, InstructionSource } from "../host/types.js";
22
23
  import type { PermissionMode, PermissionPipelineApi } from "../permissions/types.js";
@@ -96,6 +97,8 @@ export interface SessionAssembly {
96
97
  events: AgentEventBus;
97
98
  host: {
98
99
  handle: HostAdapterHandle | undefined;
100
+ /** [#301] 已激活的本地扩展(加载顺序);没有时为空表。 */
101
+ extensions?: readonly HostAdapterHandle[];
99
102
  /** 宿主 broker(链首);undefined 交给 UI / 无人值守。 */
100
103
  broker(): ApprovalBroker | undefined;
101
104
  /** 系统提示 host 节。 */
@@ -107,6 +110,8 @@ export interface SessionAssembly {
107
110
  scheme: string;
108
111
  describe: string;
109
112
  }[];
113
+ /** [#306] 宿主适配器与本地扩展共用的 runner 注册表(`task` 与 `/agents` 读它)。 */
114
+ runners?: HostRunnerRegistry;
110
115
  };
111
116
  /** `Runtime.approvals.setUiBroker` 设置的 UI broker(链尾);每次审批现取,未设置为 undefined。 */
112
117
  uiBroker(): ApprovalBroker | undefined;
@@ -151,6 +156,12 @@ export type ModeRunner = (runtime: Runtime, context: ModeContext) => Promise<num
151
156
  /** 交互 UI 回调(B7 / B6 line 提供);全部可选,缺省按非交互处理。 */
152
157
  export interface InteractiveUi {
153
158
  promptTrust?(cwd: string, resources: readonly string[]): Promise<TrustPromptAnswer>;
159
+ /** [#301] 本地扩展首次出现或内容变化时询问(一次,列出全部待定文件的路径与 sha256)。 */
160
+ promptExtensions?(files: readonly {
161
+ path: string;
162
+ sha256: string;
163
+ directory?: boolean;
164
+ }[]): Promise<TrustPromptAnswer>;
154
165
  /** `--resume` 无 id:返回会话 id,undefined = 用户取消(退出码 5)。 */
155
166
  pickSession?(items: readonly SessionListItem[]): Promise<string | undefined>;
156
167
  /** 无 key / 无模型时选择模型;返回 `provider/id`,undefined = 取消(退出码 4)。 */
@@ -10,6 +10,7 @@ import type { AgentSession } from "../agent/types.js";
10
10
  import type { AmaConfig } from "../config/types.js";
11
11
  import type { HookDispatcherApi } from "../hooks/types.js";
12
12
  import type { ApprovalBroker, HostAdapterHandle, HostMode, InstructionSource } from "../host/types.js";
13
+ import type { HostCommandSource } from "../host/commands.js";
13
14
  import type { PermissionPipelineApi } from "../permissions/types.js";
14
15
  import type { SessionManagerApi } from "../session/types.js";
15
16
  import type { ToolRegistryApi } from "../tools/types.js";
@@ -81,6 +82,12 @@ export interface Runtime {
81
82
  readonly hooks: HookDispatcherApi;
82
83
  /** 未激活宿主适配器时为 undefined。 */
83
84
  readonly host: HostAdapterHandle | undefined;
85
+ /** [#301] 已激活的本地扩展(加载顺序,来源路径与 id);没有时为空表。 */
86
+ readonly extensions?: readonly HostAdapterHandle[];
87
+ /** [#301] 宿主适配器与全部扩展 `ui.setStatus` 合并后的状态表(状态栏)。 */
88
+ hostStatus?(): ReadonlyMap<string, string>;
89
+ /** [#301] 宿主适配器与扩展经 `commands.register` 注册的斜杠命令(分派与列出)。 */
90
+ readonly hostCommands?: HostCommandSource;
84
91
  readonly permission: PermissionPipelineApi;
85
92
  readonly tools: ToolRegistryApi;
86
93
  readonly approvals: RuntimeApprovals;
@@ -16,6 +16,8 @@ import { findContextFiles } from "../../config/context-files.js";
16
16
  import { loadConfigFile, probeConfigFile } from "../../config/load.js";
17
17
  import { mergeProjectAndCli } from "../../config/merge.js";
18
18
  import { CONFIG_FILE, HOOKS_FILE, projectFile, userFile } from "../../config/paths.js";
19
+ import { inspectExtension } from "../../config/extension-trust.js";
20
+ import { discoverExtensions } from "../../host/extensions.js";
19
21
  import { findTrustEntry, readTrustFile, trustGatedResources } from "../../config/trust.js";
20
22
  import { loadHookConfigs } from "../../hooks/config.js";
21
23
  import { osSandboxStatus } from "../../sandbox/detect.js";
@@ -100,6 +102,36 @@ function trustSection(report, io, level, flag) {
100
102
  }
101
103
  return trusted;
102
104
  }
105
+ /** [#301] 本地扩展:文件、哈希前缀与信任状态;不执行扩展代码。 */
106
+ function extensionsSection(report, level, noTrust) {
107
+ const m = msg().report.doctor;
108
+ const reasons = msg().cli.bootstrap.extensionReason;
109
+ report.section(m.extensionsTitle);
110
+ const paths = discoverExtensions(level.configDir, level.profile?.extensions ?? []);
111
+ if (paths.length === 0) {
112
+ report.item(m.extensionsNone);
113
+ return;
114
+ }
115
+ report.item(m.extensionsNote);
116
+ let recorded = [];
117
+ try {
118
+ recorded = readTrustFile(level.configDir).extensions ?? [];
119
+ }
120
+ catch (error) {
121
+ report.problem(error.message);
122
+ }
123
+ for (const path of paths) {
124
+ const info = inspectExtension(path, recorded);
125
+ const reason = noTrust
126
+ ? "no-trust"
127
+ : info.status === "trusted"
128
+ ? undefined
129
+ : info.status === "unknown"
130
+ ? "untrusted"
131
+ : info.status;
132
+ report.item(m.extensionLine(reason === undefined, info.path, m.extensionSha(info.sha256), reason === undefined ? undefined : reasons[reason], info.directory === true));
133
+ }
134
+ }
103
135
  async function keySection(report, io, level, deps) {
104
136
  const m = msg().report.doctor;
105
137
  report.section(m.keysTitle);
@@ -308,6 +340,7 @@ export async function runDoctor(argv, io, deps) {
308
340
  for (const file of context.files)
309
341
  report.item(`${file.scope === "user" ? m.contextUser : m.contextProject} ${file.path}`);
310
342
  await keySection(report, io, level, deps);
343
+ extensionsSection(report, level, flags.has("no-trust"));
311
344
  hookSection(report, io, level, trusted);
312
345
  report.item(m.userHooks(userFile(level, HOOKS_FILE)));
313
346
  proxySection(report, io);
@@ -0,0 +1,31 @@
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
+ export declare const MAX_TREE_FILES = 2000;
15
+ export declare const MAX_TREE_BYTES: number;
16
+ export declare const MAX_TREE_DIRS = 2000;
17
+ export declare const MAX_TREE_DEPTH = 32;
18
+ export interface TreeLimits {
19
+ maxFiles: number;
20
+ maxBytes: number;
21
+ /** 缺省 {@link MAX_TREE_DIRS}。 */
22
+ maxDirs?: number;
23
+ /** 缺省 {@link MAX_TREE_DEPTH}。 */
24
+ maxDepth?: number;
25
+ }
26
+ export declare const DEFAULT_TREE_LIMITS: TreeLimits;
27
+ /** 文件数或总字节数超过上限(与「读不了」区分开)。 */
28
+ export declare class TreeLimitError extends Error {
29
+ }
30
+ /** 目录树的 sha256(十六进制)。读不了(含断开或成环的链接)抛错,超限抛 {@link TreeLimitError}。 */
31
+ export declare function sha256OfTree(root: string, limits?: TreeLimits): string;
@@ -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
+ }
@@ -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;