@autopilot-agent/adapters 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2159,7 +2159,9 @@ __export(index_exports, {
2159
2159
  createNodeClock: () => createNodeClock,
2160
2160
  createNodeCredentialStore: () => createNodeCredentialStore,
2161
2161
  createNodeEventSink: () => createNodeEventSink,
2162
+ createNodeExternalPermissionProjector: () => createNodeExternalPermissionProjector,
2162
2163
  createNodeFileMutationStore: () => createNodeFileMutationStore,
2164
+ createNodeHostExecutionSandboxPort: () => createNodeHostExecutionSandboxPort,
2163
2165
  createNodeInputInbox: () => createNodeInputInbox,
2164
2166
  createNodeJobOwnerProbe: () => createNodeJobOwnerProbe,
2165
2167
  createNodeJobStore: () => createNodeJobStore,
@@ -2194,8 +2196,8 @@ __export(index_exports, {
2194
2196
  getNodeStatePaths: () => getNodeStatePaths,
2195
2197
  getNodeStateSchemaDiagnostic: () => getNodeStateSchemaDiagnostic,
2196
2198
  initializeNodeStateRoot: () => initializeNodeStateRoot,
2199
+ isSafeSettingsFile: () => isSafeSettingsFile,
2197
2200
  loadMcpConfigFromWorkspace: () => loadMcpConfigFromWorkspace,
2198
- readWindowsSandboxCapability: () => readWindowsSandboxCapability,
2199
2201
  resolveNodeChatStatePaths: () => resolveNodeChatStatePaths,
2200
2202
  resolveNodeGlobalStateRoot: () => resolveNodeGlobalStateRoot,
2201
2203
  resolveNodeSettingsPaths: () => resolveNodeSettingsPaths,
@@ -2203,7 +2205,6 @@ __export(index_exports, {
2203
2205
  resolveNodeTrustRoot: () => resolveNodeTrustRoot,
2204
2206
  resolveNodeUserSettingsPath: () => resolveNodeUserSettingsPath,
2205
2207
  retrieveNodeMemories: () => retrieveNodeMemories,
2206
- runWindowsSandboxSetup: () => runWindowsSandboxSetup,
2207
2208
  serializePosixCommand: () => serializePosixCommand
2208
2209
  });
2209
2210
  module.exports = __toCommonJS(index_exports);
@@ -2276,7 +2277,7 @@ function toNodeBoundaryError(error, fallback) {
2276
2277
  }
2277
2278
 
2278
2279
  // src/node/create-node-runtime-ports.ts
2279
- var import_core12 = require("@autopilot-agent/core");
2280
+ var import_core14 = require("@autopilot-agent/core");
2280
2281
 
2281
2282
  // src/node/capabilities/context-budget.ts
2282
2283
  var DEFAULT_CONTEXT_WINDOW_TOKENS = 128e3;
@@ -17398,8 +17399,42 @@ function createNodeCapabilityLoader(options = {}) {
17398
17399
  };
17399
17400
  }
17400
17401
 
17402
+ // src/node/sandbox/node-host-execution-sandbox-port.ts
17403
+ var import_core8 = require("@autopilot-agent/core");
17404
+ function hostExecutionCapabilityReport() {
17405
+ return {
17406
+ platform: "windows",
17407
+ backend: "host-execution",
17408
+ enforcement: "unavailable",
17409
+ installed: false,
17410
+ provisioned: false,
17411
+ diagnostics: [
17412
+ "Windows \u5BBF\u4E3B\u6267\u884C\u6A21\u5F0F\uFF1A\u8FDB\u7A0B\u6C99\u7BB1\u5DF2\u505C\u7528\uFF0C\u8FDB\u7A0B\u8C03\u7528\u7ECF\u7528\u6237\u9010\u6B21\u5BA1\u6279\u540E\u5728\u5BBF\u4E3B\u4EE5\u5F53\u524D\u7528\u6237\u6743\u9650\u76F4\u63A5\u6267\u884C"
17413
+ ]
17414
+ };
17415
+ }
17416
+ function createNodeHostExecutionSandboxPort() {
17417
+ return {
17418
+ // Talk-Plan1022 CR R2:静态声明宿主执行方式,供 Turn 冻结与恢复比对,不依赖 status 探测。
17419
+ execution: "host",
17420
+ async status() {
17421
+ return hostExecutionCapabilityReport();
17422
+ },
17423
+ async setup() {
17424
+ return hostExecutionCapabilityReport();
17425
+ },
17426
+ async prepare(_request) {
17427
+ throw new import_core8.SandboxPortError(import_core8.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u5BBF\u4E3B\u6267\u884C\u6A21\u5F0F\u4E0D\u63D0\u4F9B\u6C99\u7BB1\u5305\u88C5\uFF0C\u547D\u4EE4\u672A\u901A\u8FC7\u6C99\u7BB1\u542F\u52A8");
17428
+ },
17429
+ async release() {
17430
+ },
17431
+ async shutdown() {
17432
+ }
17433
+ };
17434
+ }
17435
+
17401
17436
  // src/node/sandbox/node-sandbox-port.ts
17402
- var import_core10 = require("@autopilot-agent/core");
17437
+ var import_core9 = require("@autopilot-agent/core");
17403
17438
 
17404
17439
  // src/node/sandbox/srt-module.ts
17405
17440
  var SRT_MODULE_SPECIFIER = "@anthropic-ai/sandbox-runtime";
@@ -17412,366 +17447,318 @@ function readSrtVersion() {
17412
17447
  return void 0;
17413
17448
  }
17414
17449
  }
17450
+ var importSrtRuntime = new Function("specifier", "return import(specifier);");
17415
17451
  function loadSrtRuntimeSurface() {
17416
- return import(SRT_MODULE_SPECIFIER);
17452
+ return importSrtRuntime(SRT_MODULE_SPECIFIER);
17417
17453
  }
17418
17454
 
17419
- // src/node/sandbox/windows-sandbox-setup.ts
17420
- var import_core8 = require("@autopilot-agent/core");
17421
- function isWindowsSandboxError(error) {
17422
- return error instanceof Error && typeof error.code === "string";
17423
- }
17424
- function projectWindowsStatus(mod, status, version) {
17425
- const provisioned = status.user.provisioned && status.user.credPresent;
17426
- return {
17427
- platform: "windows",
17428
- backend: "srt-windows",
17429
- // Windows 保障等级必须以实机门禁(T12/T13)为准,未验证前不得报告 full。
17430
- enforcement: provisioned ? "partial" : "unavailable",
17431
- installed: true,
17432
- provisioned,
17433
- ...version !== void 0 ? { version } : {},
17434
- diagnostics: [
17435
- `wfp=${status.wfp.state}`,
17436
- `sandbox_user_provisioned=${status.user.provisioned}`,
17437
- "full \u80FD\u529B\u9700 SandboxPort \u521D\u59CB\u5316\u4E0E WFP \u884C\u4E3A\u9A8C\u8BC1\u6210\u529F\uFF1Bprovision \u72B6\u6001\u672C\u8EAB\u4E0D\u8BC1\u660E\u53EF\u6267\u884C"
17438
- ]
17439
- };
17455
+ // src/node/sandbox/node-sandbox-port.ts
17456
+ var import_node_path8 = __toESM(require("node:path"));
17457
+
17458
+ // src/node/file-mutation-locks.ts
17459
+ var import_node_os2 = __toESM(require("node:os"));
17460
+ var import_node_path5 = __toESM(require("node:path"));
17461
+ var import_node_crypto4 = require("node:crypto");
17462
+
17463
+ // src/node/file-utils.ts
17464
+ var import_node_fs5 = __toESM(require("node:fs"));
17465
+ var import_promises2 = __toESM(require("node:fs/promises"));
17466
+ var import_node_crypto3 = require("node:crypto");
17467
+ var import_node_path4 = __toESM(require("node:path"));
17468
+ var fileLocks = /* @__PURE__ */ new Map();
17469
+ var PROCESS_LOCK_RETRY_MS = 10;
17470
+ var PROCESS_LOCK_TIMEOUT_MS = 3e4;
17471
+ var PROCESS_LOCK_STALE_MS = 6e4;
17472
+ function waitForProcessLock() {
17473
+ return new Promise((resolve) => setTimeout(resolve, PROCESS_LOCK_RETRY_MS));
17440
17474
  }
17441
- async function readWindowsSandboxCapability(options = {}) {
17475
+ function isStaleProcessLock(lockPath) {
17442
17476
  try {
17443
- const mod = await (options.loadModule ?? loadSrtRuntimeSurface)();
17444
- const srtWin = { exe: options.srtWinExe ?? mod.VENDORED_SRT_WIN_EXE, prependArgs: [] };
17445
- const status = await mod.checkWindowsSandboxStatusAsync({ srtWin });
17446
- return projectWindowsStatus(mod, status);
17447
- } catch (error) {
17448
- throw toSandboxPortError(error);
17477
+ const metadata = JSON.parse(import_node_fs5.default.readFileSync(lockPath, "utf8"));
17478
+ const createdAt = typeof metadata.createdAt === "number" ? metadata.createdAt : import_node_fs5.default.statSync(lockPath).mtimeMs;
17479
+ return Date.now() - createdAt > PROCESS_LOCK_STALE_MS;
17480
+ } catch {
17481
+ try {
17482
+ return Date.now() - import_node_fs5.default.statSync(lockPath).mtimeMs > PROCESS_LOCK_STALE_MS;
17483
+ } catch {
17484
+ return false;
17485
+ }
17449
17486
  }
17450
17487
  }
17451
- async function runWindowsSandboxSetup(options = {}) {
17488
+ async function isStaleProcessLockAsync(lockPath) {
17452
17489
  try {
17453
- const mod = await (options.loadModule ?? loadSrtRuntimeSurface)();
17454
- const srtWin = { exe: options.srtWinExe ?? mod.VENDORED_SRT_WIN_EXE, prependArgs: [] };
17455
- const result = await mod.installWindowsSandboxAsync({ srtWin });
17456
- const status = {
17457
- user: { provisioned: result.user.provisioned, credPresent: result.user.credPresent, realUserSid: "" },
17458
- wfp: { state: result.wfp.state, filters: result.wfp.filters }
17459
- };
17460
- const report = projectWindowsStatus(mod, status);
17461
- return result.cancelled === true ? { ...report, diagnostics: [...report.diagnostics ?? [], "install_cancelled: \u7528\u6237\u53D6\u6D88\u4E86 UAC \u63D0\u6743\uFF0C\u5B89\u88C5\u672A\u6267\u884C"] } : report;
17462
- } catch (error) {
17463
- throw toSandboxPortError(error);
17464
- }
17465
- }
17466
- function toSandboxPortError(error) {
17467
- if (error instanceof import_core8.SandboxPortError) return error;
17468
- if (isWindowsSandboxError(error)) {
17469
- if (error.code === "not_provisioned") return new import_core8.SandboxPortError(import_core8.SANDBOX_ERROR_CODES.NOT_PROVISIONED, "Windows \u6C99\u7BB1\u672A\u5B8C\u6210 provision\uFF0C\u8BF7\u5148\u663E\u5F0F\u6267\u884C setup");
17470
- return new import_core8.SandboxPortError(import_core8.SANDBOX_ERROR_CODES.UNAVAILABLE, "Windows \u6C99\u7BB1\u72B6\u6001\u63A2\u6D4B\u5931\u8D25");
17490
+ const metadata = JSON.parse(await import_promises2.default.readFile(lockPath, "utf8"));
17491
+ const createdAt = typeof metadata.createdAt === "number" ? metadata.createdAt : (await import_promises2.default.stat(lockPath)).mtimeMs;
17492
+ return Date.now() - createdAt > PROCESS_LOCK_STALE_MS;
17493
+ } catch {
17494
+ try {
17495
+ return Date.now() - (await import_promises2.default.stat(lockPath)).mtimeMs > PROCESS_LOCK_STALE_MS;
17496
+ } catch {
17497
+ return false;
17498
+ }
17471
17499
  }
17472
- return new import_core8.SandboxPortError(import_core8.SANDBOX_ERROR_CODES.UNAVAILABLE, "Windows \u6C99\u7BB1 backend \u4E0D\u53EF\u7528");
17473
17500
  }
17474
-
17475
- // src/node/sandbox/windows-sandbox-command.ts
17476
- var import_node_fs5 = __toESM(require("node:fs"));
17477
- var import_node_path4 = __toESM(require("node:path"));
17478
- var import_node_crypto3 = require("node:crypto");
17479
- var import_core9 = require("@autopilot-agent/core");
17480
- function resolveWindowsSandboxRunner(vendored, explicit) {
17481
- if (explicit !== void 0) {
17482
- if (!import_node_path4.default.win32.isAbsolute(explicit)) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, "Windows runner \u5FC5\u987B\u662F\u5BBF\u4E3B\u6307\u5B9A\u7684\u7EDD\u5BF9\u8DEF\u5F84");
17483
- return explicit;
17484
- }
17485
- const publicRunner = import_node_path4.default.win32.join(process.env.ProgramData ?? "C:\\ProgramData", "AutopilotSandbox", "bin", "srt-win.exe");
17501
+ function hasExitedProcessLockOwner(lockPath) {
17486
17502
  try {
17487
- if ((0, import_node_crypto3.createHash)("sha256").update(import_node_fs5.default.readFileSync(publicRunner)).digest("hex") === (0, import_node_crypto3.createHash)("sha256").update(import_node_fs5.default.readFileSync(vendored)).digest("hex")) return publicRunner;
17503
+ const metadata = JSON.parse(import_node_fs5.default.readFileSync(lockPath, "utf8"));
17504
+ if (!Number.isInteger(metadata.pid) || metadata.pid <= 0) return false;
17505
+ try {
17506
+ process.kill(metadata.pid, 0);
17507
+ return false;
17508
+ } catch (error) {
17509
+ return error.code === "ESRCH";
17510
+ }
17488
17511
  } catch {
17512
+ return false;
17489
17513
  }
17490
- return vendored;
17491
17514
  }
17492
- function resolveWindowsSandboxCommand(program, args) {
17493
- if (/^(npm|npx)(\.cmd)?$/i.test(program)) {
17494
- const nodeRoot = import_node_fs5.default.realpathSync.native(import_node_path4.default.dirname(process.execPath));
17495
- const cli = import_node_fs5.default.realpathSync.native(import_node_path4.default.join(nodeRoot, "node_modules", "npm", "bin", /^npx/i.test(program) ? "npx-cli.js" : "npm-cli.js"));
17496
- const relative = import_node_path4.default.relative(nodeRoot, cli);
17497
- if (relative.startsWith("..") || import_node_path4.default.isAbsolute(relative)) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u53D7\u4FE1 npm CLI \u4E0D\u53EF\u7528");
17498
- return { exe: process.execPath, args: [cli, ...args] };
17515
+ async function hasExitedProcessLockOwnerAsync(lockPath) {
17516
+ try {
17517
+ const metadata = JSON.parse(await import_promises2.default.readFile(lockPath, "utf8"));
17518
+ if (!Number.isInteger(metadata.pid) || metadata.pid <= 0) return false;
17519
+ try {
17520
+ process.kill(metadata.pid, 0);
17521
+ return false;
17522
+ } catch (error) {
17523
+ return error.code === "ESRCH";
17524
+ }
17525
+ } catch {
17526
+ return false;
17499
17527
  }
17500
- const candidates = import_node_path4.default.win32.isAbsolute(program) ? [program] : (process.env.PATH ?? "").split(";").filter(Boolean).map(function candidate(directory) {
17501
- return import_node_path4.default.win32.join(directory.replace(/^"|"$/g, ""), /\.exe$/i.test(program) ? program : `${program}.exe`);
17502
- });
17503
- const exe = candidates.find(function exists(candidate) {
17504
- return import_node_fs5.default.existsSync(candidate) && import_node_fs5.default.statSync(candidate).isFile();
17505
- });
17506
- if (exe === void 0 || !/\.exe$/i.test(exe)) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, "Windows \u539F\u751F\u53EF\u6267\u884C\u7A0B\u5E8F\u4E0D\u53EF\u7528\uFF0C\u547D\u4EE4\u672A\u542F\u52A8");
17507
- return { exe, args: [...args] };
17508
- }
17509
- function finalizeWindowsSandboxArgv(argv, target, tempRoot) {
17510
- const marker = argv.length - target.args.length - 3;
17511
- const expected = ["--", target.exe, ...target.args, ""];
17512
- if (marker < 1 || JSON.stringify(argv.slice(marker)) !== JSON.stringify(expected)) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.RUNNER_FAILED, "Windows \u6C99\u7BB1\u5305\u88C5\u7ED3\u6784\u5F02\u5E38\uFF0C\u547D\u4EE4\u672A\u542F\u52A8");
17513
- const env = tempRoot === void 0 ? [] : ["TEMP", "TMP", "TMPDIR"].flatMap(function entry(key2) {
17514
- return ["--env", `${key2}=${tempRoot}`];
17515
- });
17516
- return [...argv.slice(0, marker), ...env, ...argv.slice(marker, -1)];
17517
- }
17518
-
17519
- // src/node/sandbox/node-sandbox-port.ts
17520
- var windowsManagerOwners = /* @__PURE__ */ new WeakMap();
17521
- function posixQuote(value) {
17522
- return `'${value.replace(/'/g, `'\\''`)}'`;
17523
- }
17524
- function serializePosixCommand(program, args, tempRoot) {
17525
- const command = [posixQuote(program), ...args.map(posixQuote)].join(" ");
17526
- return tempRoot !== void 0 ? `TMPDIR=${posixQuote(tempRoot)} ${command}` : command;
17527
17528
  }
17528
- function buildSrtRuntimeConfig(policy) {
17529
- return {
17530
- network: {
17531
- allowedDomains: [...policy.allowedDomains],
17532
- deniedDomains: []
17533
- },
17534
- filesystem: {
17535
- denyRead: [...policy.deniedRead],
17536
- // read-only:无任何写授权;workspace-write:仅 canonical 工作区;
17537
- // danger-full-access:宿主显式冻结后的沙箱最大档位,写全开但仍保留 deny 列表与网络边界。
17538
- allowWrite: policy.mode === "workspace-write" && policy.workspaceRoot !== void 0 ? [.../* @__PURE__ */ new Set([policy.workspaceRoot, ...policy.tempRoot !== void 0 ? [policy.tempRoot] : []])] : policy.mode === "danger-full-access" ? ["/"] : [],
17539
- denyWrite: [...policy.deniedWrite]
17540
- },
17541
- allowAppleEvents: false
17542
- };
17529
+ function isProcessLockContention(code) {
17530
+ return code === "EEXIST" || code === "EPERM" || code === "EACCES";
17543
17531
  }
17544
- function createNodeSandboxPort(options) {
17545
- let module2;
17546
- let initPromise;
17547
- let initConfigKey;
17548
- let shutdown = false;
17549
- let cleanupDiagnostic;
17550
- const activeExecutions = /* @__PURE__ */ new Set();
17551
- let windowsRunner;
17552
- const owner = {};
17553
- async function ensureModule() {
17554
- if (!module2) {
17555
- try {
17556
- module2 = await (options.loadModule ?? loadSrtRuntimeSurface)();
17557
- } catch {
17558
- throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u6C99\u7BB1 backend \u52A0\u8F7D\u5931\u8D25");
17559
- }
17560
- }
17561
- return module2;
17562
- }
17563
- function toPortError(error) {
17564
- if (error instanceof import_core10.SandboxPortError) return error;
17565
- return new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.RUNNER_FAILED, "\u6C99\u7BB1 runner \u521D\u59CB\u5316\u6216\u5305\u88C5\u5931\u8D25\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
17566
- }
17567
- async function ensureInitialized(policy) {
17568
- if (shutdown) throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u521D\u59CB\u5316");
17569
- const mod = await ensureModule();
17570
- if (!mod.SandboxManager.isSupportedPlatform()) {
17571
- throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.UNAVAILABLE, `\u5F53\u524D\u5E73\u53F0 ${process.platform} \u4E0D\u88AB\u6C99\u7BB1 backend \u652F\u6301`);
17572
- }
17573
- const dependencies = process.platform === "win32" ? { errors: [] } : mod.SandboxManager.checkDependencies();
17574
- if (dependencies.errors.length > 0) {
17575
- throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u6C99\u7BB1\u5E73\u53F0\u4F9D\u8D56\u7F3A\u5931\uFF0C\u65E0\u6CD5\u63D0\u4F9B\u5DF2\u9694\u79BB\u6267\u884C");
17576
- }
17577
- const config = buildSrtRuntimeConfig(policy);
17578
- if (process.platform === "win32") {
17579
- if (policy.mode === "danger-full-access") throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.UNAVAILABLE, "Windows \u6682\u4E0D\u652F\u6301\u5168\u76D8\u5199\u6388\u6743\uFF0C\u547D\u4EE4\u672A\u542F\u52A8");
17580
- const currentOwner = windowsManagerOwners.get(mod.SandboxManager);
17581
- if (currentOwner !== void 0 && currentOwner !== owner) throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.SCOPE_CONFLICT, "Windows \u6C99\u7BB1\u5DF2\u88AB\u53E6\u4E00 Port \u7ED1\u5B9A\uFF0C\u62D2\u7EDD\u5E76\u884C\u6539\u5199\u4F1A\u8BDD");
17582
- windowsManagerOwners.set(mod.SandboxManager, owner);
17583
- windowsRunner ??= resolveWindowsSandboxRunner(mod.VENDORED_SRT_WIN_EXE, options.windowsSrtWinExe);
17584
- config.windows = { srtWin: { path: windowsRunner } };
17585
- if (policy.mode === "read-only") config.filesystem.allowRead = [options.workspaceRoot];
17586
- }
17587
- const configKey = JSON.stringify(config);
17588
- if (initPromise && configKey === initConfigKey) {
17589
- await initPromise;
17590
- return mod;
17591
- }
17592
- if (initPromise) {
17593
- try {
17594
- await initPromise;
17595
- if (process.platform === "win32") {
17596
- if (activeExecutions.size > 0) throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.SCOPE_CONFLICT, "\u5B58\u5728\u6D3B\u52A8\u6C99\u7BB1\u8FDB\u7A0B\uFF0C\u62D2\u7EDD\u5207\u6362 Windows \u4F1A\u8BDD\u7B56\u7565");
17597
- await mod.SandboxManager.reset();
17598
- initPromise = void 0;
17599
- initConfigKey = void 0;
17600
- } else {
17601
- mod.SandboxManager.updateConfig(config);
17602
- initConfigKey = configKey;
17603
- return mod;
17532
+ async function acquireProcessLock(filePath, requireExitedOwner = false) {
17533
+ ensureParentDirectory(filePath);
17534
+ const lockPath = `${filePath}.lock`;
17535
+ const ownerId = (0, import_node_crypto3.randomUUID)();
17536
+ const startedAt = Date.now();
17537
+ while (true) {
17538
+ try {
17539
+ const descriptor = import_node_fs5.default.openSync(lockPath, "wx");
17540
+ const metadata = { ownerId, pid: process.pid, createdAt: Date.now() };
17541
+ import_node_fs5.default.writeFileSync(descriptor, JSON.stringify(metadata), "utf8");
17542
+ return { lockPath, ownerId, descriptor };
17543
+ } catch (error) {
17544
+ const code = error.code;
17545
+ if (!isProcessLockContention(code)) throw error;
17546
+ if (hasExitedProcessLockOwner(lockPath) || !requireExitedOwner && isStaleProcessLock(lockPath)) {
17547
+ try {
17548
+ import_node_fs5.default.unlinkSync(lockPath);
17549
+ } catch {
17604
17550
  }
17605
- } catch (error) {
17606
- throw toPortError(error);
17551
+ continue;
17607
17552
  }
17608
- }
17609
- initConfigKey = configKey;
17610
- initPromise = (async () => {
17611
- await mod.SandboxManager.initialize(config);
17612
- if (!await mod.SandboxManager.waitForNetworkInitialization()) {
17613
- throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.RUNNER_FAILED, "\u6C99\u7BB1\u7F51\u7EDC\u9650\u5236\u672A\u5C31\u7EEA\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
17553
+ if (Date.now() - startedAt >= PROCESS_LOCK_TIMEOUT_MS) {
17554
+ throw new Error(`\u8DE8\u8FDB\u7A0B\u6587\u4EF6\u9501\u7B49\u5F85\u8D85\u65F6\uFF1A${filePath}`);
17614
17555
  }
17615
- })();
17556
+ await waitForProcessLock();
17557
+ }
17558
+ }
17559
+ }
17560
+ function releaseProcessLock(handle) {
17561
+ try {
17562
+ import_node_fs5.default.closeSync(handle.descriptor);
17563
+ } finally {
17616
17564
  try {
17617
- await initPromise;
17618
- } catch (error) {
17619
- initPromise = void 0;
17620
- initConfigKey = void 0;
17621
- await mod.SandboxManager.reset().catch(function ignoreResetFailure() {
17622
- cleanupDiagnostic = "\u6C99\u7BB1\u521D\u59CB\u5316\u5931\u8D25\u540E\u7684 reset \u5931\u8D25";
17623
- });
17624
- windowsManagerOwners.delete(mod.SandboxManager);
17625
- throw toPortError(error);
17565
+ const metadata = JSON.parse(import_node_fs5.default.readFileSync(handle.lockPath, "utf8"));
17566
+ if (metadata.ownerId === handle.ownerId) import_node_fs5.default.unlinkSync(handle.lockPath);
17567
+ } catch {
17626
17568
  }
17627
- return mod;
17628
17569
  }
17629
- const defaultPolicy = {
17630
- mode: "workspace-write",
17631
- workspaceRoot: options.workspaceRoot,
17632
- ...options.tempRoot !== void 0 ? { tempRoot: options.tempRoot } : {},
17633
- allowedDomains: Object.freeze([]),
17634
- deniedRead: Object.freeze([]),
17635
- deniedWrite: Object.freeze([])
17636
- };
17637
- function unavailableReport(diagnostics) {
17638
- return { platform: describePlatform(), backend: "srt", enforcement: "unavailable", installed: false, diagnostics: [...diagnostics] };
17570
+ }
17571
+ async function withFileLock(filePath, operation, options) {
17572
+ const key2 = import_node_path4.default.resolve(filePath);
17573
+ const previous = fileLocks.get(key2) ?? Promise.resolve();
17574
+ let release = () => void 0;
17575
+ const next = new Promise((resolve) => {
17576
+ release = resolve;
17577
+ });
17578
+ const queued = previous.then(() => next);
17579
+ fileLocks.set(key2, queued);
17580
+ try {
17581
+ await previous;
17582
+ const handle = await acquireProcessLock(key2, options?.requireExitedOwner);
17583
+ try {
17584
+ return await operation();
17585
+ } finally {
17586
+ releaseProcessLock(handle);
17587
+ }
17588
+ } finally {
17589
+ release();
17590
+ if (fileLocks.get(key2) === queued) fileLocks.delete(key2);
17639
17591
  }
17640
- return {
17641
- async status() {
17642
- if (shutdown) return unavailableReport(["\u6C99\u7BB1\u5DF2 shutdown"]);
17643
- if (process.platform === "win32") {
17592
+ }
17593
+ var asyncFileLocks = /* @__PURE__ */ new Map();
17594
+ async function acquireAsyncProcessLock(filePath) {
17595
+ await import_promises2.default.mkdir(import_node_path4.default.dirname(filePath), { recursive: true });
17596
+ const lockPath = `${filePath}.lock`;
17597
+ const ownerId = (0, import_node_crypto3.randomUUID)();
17598
+ const startedAt = Date.now();
17599
+ while (true) {
17600
+ try {
17601
+ const descriptor = await import_promises2.default.open(lockPath, "wx");
17602
+ const metadata = { ownerId, pid: process.pid, createdAt: Date.now() };
17603
+ await descriptor.writeFile(JSON.stringify(metadata), "utf8");
17604
+ return { lockPath, ownerId, descriptor };
17605
+ } catch (error) {
17606
+ const code = error.code;
17607
+ if (!isProcessLockContention(code)) throw error;
17608
+ if (await hasExitedProcessLockOwnerAsync(lockPath) || await isStaleProcessLockAsync(lockPath)) {
17644
17609
  try {
17645
- const mod = await ensureModule();
17646
- windowsRunner ??= resolveWindowsSandboxRunner(mod.VENDORED_SRT_WIN_EXE, options.windowsSrtWinExe);
17647
- const report = await readWindowsSandboxCapability({ loadModule: options.loadModule, srtWinExe: windowsRunner });
17648
- if (!report.provisioned) return report;
17649
- if (initPromise) await initPromise;
17650
- else await ensureInitialized(defaultPolicy);
17651
- return { ...report, enforcement: "full", diagnostics: [...report.diagnostics ?? [], "network_fence_verified=true", ...cleanupDiagnostic ? [cleanupDiagnostic] : []] };
17610
+ await import_promises2.default.unlink(lockPath);
17652
17611
  } catch {
17653
- return unavailableReport(["Windows \u6C99\u7BB1\u72B6\u6001\u63A2\u6D4B\u5931\u8D25"]);
17654
17612
  }
17613
+ continue;
17655
17614
  }
17656
- if (process.platform !== "darwin") return unavailableReport([`\u5E73\u53F0 ${process.platform} \u4E0D\u5728\u9996\u53D1\u652F\u6301\u5217\u8868`]);
17657
- try {
17658
- const mod = await ensureInitialized(defaultPolicy);
17659
- const version = readSrtVersion();
17660
- return {
17661
- platform: "macos",
17662
- backend: "srt-seatbelt",
17663
- enforcement: "full",
17664
- installed: true,
17665
- provisioned: true,
17666
- ...version !== void 0 ? { version } : {},
17667
- ...cleanupDiagnostic !== void 0 ? { diagnostics: [cleanupDiagnostic] } : {}
17668
- };
17669
- } catch (error) {
17670
- return unavailableReport([error instanceof import_core10.SandboxPortError ? error.message : "\u6C99\u7BB1\u521D\u59CB\u5316\u5931\u8D25"]);
17671
- }
17672
- },
17673
- async setup() {
17674
- if (shutdown) throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u6267\u884C setup");
17675
- if (process.platform === "darwin") return this.status();
17676
- if (process.platform === "win32") {
17677
- const mod = await ensureModule();
17678
- windowsRunner ??= resolveWindowsSandboxRunner(mod.VENDORED_SRT_WIN_EXE, options.windowsSrtWinExe);
17679
- return runWindowsSandboxSetup({ loadModule: options.loadModule, srtWinExe: windowsRunner });
17680
- }
17681
- throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.UNAVAILABLE, `\u5E73\u53F0 ${process.platform} \u65E0\u6C99\u7BB1 setup \u6D41\u7A0B`);
17682
- },
17683
- async prepare(request) {
17684
- if (shutdown) throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u51C6\u5907\u6267\u884C");
17685
- if (request.policy.workspaceRoot !== void 0 && request.policy.workspaceRoot !== options.workspaceRoot) {
17686
- throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.SCOPE_CONFLICT, "\u6C99\u7BB1\u5DF2\u7ED1\u5B9A\u53E6\u4E00\u5DE5\u4F5C\u533A\uFF0C\u62D2\u7EDD\u5E76\u884C\u591A\u6839\u4F7F\u7528");
17687
- }
17688
- if (process.platform !== "darwin" && process.platform !== "win32") {
17689
- throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u5F53\u524D\u5E73\u53F0\u7684\u547D\u4EE4\u6267\u884C\u8DEF\u5F84\u672A\u901A\u8FC7\u5B9E\u673A\u95E8\u7981\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
17615
+ if (Date.now() - startedAt >= PROCESS_LOCK_TIMEOUT_MS) {
17616
+ throw new Error(`\u8DE8\u8FDB\u7A0B\u6587\u4EF6\u9501\u7B49\u5F85\u8D85\u65F6\uFF1A${filePath}`);
17690
17617
  }
17691
- const mod = await ensureInitialized(request.policy);
17692
- const command = serializePosixCommand(request.program, request.args, request.policy.tempRoot ?? options.tempRoot);
17693
- let wrapped;
17694
- try {
17695
- if (process.platform === "win32") {
17696
- const target = resolveWindowsSandboxCommand(request.program, request.args);
17697
- wrapped = await mod.SandboxManager.wrapWithSandboxArgv("", target, void 0, void 0, request.cwd, { commandId: request.commandId });
17698
- wrapped.argv = finalizeWindowsSandboxArgv(wrapped.argv, target, request.policy.tempRoot ?? options.tempRoot);
17699
- } else {
17700
- wrapped = await mod.SandboxManager.wrapWithSandboxArgv(command, "/bin/bash", void 0, void 0, request.cwd, { commandId: request.commandId });
17701
- }
17702
- } catch (error) {
17703
- throw toPortError(error);
17704
- }
17705
- if (wrapped.argv.length === 0) {
17706
- throw new import_core10.SandboxPortError(import_core10.SANDBOX_ERROR_CODES.RUNNER_FAILED, "\u6C99\u7BB1\u5305\u88C5\u8F93\u51FA\u4E3A\u7A7A\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
17707
- }
17708
- const enforcement = "full";
17709
- activeExecutions.add(request.commandId);
17710
- return {
17711
- executionId: request.commandId,
17712
- executable: wrapped.argv[0],
17713
- args: wrapped.argv.slice(1),
17714
- env: { ...wrapped.env },
17715
- enforcement
17716
- };
17717
- },
17718
- async release(executionId) {
17719
- activeExecutions.delete(executionId);
17720
- if (!module2 || !initPromise) return;
17721
- try {
17722
- module2.SandboxManager.cleanupAfterCommand();
17723
- cleanupDiagnostic = void 0;
17724
- } catch {
17725
- cleanupDiagnostic = "\u6C99\u7BB1\u6309\u547D\u4EE4\u8D44\u6E90\u6E05\u7406\u5931\u8D25\uFF0C\u5DF2\u8BB0\u5F55\u8BCA\u65AD\uFF08\u4E0D\u4E2D\u65AD\u91CA\u653E\uFF09";
17726
- }
17727
- },
17728
- async shutdown() {
17729
- if (shutdown) return;
17730
- shutdown = true;
17731
- if (module2 && initPromise) {
17732
- try {
17733
- await module2.SandboxManager.reset();
17734
- } catch {
17735
- cleanupDiagnostic = "\u6C99\u7BB1 shutdown \u65F6 reset \u5931\u8D25\uFF0C\u53EF\u80FD\u5B58\u5728\u5E73\u53F0\u8D44\u6E90\u6B8B\u7559";
17736
- }
17737
- }
17738
- if (module2 && windowsManagerOwners.get(module2.SandboxManager) === owner) windowsManagerOwners.delete(module2.SandboxManager);
17618
+ await waitForProcessLock();
17739
17619
  }
17740
- };
17620
+ }
17741
17621
  }
17742
- function describePlatform() {
17743
- if (process.platform === "darwin") return "macos";
17744
- if (process.platform === "win32") return "windows";
17745
- if (process.platform === "linux") return "linux";
17746
- return "unknown";
17622
+ async function releaseAsyncProcessLock(handle) {
17623
+ try {
17624
+ await handle.descriptor.close();
17625
+ } finally {
17626
+ try {
17627
+ const metadata = JSON.parse(await import_promises2.default.readFile(handle.lockPath, "utf8"));
17628
+ if (metadata.ownerId === handle.ownerId) await import_promises2.default.unlink(handle.lockPath);
17629
+ } catch {
17630
+ }
17631
+ }
17632
+ }
17633
+ async function withAsyncFileLock(filePath, operation) {
17634
+ const key2 = import_node_path4.default.resolve(filePath);
17635
+ const previous = asyncFileLocks.get(key2) ?? Promise.resolve();
17636
+ let release = () => void 0;
17637
+ const next = new Promise((resolve) => {
17638
+ release = resolve;
17639
+ });
17640
+ const queued = previous.then(() => next);
17641
+ asyncFileLocks.set(key2, queued);
17642
+ try {
17643
+ await previous;
17644
+ const handle = await acquireAsyncProcessLock(key2);
17645
+ try {
17646
+ return await operation();
17647
+ } finally {
17648
+ await releaseAsyncProcessLock(handle);
17649
+ }
17650
+ } finally {
17651
+ release();
17652
+ if (asyncFileLocks.get(key2) === queued) asyncFileLocks.delete(key2);
17653
+ }
17654
+ }
17655
+ function ensureParentDirectory(filePath) {
17656
+ import_node_fs5.default.mkdirSync(import_node_path4.default.dirname(filePath), { recursive: true });
17657
+ }
17658
+ function atomicReplace(filePath, content) {
17659
+ ensureParentDirectory(filePath);
17660
+ const temporaryPath = `${filePath}.${process.pid}.${(0, import_node_crypto3.randomUUID)()}.tmp`;
17661
+ try {
17662
+ import_node_fs5.default.writeFileSync(temporaryPath, content, { encoding: "utf8", flag: "wx" });
17663
+ import_node_fs5.default.renameSync(temporaryPath, filePath);
17664
+ } finally {
17665
+ if (import_node_fs5.default.existsSync(temporaryPath)) import_node_fs5.default.unlinkSync(temporaryPath);
17666
+ }
17667
+ }
17668
+ function safeFilePath(directory, key2, extension) {
17669
+ if (!key2 || key2.includes("/") || key2.includes("\\") || key2 === "." || key2 === "..") {
17670
+ throw new Error("\u6301\u4E45\u5316 ID \u4E0D\u80FD\u5305\u542B\u8DEF\u5F84\u5206\u9694\u7B26");
17671
+ }
17672
+ const canonicalDirectory = import_node_path4.default.resolve(directory);
17673
+ const candidate = import_node_path4.default.resolve(canonicalDirectory, `${key2}${extension}`);
17674
+ const relative = import_node_path4.default.relative(canonicalDirectory, candidate);
17675
+ if (relative === ".." || relative.startsWith(`..${import_node_path4.default.sep}`) || import_node_path4.default.isAbsolute(relative)) {
17676
+ throw new Error("\u6301\u4E45\u5316\u8DEF\u5F84\u8D8A\u51FA\u72B6\u6001\u6839");
17677
+ }
17678
+ return candidate;
17679
+ }
17680
+ function readJsonFile(filePath) {
17681
+ try {
17682
+ return JSON.parse(import_node_fs5.default.readFileSync(filePath, "utf8"));
17683
+ } catch {
17684
+ return null;
17685
+ }
17686
+ }
17687
+ function readJsonLines(filePath) {
17688
+ if (!import_node_fs5.default.existsSync(filePath)) return { values: [], lines: [], diagnostics: [] };
17689
+ const sourceLines = import_node_fs5.default.readFileSync(filePath, "utf8").split("\n");
17690
+ const values = [];
17691
+ const validLines = [];
17692
+ const diagnostics = [];
17693
+ for (let index = 0; index < sourceLines.length; index += 1) {
17694
+ const line = sourceLines[index];
17695
+ if (!line) continue;
17696
+ try {
17697
+ values.push(JSON.parse(line));
17698
+ validLines.push(line);
17699
+ } catch {
17700
+ diagnostics.push({ code: "DURABLE_JSONL_CORRUPTED", line: index + 1, reason: "INVALID_JSON" });
17701
+ }
17702
+ }
17703
+ if (diagnostics.length > 0) {
17704
+ console.warn(`[DURABLE_JSONL_CORRUPTED] file=${import_node_path4.default.basename(filePath)} records=${diagnostics.length} lines=${diagnostics.map((item) => item.line).join(",")}`);
17705
+ }
17706
+ return { values, lines: validLines, diagnostics };
17707
+ }
17708
+ function appendJsonLine(filePath, serialized) {
17709
+ ensureParentDirectory(filePath);
17710
+ import_node_fs5.default.appendFileSync(filePath, `${serialized}
17711
+ `, "utf8");
17712
+ }
17713
+ async function appendUniqueJsonLine(filePath, serialized) {
17714
+ await withFileLock(filePath, () => {
17715
+ const existing = readJsonLines(filePath).lines;
17716
+ if (existing.includes(serialized)) return;
17717
+ appendJsonLine(filePath, serialized);
17718
+ });
17747
17719
  }
17748
17720
 
17749
- // src/node/workspace-adapter.ts
17750
- var import_node_fs9 = __toESM(require("node:fs"));
17751
- var import_node_path8 = __toESM(require("node:path"));
17721
+ // src/node/file-mutation-locks.ts
17722
+ function getNodeFileMutationLockRoot() {
17723
+ return import_node_path5.default.join(import_node_os2.default.userInfo().homedir, ".autopilot", "file-mutation-locks");
17724
+ }
17725
+ async function withNodeFileMutationLocks(canonicalTargets, operation) {
17726
+ const ids = [...new Set(canonicalTargets.map(function targetId(target) {
17727
+ if (!import_node_path5.default.isAbsolute(target)) throw new Error("\u6587\u4EF6\u76EE\u6807\u9501\u5FC5\u987B\u7ED1\u5B9A canonical \u7EDD\u5BF9\u8DEF\u5F84");
17728
+ const normalized = import_node_path5.default.normalize(target);
17729
+ return (0, import_node_crypto4.createHash)("sha256").update(process.platform === "win32" ? normalized.toLowerCase() : normalized).digest("hex");
17730
+ }))].sort();
17731
+ async function lockNext(index) {
17732
+ if (index === ids.length) return operation();
17733
+ return withFileLock(import_node_path5.default.join(getNodeFileMutationLockRoot(), ids[index] + ".target"), function acquireNext() {
17734
+ return lockNext(index + 1);
17735
+ }, { requireExitedOwner: true });
17736
+ }
17737
+ return lockNext(0);
17738
+ }
17752
17739
 
17753
17740
  // src/node/state-root.ts
17754
- var import_node_fs8 = __toESM(require("node:fs"));
17741
+ var import_node_fs7 = __toESM(require("node:fs"));
17755
17742
  var import_node_crypto6 = require("node:crypto");
17756
- var import_node_os2 = __toESM(require("node:os"));
17743
+ var import_node_os3 = __toESM(require("node:os"));
17757
17744
  var import_node_path7 = __toESM(require("node:path"));
17758
17745
 
17759
17746
  // src/node/state-schema-manager.ts
17760
17747
  var import_node_fs6 = __toESM(require("node:fs"));
17761
- var import_node_path5 = __toESM(require("node:path"));
17762
- var import_node_crypto4 = require("node:crypto");
17748
+ var import_node_path6 = __toESM(require("node:path"));
17749
+ var import_node_crypto5 = require("node:crypto");
17763
17750
  function assertPlainStateTree(root) {
17764
17751
  const entry = import_node_fs6.default.lstatSync(root);
17765
17752
  if (entry.isSymbolicLink() || !entry.isDirectory() && !entry.isFile()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
17766
17753
  if (!entry.isDirectory()) return;
17767
17754
  for (const name of import_node_fs6.default.readdirSync(root)) {
17768
17755
  if (name.endsWith(".lock")) throw new NodeStateError("STATE_SCHEMA_BUSY");
17769
- assertPlainStateTree(import_node_path5.default.join(root, name));
17756
+ assertPlainStateTree(import_node_path6.default.join(root, name));
17770
17757
  }
17771
17758
  }
17772
17759
  function acquireSchemaLock(root) {
17773
17760
  const lock = `${root}.schema-lock`;
17774
- import_node_fs6.default.mkdirSync(import_node_path5.default.dirname(root), { recursive: true });
17761
+ import_node_fs6.default.mkdirSync(import_node_path6.default.dirname(root), { recursive: true });
17775
17762
  try {
17776
17763
  const descriptor = import_node_fs6.default.openSync(lock, "wx", 384);
17777
17764
  import_node_fs6.default.writeFileSync(descriptor, String(process.pid));
@@ -17799,7 +17786,7 @@ function hasDurableState(root) {
17799
17786
  });
17800
17787
  }
17801
17788
  function readManifest(root) {
17802
- const filePath = import_node_path5.default.join(root, "schema.json");
17789
+ const filePath = import_node_path6.default.join(root, "schema.json");
17803
17790
  if (!import_node_fs6.default.existsSync(filePath)) return void 0;
17804
17791
  if (import_node_fs6.default.lstatSync(root).isSymbolicLink() || !import_node_fs6.default.lstatSync(filePath).isFile() || import_node_fs6.default.lstatSync(filePath).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
17805
17792
  const content = import_node_fs6.default.readFileSync(filePath, "utf8");
@@ -17819,25 +17806,25 @@ function readManifest(root) {
17819
17806
  function writeManifest(root, schemaVersion, diagnostic) {
17820
17807
  import_node_fs6.default.mkdirSync(root, { recursive: true });
17821
17808
  const manifest = { schemaVersion, ...diagnostic ? { lastMigration: diagnostic } : {} };
17822
- import_node_fs6.default.writeFileSync(import_node_path5.default.join(root, "schema.json"), JSON.stringify(manifest, null, 2), "utf8");
17809
+ import_node_fs6.default.writeFileSync(import_node_path6.default.join(root, "schema.json"), JSON.stringify(manifest, null, 2), "utf8");
17823
17810
  }
17824
17811
  function createBackupPath(root, fromVersion, toVersion) {
17825
- const backupRoot = import_node_path5.default.join(import_node_path5.default.dirname(root), `${import_node_path5.default.basename(root)}.schema-backups`);
17812
+ const backupRoot = import_node_path6.default.join(import_node_path6.default.dirname(root), `${import_node_path6.default.basename(root)}.schema-backups`);
17826
17813
  const timestamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
17827
- return import_node_path5.default.join(backupRoot, `${timestamp2}-v${fromVersion}-to-v${toVersion}-${(0, import_node_crypto4.randomUUID)()}`);
17814
+ return import_node_path6.default.join(backupRoot, `${timestamp2}-v${fromVersion}-to-v${toVersion}-${(0, import_node_crypto5.randomUUID)()}`);
17828
17815
  }
17829
17816
  function backupStateRoot(root, fromVersion, toVersion) {
17830
17817
  if (!hasDurableState(root)) return void 0;
17831
17818
  assertPlainStateTree(root);
17832
17819
  const backupPath = createBackupPath(root, fromVersion, toVersion);
17833
- const backupRoot = import_node_path5.default.dirname(backupPath);
17820
+ const backupRoot = import_node_path6.default.dirname(backupPath);
17834
17821
  if (import_node_fs6.default.existsSync(backupRoot) && import_node_fs6.default.lstatSync(backupRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
17835
17822
  import_node_fs6.default.mkdirSync(backupRoot, { recursive: true });
17836
17823
  import_node_fs6.default.cpSync(root, backupPath, { recursive: true, errorOnExist: true });
17837
17824
  return backupPath;
17838
17825
  }
17839
17826
  function createNodeStateSchemaManager(options) {
17840
- const root = import_node_path5.default.resolve(options.stateRoot);
17827
+ const root = import_node_path6.default.resolve(options.stateRoot);
17841
17828
  const originalRoot = `${root}.schema-original`;
17842
17829
  const stagingRoot = `${root}.schema-staging`;
17843
17830
  function detectVersion() {
@@ -17959,360 +17946,102 @@ function createNodeStateSchemaManager(options) {
17959
17946
  return { detectVersion, migrate, backup, verify, getDiagnostics };
17960
17947
  }
17961
17948
 
17962
- // src/node/file-utils.ts
17963
- var import_node_fs7 = __toESM(require("node:fs"));
17964
- var import_promises2 = __toESM(require("node:fs/promises"));
17965
- var import_node_crypto5 = require("node:crypto");
17966
- var import_node_path6 = __toESM(require("node:path"));
17967
- var fileLocks = /* @__PURE__ */ new Map();
17968
- var PROCESS_LOCK_RETRY_MS = 10;
17969
- var PROCESS_LOCK_TIMEOUT_MS = 3e4;
17970
- var PROCESS_LOCK_STALE_MS = 6e4;
17971
- function waitForProcessLock() {
17972
- return new Promise((resolve) => setTimeout(resolve, PROCESS_LOCK_RETRY_MS));
17973
- }
17974
- function isStaleProcessLock(lockPath) {
17975
- try {
17976
- const metadata = JSON.parse(import_node_fs7.default.readFileSync(lockPath, "utf8"));
17977
- const createdAt = typeof metadata.createdAt === "number" ? metadata.createdAt : import_node_fs7.default.statSync(lockPath).mtimeMs;
17978
- return Date.now() - createdAt > PROCESS_LOCK_STALE_MS;
17979
- } catch {
17980
- try {
17981
- return Date.now() - import_node_fs7.default.statSync(lockPath).mtimeMs > PROCESS_LOCK_STALE_MS;
17982
- } catch {
17983
- return false;
17984
- }
17949
+ // src/node/session-record.ts
17950
+ function normalizeNodeSession(value, id) {
17951
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
17952
+ const session = value;
17953
+ if (session.id !== id || !Number.isFinite(session.createdAt) || !Number.isFinite(session.updatedAt)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
17954
+ const mode = session.productMode ?? "work";
17955
+ if (mode === "chat") {
17956
+ if (session.projectId !== void 0 || !["none", "web", "rag"].includes(session.chatRetrievalMode ?? "")) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
17957
+ } else if (mode !== "work" || session.chatRetrievalMode !== void 0 || typeof session.projectId !== "string" || !session.projectId.trim()) {
17958
+ throw createNodeIdentityError("SESSION_MODE_MISMATCH");
17985
17959
  }
17960
+ return { ...session, productMode: mode };
17986
17961
  }
17987
- async function isStaleProcessLockAsync(lockPath) {
17988
- try {
17989
- const metadata = JSON.parse(await import_promises2.default.readFile(lockPath, "utf8"));
17990
- const createdAt = typeof metadata.createdAt === "number" ? metadata.createdAt : (await import_promises2.default.stat(lockPath)).mtimeMs;
17991
- return Date.now() - createdAt > PROCESS_LOCK_STALE_MS;
17992
- } catch {
17993
- try {
17994
- return Date.now() - (await import_promises2.default.stat(lockPath)).mtimeMs > PROCESS_LOCK_STALE_MS;
17995
- } catch {
17996
- return false;
17997
- }
17998
- }
17962
+ function assertNodeSessionIdentity(previous, next) {
17963
+ if (previous.workContextVersion !== next.workContextVersion) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
17964
+ if (previous.productMode !== next.productMode || previous.projectId !== next.projectId) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
17965
+ if (previous.chatRetrievalMode !== next.chatRetrievalMode) throw createNodeIdentityError("CHAT_RETRIEVAL_MODE_LOCKED");
17999
17966
  }
18000
- function hasExitedProcessLockOwner(lockPath) {
18001
- try {
18002
- const metadata = JSON.parse(import_node_fs7.default.readFileSync(lockPath, "utf8"));
18003
- if (!Number.isInteger(metadata.pid) || metadata.pid <= 0) return false;
18004
- try {
18005
- process.kill(metadata.pid, 0);
18006
- return false;
18007
- } catch (error) {
18008
- return error.code === "ESRCH";
17967
+
17968
+ // src/node/state-root.ts
17969
+ var NODE_STATE_SCHEMA_VERSION = 6;
17970
+ var NODE_WORKSPACE_ID_VERSION = 1;
17971
+ var NODE_STATE_SCHEMA_MIGRATIONS = [{
17972
+ fromVersion: 0,
17973
+ toVersion: 1,
17974
+ migrate() {
17975
+ }
17976
+ }, {
17977
+ fromVersion: 1,
17978
+ toVersion: 2,
17979
+ migrate(stagingRoot) {
17980
+ import_node_fs7.default.mkdirSync(import_node_path7.default.join(stagingRoot, "jobs"), { recursive: true });
17981
+ }
17982
+ }, {
17983
+ fromVersion: 2,
17984
+ toVersion: 3,
17985
+ migrate(stagingRoot) {
17986
+ import_node_fs7.default.mkdirSync(import_node_path7.default.join(stagingRoot, "mutations"), { recursive: true });
17987
+ import_node_fs7.default.mkdirSync(import_node_path7.default.join(stagingRoot, "mutation-blobs"), { recursive: true });
17988
+ import_node_fs7.default.mkdirSync(import_node_path7.default.join(stagingRoot, "mutation-locks"), { recursive: true });
17989
+ import_node_fs7.default.mkdirSync(import_node_path7.default.join(stagingRoot, "undo-transactions"), { recursive: true });
17990
+ }
17991
+ }, {
17992
+ fromVersion: 3,
17993
+ toVersion: 4,
17994
+ migrate(stagingRoot) {
17995
+ import_node_fs7.default.mkdirSync(import_node_path7.default.join(stagingRoot, "questions"), { recursive: true });
17996
+ }
17997
+ }, {
17998
+ fromVersion: 4,
17999
+ toVersion: 5,
18000
+ /** 仅在迁移副本补写产品身份;缺失归属只能采用唯一已有 Project,不能猜工作区。 */
18001
+ migrate(stagingRoot) {
18002
+ const sessions = import_node_path7.default.join(stagingRoot, "sessions");
18003
+ if (!import_node_fs7.default.existsSync(sessions)) return;
18004
+ const projects = import_node_path7.default.join(stagingRoot, "projects");
18005
+ const candidates = import_node_fs7.default.existsSync(projects) ? import_node_fs7.default.readdirSync(projects).filter(
18006
+ /** 只检查现有 Project 记录,不创建新的工作区身份。 */
18007
+ function projectFile(file) {
18008
+ return file.endsWith(".json");
18009
+ }
18010
+ ) : [];
18011
+ for (const file of import_node_fs7.default.readdirSync(sessions)) {
18012
+ if (!file.endsWith(".json")) continue;
18013
+ const target = import_node_path7.default.join(sessions, file);
18014
+ const value = JSON.parse(import_node_fs7.default.readFileSync(target, "utf8"));
18015
+ if (value && value.productMode === void 0 && value.projectId === void 0 && candidates.length === 1) {
18016
+ const project = JSON.parse(import_node_fs7.default.readFileSync(import_node_path7.default.join(projects, candidates[0]), "utf8"));
18017
+ if (project.id === candidates[0].slice(0, -5) && typeof project.workspaceRoot === "string" && project.workspaceRoot) value.projectId = project.id;
18018
+ }
18019
+ const session = normalizeNodeSession(value, file.slice(0, -5));
18020
+ import_node_fs7.default.writeFileSync(target, JSON.stringify(session, null, 2), "utf8");
18009
18021
  }
18010
- } catch {
18011
- return false;
18012
18022
  }
18013
- }
18014
- async function hasExitedProcessLockOwnerAsync(lockPath) {
18023
+ }, {
18024
+ fromVersion: 5,
18025
+ toVersion: 6,
18026
+ migrate() {
18027
+ }
18028
+ }];
18029
+ function canonicalizeNodePath(candidate, baseDirectory = process.cwd()) {
18030
+ const resolved = import_node_path7.default.resolve(baseDirectory, candidate);
18015
18031
  try {
18016
- const metadata = JSON.parse(await import_promises2.default.readFile(lockPath, "utf8"));
18017
- if (!Number.isInteger(metadata.pid) || metadata.pid <= 0) return false;
18018
- try {
18019
- process.kill(metadata.pid, 0);
18020
- return false;
18021
- } catch (error) {
18022
- return error.code === "ESRCH";
18023
- }
18032
+ return import_node_fs7.default.realpathSync.native(resolved);
18024
18033
  } catch {
18025
- return false;
18034
+ return resolved;
18026
18035
  }
18027
18036
  }
18028
- function isProcessLockContention(code) {
18029
- return code === "EEXIST" || code === "EPERM" || code === "EACCES";
18030
- }
18031
- async function acquireProcessLock(filePath) {
18032
- ensureParentDirectory(filePath);
18033
- const lockPath = `${filePath}.lock`;
18034
- const ownerId = (0, import_node_crypto5.randomUUID)();
18035
- const startedAt = Date.now();
18036
- while (true) {
18037
- try {
18038
- const descriptor = import_node_fs7.default.openSync(lockPath, "wx");
18039
- const metadata = { ownerId, pid: process.pid, createdAt: Date.now() };
18040
- import_node_fs7.default.writeFileSync(descriptor, JSON.stringify(metadata), "utf8");
18041
- return { lockPath, ownerId, descriptor };
18042
- } catch (error) {
18043
- const code = error.code;
18044
- if (!isProcessLockContention(code)) throw error;
18045
- if (hasExitedProcessLockOwner(lockPath) || isStaleProcessLock(lockPath)) {
18046
- try {
18047
- import_node_fs7.default.unlinkSync(lockPath);
18048
- } catch {
18049
- }
18050
- continue;
18051
- }
18052
- if (Date.now() - startedAt >= PROCESS_LOCK_TIMEOUT_MS) {
18053
- throw new Error(`\u8DE8\u8FDB\u7A0B\u6587\u4EF6\u9501\u7B49\u5F85\u8D85\u65F6\uFF1A${filePath}`);
18054
- }
18055
- await waitForProcessLock();
18056
- }
18057
- }
18058
- }
18059
- function releaseProcessLock(handle) {
18060
- try {
18061
- import_node_fs7.default.closeSync(handle.descriptor);
18062
- } finally {
18063
- try {
18064
- const metadata = JSON.parse(import_node_fs7.default.readFileSync(handle.lockPath, "utf8"));
18065
- if (metadata.ownerId === handle.ownerId) import_node_fs7.default.unlinkSync(handle.lockPath);
18066
- } catch {
18067
- }
18068
- }
18069
- }
18070
- async function withFileLock(filePath, operation) {
18071
- const key2 = import_node_path6.default.resolve(filePath);
18072
- const previous = fileLocks.get(key2) ?? Promise.resolve();
18073
- let release = () => void 0;
18074
- const next = new Promise((resolve) => {
18075
- release = resolve;
18076
- });
18077
- const queued = previous.then(() => next);
18078
- fileLocks.set(key2, queued);
18079
- try {
18080
- await previous;
18081
- const handle = await acquireProcessLock(key2);
18082
- try {
18083
- return await operation();
18084
- } finally {
18085
- releaseProcessLock(handle);
18086
- }
18087
- } finally {
18088
- release();
18089
- if (fileLocks.get(key2) === queued) fileLocks.delete(key2);
18090
- }
18091
- }
18092
- var asyncFileLocks = /* @__PURE__ */ new Map();
18093
- async function acquireAsyncProcessLock(filePath) {
18094
- await import_promises2.default.mkdir(import_node_path6.default.dirname(filePath), { recursive: true });
18095
- const lockPath = `${filePath}.lock`;
18096
- const ownerId = (0, import_node_crypto5.randomUUID)();
18097
- const startedAt = Date.now();
18098
- while (true) {
18099
- try {
18100
- const descriptor = await import_promises2.default.open(lockPath, "wx");
18101
- const metadata = { ownerId, pid: process.pid, createdAt: Date.now() };
18102
- await descriptor.writeFile(JSON.stringify(metadata), "utf8");
18103
- return { lockPath, ownerId, descriptor };
18104
- } catch (error) {
18105
- const code = error.code;
18106
- if (!isProcessLockContention(code)) throw error;
18107
- if (await hasExitedProcessLockOwnerAsync(lockPath) || await isStaleProcessLockAsync(lockPath)) {
18108
- try {
18109
- await import_promises2.default.unlink(lockPath);
18110
- } catch {
18111
- }
18112
- continue;
18113
- }
18114
- if (Date.now() - startedAt >= PROCESS_LOCK_TIMEOUT_MS) {
18115
- throw new Error(`\u8DE8\u8FDB\u7A0B\u6587\u4EF6\u9501\u7B49\u5F85\u8D85\u65F6\uFF1A${filePath}`);
18116
- }
18117
- await waitForProcessLock();
18118
- }
18119
- }
18120
- }
18121
- async function releaseAsyncProcessLock(handle) {
18122
- try {
18123
- await handle.descriptor.close();
18124
- } finally {
18125
- try {
18126
- const metadata = JSON.parse(await import_promises2.default.readFile(handle.lockPath, "utf8"));
18127
- if (metadata.ownerId === handle.ownerId) await import_promises2.default.unlink(handle.lockPath);
18128
- } catch {
18129
- }
18130
- }
18131
- }
18132
- async function withAsyncFileLock(filePath, operation) {
18133
- const key2 = import_node_path6.default.resolve(filePath);
18134
- const previous = asyncFileLocks.get(key2) ?? Promise.resolve();
18135
- let release = () => void 0;
18136
- const next = new Promise((resolve) => {
18137
- release = resolve;
18138
- });
18139
- const queued = previous.then(() => next);
18140
- asyncFileLocks.set(key2, queued);
18141
- try {
18142
- await previous;
18143
- const handle = await acquireAsyncProcessLock(key2);
18144
- try {
18145
- return await operation();
18146
- } finally {
18147
- await releaseAsyncProcessLock(handle);
18148
- }
18149
- } finally {
18150
- release();
18151
- if (asyncFileLocks.get(key2) === queued) asyncFileLocks.delete(key2);
18152
- }
18153
- }
18154
- function ensureParentDirectory(filePath) {
18155
- import_node_fs7.default.mkdirSync(import_node_path6.default.dirname(filePath), { recursive: true });
18156
- }
18157
- function atomicReplace(filePath, content) {
18158
- ensureParentDirectory(filePath);
18159
- const temporaryPath = `${filePath}.${process.pid}.${(0, import_node_crypto5.randomUUID)()}.tmp`;
18160
- try {
18161
- import_node_fs7.default.writeFileSync(temporaryPath, content, { encoding: "utf8", flag: "wx" });
18162
- import_node_fs7.default.renameSync(temporaryPath, filePath);
18163
- } finally {
18164
- if (import_node_fs7.default.existsSync(temporaryPath)) import_node_fs7.default.unlinkSync(temporaryPath);
18165
- }
18166
- }
18167
- function safeFilePath(directory, key2, extension) {
18168
- if (!key2 || key2.includes("/") || key2.includes("\\") || key2 === "." || key2 === "..") {
18169
- throw new Error("\u6301\u4E45\u5316 ID \u4E0D\u80FD\u5305\u542B\u8DEF\u5F84\u5206\u9694\u7B26");
18170
- }
18171
- const canonicalDirectory = import_node_path6.default.resolve(directory);
18172
- const candidate = import_node_path6.default.resolve(canonicalDirectory, `${key2}${extension}`);
18173
- const relative = import_node_path6.default.relative(canonicalDirectory, candidate);
18174
- if (relative === ".." || relative.startsWith(`..${import_node_path6.default.sep}`) || import_node_path6.default.isAbsolute(relative)) {
18175
- throw new Error("\u6301\u4E45\u5316\u8DEF\u5F84\u8D8A\u51FA\u72B6\u6001\u6839");
18176
- }
18177
- return candidate;
18178
- }
18179
- function readJsonFile(filePath) {
18180
- try {
18181
- return JSON.parse(import_node_fs7.default.readFileSync(filePath, "utf8"));
18182
- } catch {
18183
- return null;
18184
- }
18185
- }
18186
- function readJsonLines(filePath) {
18187
- if (!import_node_fs7.default.existsSync(filePath)) return { values: [], lines: [], diagnostics: [] };
18188
- const sourceLines = import_node_fs7.default.readFileSync(filePath, "utf8").split("\n");
18189
- const values = [];
18190
- const validLines = [];
18191
- const diagnostics = [];
18192
- for (let index = 0; index < sourceLines.length; index += 1) {
18193
- const line = sourceLines[index];
18194
- if (!line) continue;
18195
- try {
18196
- values.push(JSON.parse(line));
18197
- validLines.push(line);
18198
- } catch {
18199
- diagnostics.push({ code: "DURABLE_JSONL_CORRUPTED", line: index + 1, reason: "INVALID_JSON" });
18200
- }
18201
- }
18202
- if (diagnostics.length > 0) {
18203
- console.warn(`[DURABLE_JSONL_CORRUPTED] file=${import_node_path6.default.basename(filePath)} records=${diagnostics.length} lines=${diagnostics.map((item) => item.line).join(",")}`);
18204
- }
18205
- return { values, lines: validLines, diagnostics };
18206
- }
18207
- function appendJsonLine(filePath, serialized) {
18208
- ensureParentDirectory(filePath);
18209
- import_node_fs7.default.appendFileSync(filePath, `${serialized}
18210
- `, "utf8");
18211
- }
18212
- async function appendUniqueJsonLine(filePath, serialized) {
18213
- await withFileLock(filePath, () => {
18214
- const existing = readJsonLines(filePath).lines;
18215
- if (existing.includes(serialized)) return;
18216
- appendJsonLine(filePath, serialized);
18217
- });
18218
- }
18219
-
18220
- // src/node/session-record.ts
18221
- function normalizeNodeSession(value, id) {
18222
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
18223
- const session = value;
18224
- if (session.id !== id || !Number.isFinite(session.createdAt) || !Number.isFinite(session.updatedAt)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
18225
- const mode = session.productMode ?? "work";
18226
- if (mode === "chat") {
18227
- if (session.projectId !== void 0 || !["none", "web", "rag"].includes(session.chatRetrievalMode ?? "")) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
18228
- } else if (mode !== "work" || session.chatRetrievalMode !== void 0 || typeof session.projectId !== "string" || !session.projectId.trim()) {
18229
- throw createNodeIdentityError("SESSION_MODE_MISMATCH");
18230
- }
18231
- return { ...session, productMode: mode };
18232
- }
18233
- function assertNodeSessionIdentity(previous, next) {
18234
- if (previous.workContextVersion !== next.workContextVersion) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
18235
- if (previous.productMode !== next.productMode || previous.projectId !== next.projectId) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
18236
- if (previous.chatRetrievalMode !== next.chatRetrievalMode) throw createNodeIdentityError("CHAT_RETRIEVAL_MODE_LOCKED");
18237
- }
18238
-
18239
- // src/node/state-root.ts
18240
- var NODE_STATE_SCHEMA_VERSION = 6;
18241
- var NODE_WORKSPACE_ID_VERSION = 1;
18242
- var NODE_STATE_SCHEMA_MIGRATIONS = [{
18243
- fromVersion: 0,
18244
- toVersion: 1,
18245
- migrate() {
18246
- }
18247
- }, {
18248
- fromVersion: 1,
18249
- toVersion: 2,
18250
- migrate(stagingRoot) {
18251
- import_node_fs8.default.mkdirSync(import_node_path7.default.join(stagingRoot, "jobs"), { recursive: true });
18252
- }
18253
- }, {
18254
- fromVersion: 2,
18255
- toVersion: 3,
18256
- migrate(stagingRoot) {
18257
- import_node_fs8.default.mkdirSync(import_node_path7.default.join(stagingRoot, "mutations"), { recursive: true });
18258
- import_node_fs8.default.mkdirSync(import_node_path7.default.join(stagingRoot, "mutation-blobs"), { recursive: true });
18259
- import_node_fs8.default.mkdirSync(import_node_path7.default.join(stagingRoot, "mutation-locks"), { recursive: true });
18260
- import_node_fs8.default.mkdirSync(import_node_path7.default.join(stagingRoot, "undo-transactions"), { recursive: true });
18261
- }
18262
- }, {
18263
- fromVersion: 3,
18264
- toVersion: 4,
18265
- migrate(stagingRoot) {
18266
- import_node_fs8.default.mkdirSync(import_node_path7.default.join(stagingRoot, "questions"), { recursive: true });
18267
- }
18268
- }, {
18269
- fromVersion: 4,
18270
- toVersion: 5,
18271
- /** 仅在迁移副本补写产品身份;缺失归属只能采用唯一已有 Project,不能猜工作区。 */
18272
- migrate(stagingRoot) {
18273
- const sessions = import_node_path7.default.join(stagingRoot, "sessions");
18274
- if (!import_node_fs8.default.existsSync(sessions)) return;
18275
- const projects = import_node_path7.default.join(stagingRoot, "projects");
18276
- const candidates = import_node_fs8.default.existsSync(projects) ? import_node_fs8.default.readdirSync(projects).filter(
18277
- /** 只检查现有 Project 记录,不创建新的工作区身份。 */
18278
- function projectFile(file) {
18279
- return file.endsWith(".json");
18280
- }
18281
- ) : [];
18282
- for (const file of import_node_fs8.default.readdirSync(sessions)) {
18283
- if (!file.endsWith(".json")) continue;
18284
- const target = import_node_path7.default.join(sessions, file);
18285
- const value = JSON.parse(import_node_fs8.default.readFileSync(target, "utf8"));
18286
- if (value && value.productMode === void 0 && value.projectId === void 0 && candidates.length === 1) {
18287
- const project = JSON.parse(import_node_fs8.default.readFileSync(import_node_path7.default.join(projects, candidates[0]), "utf8"));
18288
- if (project.id === candidates[0].slice(0, -5) && typeof project.workspaceRoot === "string" && project.workspaceRoot) value.projectId = project.id;
18289
- }
18290
- const session = normalizeNodeSession(value, file.slice(0, -5));
18291
- import_node_fs8.default.writeFileSync(target, JSON.stringify(session, null, 2), "utf8");
18292
- }
18293
- }
18294
- }, {
18295
- fromVersion: 5,
18296
- toVersion: 6,
18297
- migrate() {
18298
- }
18299
- }];
18300
- function canonicalizeNodePath(candidate, baseDirectory = process.cwd()) {
18301
- const resolved = import_node_path7.default.resolve(baseDirectory, candidate);
18302
- try {
18303
- return import_node_fs8.default.realpathSync.native(resolved);
18304
- } catch {
18305
- return resolved;
18306
- }
18307
- }
18308
- function createNodeWorkspaceId(workspaceRoot, baseDirectory) {
18309
- const canonicalRoot = canonicalizeNodePath(workspaceRoot, baseDirectory);
18310
- const digest2 = (0, import_node_crypto6.createHash)("sha256").update(canonicalRoot).digest("hex").slice(0, 24);
18311
- return `v${NODE_WORKSPACE_ID_VERSION}-${digest2}`;
18037
+ function createNodeWorkspaceId(workspaceRoot, baseDirectory) {
18038
+ const canonicalRoot = canonicalizeNodePath(workspaceRoot, baseDirectory);
18039
+ const digest2 = (0, import_node_crypto6.createHash)("sha256").update(canonicalRoot).digest("hex").slice(0, 24);
18040
+ return `v${NODE_WORKSPACE_ID_VERSION}-${digest2}`;
18312
18041
  }
18313
18042
  function resolveNodeGlobalStateRoot(options = {}) {
18314
18043
  const baseDirectory = options.cwd ?? process.cwd();
18315
- const defaultRoot = process.env.LOCALAPPDATA ? import_node_path7.default.join(process.env.LOCALAPPDATA, "autopilot-agent") : import_node_path7.default.join(import_node_os2.default.homedir(), ".autopilot-agent");
18044
+ const defaultRoot = process.env.LOCALAPPDATA ? import_node_path7.default.join(process.env.LOCALAPPDATA, "autopilot-agent") : import_node_path7.default.join(import_node_os3.default.homedir(), ".autopilot-agent");
18316
18045
  return canonicalizeNodePath(options.globalStateRoot ?? defaultRoot, baseDirectory);
18317
18046
  }
18318
18047
  function resolveNodeStateRoot(options = {}) {
@@ -18346,57 +18075,302 @@ function getNodeStatePaths(stateRoot) {
18346
18075
  questionsDir: import_node_path7.default.join(root, "questions")
18347
18076
  };
18348
18077
  }
18349
- function assertNodeStateSchema(stateRoot) {
18350
- const paths = getNodeStatePaths(stateRoot);
18351
- if (!import_node_fs8.default.existsSync(paths.schemaFile)) return;
18352
- createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS }).verify();
18353
- }
18354
- function ensureNodeStateRoot(stateRoot) {
18355
- return initializeNodeStateRoot(stateRoot);
18356
- }
18357
- function initializeNodeStateRoot(stateRoot) {
18358
- try {
18359
- if (import_node_fs8.default.existsSync(stateRoot) && import_node_fs8.default.lstatSync(stateRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
18360
- const paths = getNodeStatePaths(stateRoot);
18361
- const manager = createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS });
18362
- manager.migrate();
18363
- return paths;
18364
- } catch (error) {
18365
- throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
18366
- }
18367
- }
18368
- function getNodeStateSchemaDiagnostic(stateRoot) {
18369
- const paths = getNodeStatePaths(stateRoot);
18370
- return createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS }).getDiagnostics();
18371
- }
18372
- function getNodeStateCorruptionDiagnostics(stateRoot) {
18373
- const paths = getNodeStatePaths(stateRoot);
18374
- const directories = [paths.approvalsDir, paths.checkpointsDir, paths.inboxDir, paths.transcriptsDir, paths.questionsDir];
18375
- const diagnostics = [];
18376
- for (const directory of directories) {
18377
- if (!import_node_fs8.default.existsSync(directory)) continue;
18378
- for (const entry of import_node_fs8.default.readdirSync(directory).filter((file) => file.endsWith(".jsonl"))) {
18379
- const filePath = import_node_path7.default.join(directory, entry);
18380
- const result = readJsonLines(filePath);
18381
- for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file: import_node_path7.default.relative(paths.root, filePath) });
18382
- }
18383
- }
18384
- return diagnostics;
18078
+ function assertNodeStateSchema(stateRoot) {
18079
+ const paths = getNodeStatePaths(stateRoot);
18080
+ if (!import_node_fs7.default.existsSync(paths.schemaFile)) return;
18081
+ createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS }).verify();
18082
+ }
18083
+ function ensureNodeStateRoot(stateRoot) {
18084
+ return initializeNodeStateRoot(stateRoot);
18085
+ }
18086
+ function initializeNodeStateRoot(stateRoot) {
18087
+ try {
18088
+ if (import_node_fs7.default.existsSync(stateRoot) && import_node_fs7.default.lstatSync(stateRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
18089
+ const paths = getNodeStatePaths(stateRoot);
18090
+ const manager = createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS });
18091
+ manager.migrate();
18092
+ return paths;
18093
+ } catch (error) {
18094
+ throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
18095
+ }
18096
+ }
18097
+ function getNodeStateSchemaDiagnostic(stateRoot) {
18098
+ const paths = getNodeStatePaths(stateRoot);
18099
+ return createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS }).getDiagnostics();
18100
+ }
18101
+ function getNodeStateCorruptionDiagnostics(stateRoot) {
18102
+ const paths = getNodeStatePaths(stateRoot);
18103
+ const directories = [paths.approvalsDir, paths.checkpointsDir, paths.inboxDir, paths.transcriptsDir, paths.questionsDir];
18104
+ const diagnostics = [];
18105
+ for (const directory of directories) {
18106
+ if (!import_node_fs7.default.existsSync(directory)) continue;
18107
+ for (const entry of import_node_fs7.default.readdirSync(directory).filter((file) => file.endsWith(".jsonl"))) {
18108
+ const filePath = import_node_path7.default.join(directory, entry);
18109
+ const result = readJsonLines(filePath);
18110
+ for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file: import_node_path7.default.relative(paths.root, filePath) });
18111
+ }
18112
+ }
18113
+ return diagnostics;
18114
+ }
18115
+
18116
+ // src/node/sandbox/node-sandbox-port.ts
18117
+ var managerOwners = /* @__PURE__ */ new WeakMap();
18118
+ function posixQuote(value) {
18119
+ return `'${value.replace(/'/g, `'\\''`)}'`;
18120
+ }
18121
+ function serializePosixCommand(program, args, tempRoot) {
18122
+ const command = [posixQuote(program), ...args.map(posixQuote)].join(" ");
18123
+ return tempRoot !== void 0 ? `TMPDIR=${posixQuote(tempRoot)} ${command}` : command;
18124
+ }
18125
+ function buildSrtRuntimeConfig(policy) {
18126
+ if ("externalWriteCapability" in policy && policy.externalWriteCapability !== void 0) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u5F53\u524D\u5E73\u53F0\u672A\u8BC1\u660E\u7CBE\u786E\u5916\u90E8\u6587\u4EF6\u5199\u8FB9\u754C\uFF0C\u4E0D\u80FD\u63D0\u5347\u7236\u76EE\u5F55\u5199\u6839");
18127
+ return {
18128
+ network: {
18129
+ allowedDomains: [...policy.allowedDomains],
18130
+ deniedDomains: []
18131
+ },
18132
+ filesystem: {
18133
+ denyRead: [...policy.deniedRead],
18134
+ // 所有可写模式仅授予工作区与受控 temp;模式本身不授予任何外部修改能力。
18135
+ allowWrite: policy.mode !== "read-only" && policy.workspaceRoot !== void 0 ? [.../* @__PURE__ */ new Set([policy.workspaceRoot, ...policy.tempRoot !== void 0 ? [policy.tempRoot] : []])] : [],
18136
+ denyWrite: [...policy.deniedWrite]
18137
+ },
18138
+ allowAppleEvents: false
18139
+ };
18140
+ }
18141
+ function formatSandboxFailureDiagnostic(phase, error) {
18142
+ const source = error && typeof error === "object" ? error : {};
18143
+ const code = typeof source.code === "string" && /^(EPERM|EACCES|ENOENT|ENOTDIR|EINVAL|EBUSY|ETIMEDOUT|not_provisioned)$/.test(source.code) ? source.code : void 0;
18144
+ const win32 = typeof source.win32Code === "number" && Number.isSafeInteger(source.win32Code) && source.win32Code >= 0 && source.win32Code <= 4294967295 ? `0x${source.win32Code.toString(16).padStart(8, "0")}` : void 0;
18145
+ return [`phase=${phase}`, ...code ? [`cause=${code}`] : [], ...win32 ? [`win32=${win32}`] : []].join(";");
18146
+ }
18147
+ function createNodeSandboxPort(options) {
18148
+ let module2;
18149
+ let initPromise;
18150
+ let initConfigKey;
18151
+ let shutdown = false;
18152
+ let cleanupDiagnostic;
18153
+ const activeExecutions = /* @__PURE__ */ new Set();
18154
+ const owner = {};
18155
+ let operationTail = Promise.resolve();
18156
+ function serializeOperation(operation) {
18157
+ const result = operationTail.then(operation);
18158
+ operationTail = result.catch(function retainQueue() {
18159
+ });
18160
+ return result;
18161
+ }
18162
+ function protectAuthority(policy) {
18163
+ const settingsRoot = import_node_path8.default.join(options.workspaceRoot, ".autopilot");
18164
+ const writes = [getNodeFileMutationLockRoot(), ...["settings.json", "settings.local.json", "mcp.json"].map(function settingsPath(file) {
18165
+ return import_node_path8.default.join(settingsRoot, file);
18166
+ })];
18167
+ const state = options.stateRoot ? [options.stateRoot, canonicalizeNodePath(options.stateRoot)] : [];
18168
+ return { ...policy, deniedRead: [.../* @__PURE__ */ new Set([...policy.deniedRead, ...state])], deniedWrite: [.../* @__PURE__ */ new Set([...policy.deniedWrite, ...state, ...writes, ...writes.map(function canonical(candidate) {
18169
+ return canonicalizeNodePath(candidate);
18170
+ })])] };
18171
+ }
18172
+ async function ensureModule() {
18173
+ if (!module2) {
18174
+ try {
18175
+ module2 = await (options.loadModule ?? loadSrtRuntimeSurface)();
18176
+ } catch (error) {
18177
+ throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, formatSandboxFailureDiagnostic("module-load", error));
18178
+ }
18179
+ }
18180
+ return module2;
18181
+ }
18182
+ function toPortError(error, phase, fallbackCode = import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE) {
18183
+ if (error instanceof import_core9.SandboxPortError && error.message.startsWith("phase=")) return error;
18184
+ return new import_core9.SandboxPortError(error instanceof import_core9.SandboxPortError ? error.code : fallbackCode, formatSandboxFailureDiagnostic(phase, error));
18185
+ }
18186
+ async function ensureInitialized(policy) {
18187
+ if (shutdown) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u521D\u59CB\u5316");
18188
+ if (cleanupDiagnostic) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.CLEANUP_FAILED, "\u6C99\u7BB1\u6E05\u7406\u672A\u786E\u8BA4\uFF0C\u7981\u6B62\u7EE7\u7EED\u6267\u884C");
18189
+ const mod = await ensureModule();
18190
+ if (!mod.SandboxManager.isSupportedPlatform()) {
18191
+ throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, `\u5F53\u524D\u5E73\u53F0 ${process.platform} \u4E0D\u88AB\u6C99\u7BB1 backend \u652F\u6301`);
18192
+ }
18193
+ const dependencies = mod.SandboxManager.checkDependencies();
18194
+ if (dependencies.errors.length > 0) {
18195
+ throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u6C99\u7BB1\u5E73\u53F0\u4F9D\u8D56\u7F3A\u5931\uFF0C\u65E0\u6CD5\u63D0\u4F9B\u5DF2\u9694\u79BB\u6267\u884C");
18196
+ }
18197
+ const currentOwner = managerOwners.get(mod.SandboxManager);
18198
+ if (currentOwner !== void 0 && currentOwner !== owner) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.SCOPE_CONFLICT, "\u5171\u4EAB\u6C99\u7BB1\u5DF2\u88AB\u53E6\u4E00 Port \u7ED1\u5B9A\uFF0C\u62D2\u7EDD\u7B56\u7565\u6DF7\u7528");
18199
+ const protectedPolicy = protectAuthority(policy);
18200
+ const config = buildSrtRuntimeConfig(protectedPolicy);
18201
+ const configKey = JSON.stringify(config);
18202
+ if (initPromise && configKey === initConfigKey) {
18203
+ await initPromise;
18204
+ return mod;
18205
+ }
18206
+ if (initPromise) {
18207
+ try {
18208
+ await initPromise;
18209
+ if (activeExecutions.size > 0) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.SCOPE_CONFLICT, "\u5B58\u5728\u6D3B\u52A8\u6C99\u7BB1\u6267\u884C\uFF0C\u62D2\u7EDD\u5207\u6362\u5171\u4EAB\u7B56\u7565");
18210
+ mod.SandboxManager.updateConfig(config);
18211
+ initConfigKey = configKey;
18212
+ return mod;
18213
+ } catch (error) {
18214
+ throw toPortError(error, "initialize");
18215
+ }
18216
+ }
18217
+ managerOwners.set(mod.SandboxManager, owner);
18218
+ initConfigKey = configKey;
18219
+ initPromise = (async () => {
18220
+ await mod.SandboxManager.initialize(config);
18221
+ if (!await mod.SandboxManager.waitForNetworkInitialization()) {
18222
+ throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.RUNNER_FAILED, "\u6C99\u7BB1\u7F51\u7EDC\u9650\u5236\u672A\u5C31\u7EEA\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
18223
+ }
18224
+ })();
18225
+ try {
18226
+ await initPromise;
18227
+ } catch (error) {
18228
+ initPromise = void 0;
18229
+ initConfigKey = void 0;
18230
+ await mod.SandboxManager.reset().catch(function ignoreResetFailure() {
18231
+ cleanupDiagnostic = "\u6C99\u7BB1\u521D\u59CB\u5316\u5931\u8D25\u540E\u7684 reset \u5931\u8D25";
18232
+ });
18233
+ if (!cleanupDiagnostic) managerOwners.delete(mod.SandboxManager);
18234
+ throw toPortError(error, "initialize");
18235
+ }
18236
+ return mod;
18237
+ }
18238
+ const defaultPolicy = {
18239
+ mode: "workspace-write",
18240
+ workspaceRoot: options.workspaceRoot,
18241
+ ...options.tempRoot !== void 0 ? { tempRoot: options.tempRoot } : {},
18242
+ allowedDomains: Object.freeze([]),
18243
+ deniedRead: Object.freeze([]),
18244
+ deniedWrite: Object.freeze([])
18245
+ };
18246
+ function unavailableReport(diagnostics) {
18247
+ return { platform: describePlatform(), backend: "srt", enforcement: "unavailable", installed: false, diagnostics: [...diagnostics] };
18248
+ }
18249
+ return {
18250
+ async status() {
18251
+ return serializeOperation(async function statusLocked() {
18252
+ if (shutdown) return unavailableReport(["\u6C99\u7BB1\u5DF2 shutdown"]);
18253
+ if (cleanupDiagnostic) return unavailableReport([cleanupDiagnostic]);
18254
+ if (process.platform !== "darwin") return unavailableReport([`\u5E73\u53F0 ${process.platform} \u4E0D\u5728\u652F\u6301\u5217\u8868`]);
18255
+ try {
18256
+ const mod = await ensureInitialized(defaultPolicy);
18257
+ const version = readSrtVersion();
18258
+ return {
18259
+ platform: "macos",
18260
+ backend: "srt-seatbelt",
18261
+ enforcement: "full",
18262
+ installed: true,
18263
+ provisioned: true,
18264
+ ...version !== void 0 ? { version } : {},
18265
+ ...cleanupDiagnostic !== void 0 ? { diagnostics: [cleanupDiagnostic] } : {}
18266
+ };
18267
+ } catch (error) {
18268
+ return unavailableReport([error instanceof import_core9.SandboxPortError ? error.message : "\u6C99\u7BB1\u521D\u59CB\u5316\u5931\u8D25"]);
18269
+ }
18270
+ });
18271
+ },
18272
+ async setup() {
18273
+ if (shutdown) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u6267\u884C setup");
18274
+ if (activeExecutions.size > 0) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.SCOPE_CONFLICT, "\u4ECD\u6709\u6D3B\u52A8\u6267\u884C\uFF0C\u7981\u6B62\u6267\u884C\u7CFB\u7EDF setup");
18275
+ if (process.platform === "darwin") return this.status();
18276
+ throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, `\u5E73\u53F0 ${process.platform} \u65E0\u6C99\u7BB1 setup \u6D41\u7A0B`);
18277
+ },
18278
+ async prepare(request) {
18279
+ return serializeOperation(async function prepareLocked() {
18280
+ if ("externalWriteCapability" in request.policy && request.policy.externalWriteCapability !== void 0) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u5916\u90E8\u7CBE\u786E\u6587\u4EF6\u80FD\u529B\u5C1A\u672A\u901A\u8FC7 OS \u95E8\u7981\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
18281
+ if (shutdown) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u51C6\u5907\u6267\u884C");
18282
+ if (!options.stateRoot) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u672A\u7ED1\u5B9A\u6388\u6743\u72B6\u6001\u4FDD\u62A4\u57DF\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
18283
+ if (activeExecutions.has(request.commandId)) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.SCOPE_CONFLICT, "\u6267\u884C\u5DF2\u7ED1\u5B9A\uFF0C\u7981\u6B62\u590D\u7528\u6D3B\u52A8 executionId");
18284
+ if (request.policy.workspaceRoot !== void 0 && request.policy.workspaceRoot !== options.workspaceRoot) {
18285
+ throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.SCOPE_CONFLICT, "\u6C99\u7BB1\u5DF2\u7ED1\u5B9A\u53E6\u4E00\u5DE5\u4F5C\u533A\uFF0C\u62D2\u7EDD\u5E76\u884C\u591A\u6839\u4F7F\u7528");
18286
+ }
18287
+ if (process.platform !== "darwin") {
18288
+ throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.UNAVAILABLE, "\u5F53\u524D\u5E73\u53F0\u7684\u547D\u4EE4\u6267\u884C\u8DEF\u5F84\u672A\u901A\u8FC7\u5B9E\u673A\u95E8\u7981\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
18289
+ }
18290
+ const mod = await ensureInitialized(request.policy);
18291
+ activeExecutions.add(request.commandId);
18292
+ try {
18293
+ const command = serializePosixCommand(request.program, request.args, request.policy.tempRoot ?? options.tempRoot);
18294
+ let wrapped;
18295
+ try {
18296
+ wrapped = await mod.SandboxManager.wrapWithSandboxArgv(command, "/bin/bash", void 0, void 0, request.cwd, { commandId: request.commandId });
18297
+ } catch (error) {
18298
+ throw toPortError(error, "wrap", import_core9.SANDBOX_ERROR_CODES.RUNNER_FAILED);
18299
+ }
18300
+ if (wrapped.argv.length === 0) {
18301
+ throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.RUNNER_FAILED, "\u6C99\u7BB1\u5305\u88C5\u8F93\u51FA\u4E3A\u7A7A\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
18302
+ }
18303
+ const enforcement = "full";
18304
+ return {
18305
+ executionId: request.commandId,
18306
+ executable: wrapped.argv[0],
18307
+ args: wrapped.argv.slice(1),
18308
+ env: { ...wrapped.env },
18309
+ enforcement
18310
+ };
18311
+ } catch (error) {
18312
+ activeExecutions.delete(request.commandId);
18313
+ try {
18314
+ mod.SandboxManager.cleanupAfterCommand();
18315
+ } catch {
18316
+ cleanupDiagnostic = "\u6C99\u7BB1\u5305\u88C5\u5931\u8D25\u540E\u7684\u6E05\u7406\u672A\u786E\u8BA4";
18317
+ }
18318
+ throw error;
18319
+ }
18320
+ });
18321
+ },
18322
+ async release(executionId) {
18323
+ return serializeOperation(async function releaseLocked() {
18324
+ if (!activeExecutions.has(executionId)) return;
18325
+ activeExecutions.delete(executionId);
18326
+ if (!module2 || !initPromise) return;
18327
+ try {
18328
+ module2.SandboxManager.cleanupAfterCommand();
18329
+ } catch {
18330
+ cleanupDiagnostic = "\u6C99\u7BB1\u6309\u547D\u4EE4\u8D44\u6E90\u6E05\u7406\u5931\u8D25\uFF0C\u5DF2\u8BB0\u5F55\u8BCA\u65AD\uFF08\u4E0D\u4E2D\u65AD\u91CA\u653E\uFF09";
18331
+ }
18332
+ });
18333
+ },
18334
+ async shutdown() {
18335
+ return serializeOperation(async function shutdownLocked() {
18336
+ if (shutdown) return;
18337
+ if (activeExecutions.size > 0) throw new import_core9.SandboxPortError(import_core9.SANDBOX_ERROR_CODES.CLEANUP_FAILED, "\u4ECD\u6709\u6D3B\u52A8\u6267\u884C\uFF0C\u7981\u6B62\u63D0\u524D shutdown");
18338
+ shutdown = true;
18339
+ if (module2 && initPromise) {
18340
+ try {
18341
+ await module2.SandboxManager.reset();
18342
+ cleanupDiagnostic = void 0;
18343
+ } catch {
18344
+ cleanupDiagnostic = "\u6C99\u7BB1 shutdown \u65F6 reset \u5931\u8D25\uFF0C\u53EF\u80FD\u5B58\u5728\u5E73\u53F0\u8D44\u6E90\u6B8B\u7559";
18345
+ }
18346
+ }
18347
+ if (module2 && !cleanupDiagnostic && managerOwners.get(module2.SandboxManager) === owner) managerOwners.delete(module2.SandboxManager);
18348
+ });
18349
+ }
18350
+ };
18351
+ }
18352
+ function describePlatform() {
18353
+ if (process.platform === "darwin") return "macos";
18354
+ if (process.platform === "win32") return "windows";
18355
+ if (process.platform === "linux") return "linux";
18356
+ return "unknown";
18385
18357
  }
18386
18358
 
18387
18359
  // src/node/workspace-adapter.ts
18360
+ var import_node_fs8 = __toESM(require("node:fs"));
18361
+ var import_node_path9 = __toESM(require("node:path"));
18388
18362
  function findWorkspaceRoot(startDirectory) {
18389
18363
  let current = canonicalizeNodePath(startDirectory);
18390
18364
  while (true) {
18391
- const manifestPath = import_node_path8.default.join(current, "package.json");
18392
- if (import_node_fs9.default.existsSync(manifestPath)) {
18365
+ const manifestPath = import_node_path9.default.join(current, "package.json");
18366
+ if (import_node_fs8.default.existsSync(manifestPath)) {
18393
18367
  try {
18394
- const manifest = JSON.parse(import_node_fs9.default.readFileSync(manifestPath, "utf8"));
18368
+ const manifest = JSON.parse(import_node_fs8.default.readFileSync(manifestPath, "utf8"));
18395
18369
  if (manifest.workspaces) return canonicalizeNodePath(current);
18396
18370
  } catch {
18397
18371
  }
18398
18372
  }
18399
- const parent = import_node_path8.default.dirname(current);
18373
+ const parent = import_node_path9.default.dirname(current);
18400
18374
  if (parent === current) throw new Error("\u65E0\u6CD5\u5B9A\u4F4D Agent \u5DE5\u4F5C\u533A\uFF1B\u8BF7\u8BBE\u7F6E AGENT_WORKSPACE_ROOT");
18401
18375
  current = parent;
18402
18376
  }
@@ -18415,37 +18389,162 @@ function createNodeWorkspaceAdapter(options = {}) {
18415
18389
  const root = canonicalizeWorkspaceRoot(workspaceRoot);
18416
18390
  const markers = [];
18417
18391
  for (const marker of ["AGENTS.md", ".autopilot", ".claude"]) {
18418
- if (import_node_fs9.default.existsSync(import_node_path8.default.join(root, marker))) markers.push(marker);
18392
+ if (import_node_fs8.default.existsSync(import_node_path9.default.join(root, marker))) markers.push(marker);
18419
18393
  }
18420
18394
  return {
18421
18395
  root,
18422
18396
  hasTrustMarker: markers.length > 0,
18423
18397
  trustMarkers: markers,
18424
- displayName: import_node_path8.default.basename(root)
18398
+ displayName: import_node_path9.default.basename(root)
18425
18399
  };
18426
18400
  }
18427
18401
  return { resolveWorkspaceRoot, canonicalizeWorkspaceRoot, getWorkspaceInfo };
18428
18402
  }
18429
18403
 
18430
18404
  // src/node/stores/node-approval-store.ts
18431
- var import_node_fs10 = __toESM(require("node:fs"));
18432
- var import_core11 = require("@autopilot-agent/core");
18405
+ var import_node_fs9 = __toESM(require("node:fs"));
18406
+ var import_core10 = require("@autopilot-agent/core");
18433
18407
  function createNodeApprovalStore(options) {
18434
18408
  const paths = getNodeStatePaths(options.stateRoot);
18435
18409
  const decisionsFile = `${paths.approvalsDir}/decisions.jsonl`;
18436
18410
  const grantsFile = `${paths.approvalsDir}/grants.jsonl`;
18437
18411
  function ensureDir() {
18438
18412
  const state = ensureNodeStateRoot(paths.root);
18439
- import_node_fs10.default.mkdirSync(state.approvalsDir, { recursive: true });
18413
+ import_node_fs9.default.mkdirSync(state.approvalsDir, { recursive: true });
18440
18414
  }
18441
18415
  return {
18416
+ /** 待审批私有身份复用 decisions.jsonl;记录类型不与真实 decision 混淆。 */
18417
+ async saveExecutionApproval(request) {
18418
+ ensureDir();
18419
+ return withFileLock(decisionsFile, function freezeRequest() {
18420
+ const records = readJsonLines(decisionsFile).values;
18421
+ if (records.some(function sameRequest(record) {
18422
+ return record.recordType === "external_execution_request" && record.sessionId === request.sessionId && record.turnId === request.turnId && record.approvalId === request.approvalId;
18423
+ })) return false;
18424
+ appendJsonLine(decisionsFile, JSON.stringify(request));
18425
+ return true;
18426
+ });
18427
+ },
18428
+ /** 仅读取当前审批键的私有冻结请求,不经 transcript 公开目标。 */
18429
+ async getExecutionApproval(input) {
18430
+ ensureDir();
18431
+ return withFileLock(decisionsFile, function readRequest() {
18432
+ const records = readJsonLines(decisionsFile).values;
18433
+ return records.find(function sameRequest(record) {
18434
+ return record.recordType === "external_execution_request" && record.sessionId === input.sessionId && record.turnId === input.turnId && record.approvalId === input.approvalId;
18435
+ }) ?? null;
18436
+ });
18437
+ },
18438
+ /** 同一文件锁内核验真实批准、当前约束、TTL及未消费状态,跨进程只成功一次。 */
18439
+ async consumeExecutionApproval(input) {
18440
+ ensureDir();
18441
+ return withFileLock(decisionsFile, function consumeRequest() {
18442
+ const records = readJsonLines(decisionsFile).values;
18443
+ const matching = records.filter(function sameKey(record) {
18444
+ return record.sessionId === input.sessionId && record.turnId === input.turnId && record.approvalId === input.approvalId;
18445
+ });
18446
+ if (matching.some(function consumed(record) {
18447
+ return "recordType" in record && record.recordType === "external_execution_consumed";
18448
+ })) return false;
18449
+ const request = matching.find(function frozen(record) {
18450
+ return "recordType" in record && record.recordType === "external_execution_request";
18451
+ });
18452
+ const decision = matching.find(function approved(record) {
18453
+ return !("recordType" in record);
18454
+ });
18455
+ if (request && decision && (decision.toolName !== request.toolName || decision.expiresAt !== request.expiresAt)) return false;
18456
+ if (!request || !decision || !["allow_once", "allow_session", "allow_workspace"].includes(decision.decision) || request.constraint !== input.constraint || decision.constraint !== input.constraint || request.callId !== input.callId || decision.callId !== input.callId || request.normalizedInputHash !== input.normalizedInputHash || decision.normalizedInputHash !== input.normalizedInputHash || !Number.isFinite(Date.parse(request.expiresAt)) || !Number.isFinite(Date.parse(input.now)) || Date.parse(request.expiresAt) <= Date.parse(input.now)) return false;
18457
+ appendJsonLine(decisionsFile, JSON.stringify({ recordType: "external_execution_consumed", sessionId: input.sessionId, turnId: input.turnId, approvalId: input.approvalId }));
18458
+ return true;
18459
+ });
18460
+ },
18461
+ /** Talk-Plan1013 Stage5 R2:文件审批冻结记录复用 decisions.jsonl;recordType 与 execution 记录区分。 */
18462
+ async saveFileApproval(request) {
18463
+ ensureDir();
18464
+ return withFileLock(decisionsFile, function freezeFileRequest() {
18465
+ const records = readJsonLines(decisionsFile).values;
18466
+ if (records.some(function sameRequest(record) {
18467
+ return record.recordType === "external_file_request" && record.sessionId === request.sessionId && record.turnId === request.turnId && record.approvalId === request.approvalId;
18468
+ })) return false;
18469
+ appendJsonLine(decisionsFile, JSON.stringify(request));
18470
+ return true;
18471
+ });
18472
+ },
18473
+ /** 仅读取当前审批键的文件冻结记录,不与真实 decision 混淆。 */
18474
+ async getFileApproval(input) {
18475
+ ensureDir();
18476
+ return withFileLock(decisionsFile, function readFileRequest() {
18477
+ const records = readJsonLines(decisionsFile).values;
18478
+ return records.find(function sameRequest(record) {
18479
+ return record.recordType === "external_file_request" && record.sessionId === input.sessionId && record.turnId === input.turnId && record.approvalId === input.approvalId;
18480
+ }) ?? null;
18481
+ });
18482
+ },
18483
+ /** 同一文件锁内核验真实批准、当前约束、TTL及未消费状态,跨进程只成功一次。 */
18484
+ async consumeFileApproval(input) {
18485
+ ensureDir();
18486
+ return withFileLock(decisionsFile, function consumeFileRequest() {
18487
+ const records = readJsonLines(decisionsFile).values;
18488
+ const matching = records.filter(function sameKey(record) {
18489
+ return record.sessionId === input.sessionId && record.turnId === input.turnId && record.approvalId === input.approvalId;
18490
+ });
18491
+ if (matching.some(function consumed(record) {
18492
+ return "recordType" in record && record.recordType === "external_file_consumed";
18493
+ })) return false;
18494
+ const request = matching.find(function frozen(record) {
18495
+ return "recordType" in record && record.recordType === "external_file_request";
18496
+ });
18497
+ const decision = matching.find(function approved(record) {
18498
+ return !("recordType" in record);
18499
+ });
18500
+ if (request && decision && (decision.toolName !== request.toolName || decision.expiresAt !== request.expiresAt)) return false;
18501
+ if (!request || !decision || !["allow_once", "allow_session", "allow_workspace"].includes(decision.decision) || request.constraint !== input.constraint || decision.constraint !== input.constraint || request.callId !== input.callId || decision.callId !== input.callId || request.normalizedInputHash !== input.normalizedInputHash || decision.normalizedInputHash !== input.normalizedInputHash || !Number.isFinite(Date.parse(request.expiresAt)) || !Number.isFinite(Date.parse(input.now)) || Date.parse(request.expiresAt) <= Date.parse(input.now)) return false;
18502
+ appendJsonLine(decisionsFile, JSON.stringify({ recordType: "external_file_consumed", sessionId: input.sessionId, turnId: input.turnId, approvalId: input.approvalId }));
18503
+ return true;
18504
+ });
18505
+ },
18506
+ /** R1:降级审批冻结记录复用 decisions.jsonl;recordType 与 execution/file 记录区分。 */
18507
+ async saveDegradeApproval(request) {
18508
+ ensureDir();
18509
+ return withFileLock(decisionsFile, function freezeDegradeRequest() {
18510
+ const records = readJsonLines(decisionsFile).values;
18511
+ if (records.some(function sameRequest(record) {
18512
+ return record.recordType === "sandbox_degrade_request" && record.sessionId === request.sessionId && record.turnId === request.turnId && record.approvalId === request.approvalId;
18513
+ })) return false;
18514
+ appendJsonLine(decisionsFile, JSON.stringify(request));
18515
+ return true;
18516
+ });
18517
+ },
18518
+ /** R1:同一文件锁内核验真实批准、当前约束、TTL及未消费状态,跨进程只成功一次。 */
18519
+ async consumeDegradeApproval(input) {
18520
+ ensureDir();
18521
+ return withFileLock(decisionsFile, function consumeDegradeRequest() {
18522
+ const records = readJsonLines(decisionsFile).values;
18523
+ const matching = records.filter(function sameKey(record) {
18524
+ return record.sessionId === input.sessionId && record.turnId === input.turnId && record.approvalId === input.approvalId;
18525
+ });
18526
+ if (matching.some(function consumed(record) {
18527
+ return "recordType" in record && record.recordType === "sandbox_degrade_consumed";
18528
+ })) return false;
18529
+ const request = matching.find(function frozen(record) {
18530
+ return "recordType" in record && record.recordType === "sandbox_degrade_request";
18531
+ });
18532
+ const decision = matching.find(function approved(record) {
18533
+ return !("recordType" in record);
18534
+ });
18535
+ if (request && decision && (decision.toolName !== request.toolName || decision.expiresAt !== request.expiresAt)) return false;
18536
+ if (!request || !decision || !["allow_once", "allow_session", "allow_workspace"].includes(decision.decision) || request.constraint !== input.constraint || decision.constraint !== input.constraint || request.callId !== input.callId || decision.callId !== input.callId || request.normalizedInputHash !== input.normalizedInputHash || decision.normalizedInputHash !== input.normalizedInputHash || !Number.isFinite(Date.parse(request.expiresAt)) || !Number.isFinite(Date.parse(input.now)) || Date.parse(request.expiresAt) <= Date.parse(input.now)) return false;
18537
+ appendJsonLine(decisionsFile, JSON.stringify({ recordType: "sandbox_degrade_consumed", sessionId: input.sessionId, turnId: input.turnId, approvalId: input.approvalId }));
18538
+ return true;
18539
+ });
18540
+ },
18442
18541
  async getDecision(input) {
18443
18542
  ensureDir();
18444
18543
  return withFileLock(decisionsFile, () => {
18445
18544
  const decisions = readJsonLines(decisionsFile).values;
18446
18545
  for (let index = decisions.length - 1; index >= 0; index--) {
18447
18546
  const decision = decisions[index];
18448
- if (decision.sessionId === input.sessionId && decision.turnId === input.turnId && decision.approvalId === input.approvalId) {
18547
+ if (!("recordType" in decision) && decision.sessionId === input.sessionId && decision.turnId === input.turnId && decision.approvalId === input.approvalId) {
18449
18548
  return decision;
18450
18549
  }
18451
18550
  }
@@ -18457,7 +18556,7 @@ function createNodeApprovalStore(options) {
18457
18556
  ensureDir();
18458
18557
  return withFileLock(decisionsFile, () => {
18459
18558
  const existing = readJsonLines(decisionsFile).values;
18460
- if (existing.some((candidate) => candidate.sessionId === decision.sessionId && candidate.turnId === decision.turnId && candidate.approvalId === decision.approvalId)) return false;
18559
+ if (existing.some((candidate) => !("recordType" in candidate) && candidate.sessionId === decision.sessionId && candidate.turnId === decision.turnId && candidate.approvalId === decision.approvalId)) return false;
18461
18560
  appendJsonLine(decisionsFile, JSON.stringify(decision));
18462
18561
  return true;
18463
18562
  });
@@ -18480,16 +18579,16 @@ function createNodeApprovalStore(options) {
18480
18579
  async savePersistentGrant(input) {
18481
18580
  ensureDir();
18482
18581
  if (input.scope !== "allow_session" && input.scope !== "allow_workspace") {
18483
- throw new import_core11.AgentRuntimeError(
18582
+ throw new import_core10.AgentRuntimeError(
18484
18583
  "INVALID_INPUT",
18485
18584
  `PersistentGrant scope \u53EA\u80FD\u662F allow_session \u6216 allow_workspace\uFF0C\u6536\u5230 ${input.scope}`
18486
18585
  );
18487
18586
  }
18488
18587
  if (input.scope === "allow_session" && !input.sessionId) {
18489
- throw new import_core11.AgentRuntimeError("INVALID_INPUT", "allow_session \u6388\u6743\u5FC5\u987B\u5305\u542B sessionId");
18588
+ throw new import_core10.AgentRuntimeError("INVALID_INPUT", "allow_session \u6388\u6743\u5FC5\u987B\u5305\u542B sessionId");
18490
18589
  }
18491
18590
  if (input.scope === "allow_workspace" && !input.workspaceRoot) {
18492
- throw new import_core11.AgentRuntimeError("INVALID_INPUT", "allow_workspace \u6388\u6743\u5FC5\u987B\u5305\u542B workspaceRoot");
18591
+ throw new import_core10.AgentRuntimeError("INVALID_INPUT", "allow_workspace \u6388\u6743\u5FC5\u987B\u5305\u542B workspaceRoot");
18493
18592
  }
18494
18593
  const grant = {
18495
18594
  ...input,
@@ -18505,7 +18604,7 @@ function createNodeApprovalStore(options) {
18505
18604
  const grants = readJsonLines(grantsFile).values;
18506
18605
  let deleted = false;
18507
18606
  const remaining = grants.filter((grant) => {
18508
- const matches3 = grant.toolName === input.toolName && grant.constraint === input.constraint && grant.scope === "allow_workspace" && grant.workspaceRoot && canonicalizeNodePath(grant.workspaceRoot) === workspaceRoot;
18607
+ const matches3 = grant.toolName === input.toolName && grant.constraint === input.constraint && (grant.scope === "allow_workspace" && grant.workspaceRoot && canonicalizeNodePath(grant.workspaceRoot) === workspaceRoot || grant.scope === "allow_session" && grant.sessionId === input.sessionId);
18509
18608
  if (matches3) deleted = true;
18510
18609
  return !matches3;
18511
18610
  });
@@ -18519,21 +18618,347 @@ function createNodeApprovalStore(options) {
18519
18618
  const remaining = readJsonLines(decisionsFile).values.filter((decision) => decision.sessionId !== sessionId);
18520
18619
  atomicReplace(decisionsFile, remaining.map((decision) => JSON.stringify(decision)).join("\n") + (remaining.length ? "\n" : ""));
18521
18620
  });
18522
- await withFileLock(grantsFile, () => {
18523
- const remaining = readJsonLines(grantsFile).values.filter((grant) => !(grant.scope === "allow_session" && grant.sessionId === sessionId));
18524
- atomicReplace(grantsFile, remaining.map((grant) => JSON.stringify(grant)).join("\n") + (remaining.length ? "\n" : ""));
18621
+ await withFileLock(grantsFile, () => {
18622
+ const remaining = readJsonLines(grantsFile).values.filter((grant) => !(grant.scope === "allow_session" && grant.sessionId === sessionId));
18623
+ atomicReplace(grantsFile, remaining.map((grant) => JSON.stringify(grant)).join("\n") + (remaining.length ? "\n" : ""));
18624
+ });
18625
+ },
18626
+ /** Talk-Plan1013 Stage 2:按 canonical workspace / sessionId 过滤列出授权。 */
18627
+ async listPersistentGrants(input) {
18628
+ ensureDir();
18629
+ const workspaceRoot = input.workspaceRoot !== void 0 ? canonicalizeNodePath(input.workspaceRoot) : void 0;
18630
+ return withFileLock(grantsFile, () => {
18631
+ return readJsonLines(grantsFile).values.filter((grant) => {
18632
+ if (workspaceRoot !== void 0 && !(grant.workspaceRoot && canonicalizeNodePath(grant.workspaceRoot) === workspaceRoot)) return false;
18633
+ if (input.sessionId !== void 0 && grant.sessionId !== input.sessionId) return false;
18634
+ return true;
18635
+ });
18636
+ });
18637
+ },
18638
+ /** Talk-Plan1013 Stage 2:锁内更新授权投影状态;先写 grant 后投影失败时由调用方回写 pending。 */
18639
+ async setGrantProjection(input) {
18640
+ ensureDir();
18641
+ const workspaceRoot = canonicalizeNodePath(input.workspaceRoot);
18642
+ return withFileLock(grantsFile, () => {
18643
+ const grants = readJsonLines(grantsFile).values;
18644
+ for (let index = grants.length - 1; index >= 0; index--) {
18645
+ const grant = grants[index];
18646
+ const matches3 = grant.toolName === input.toolName && grant.constraint === input.constraint && (grant.scope === "allow_workspace" && grant.workspaceRoot && canonicalizeNodePath(grant.workspaceRoot) === workspaceRoot || grant.scope === "allow_session" && grant.sessionId === input.sessionId);
18647
+ if (!matches3) continue;
18648
+ const updated = { ...grant, projection: input.projection };
18649
+ const rewritten = grants.map((candidate, candidateIndex) => candidateIndex === index ? updated : candidate);
18650
+ atomicReplace(grantsFile, rewritten.map((candidate) => JSON.stringify(candidate)).join("\n") + "\n");
18651
+ return updated;
18652
+ }
18653
+ return null;
18654
+ });
18655
+ }
18656
+ };
18657
+ }
18658
+
18659
+ // src/node/settings/node-external-permission-projector.ts
18660
+ var import_node_fs12 = __toESM(require("node:fs"));
18661
+ var import_node_os6 = __toESM(require("node:os"));
18662
+ var import_core12 = require("@autopilot-agent/core");
18663
+ var import_core13 = require("@autopilot-agent/core");
18664
+
18665
+ // src/node/settings/user-config-directory.ts
18666
+ var import_node_fs10 = __toESM(require("node:fs"));
18667
+ var import_node_os4 = __toESM(require("node:os"));
18668
+ var import_node_path10 = __toESM(require("node:path"));
18669
+ var UserConfigDirectoryError = class extends Error {
18670
+ constructor(code) {
18671
+ super(code);
18672
+ this.code = code;
18673
+ this.name = "UserConfigDirectoryError";
18674
+ }
18675
+ };
18676
+ function resolveUserHome(homeDirectory) {
18677
+ let candidate = homeDirectory;
18678
+ if (candidate === void 0) {
18679
+ try {
18680
+ candidate = import_node_os4.default.homedir();
18681
+ } catch {
18682
+ throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
18683
+ }
18684
+ }
18685
+ if (!candidate || !import_node_path10.default.isAbsolute(candidate)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
18686
+ return import_node_path10.default.resolve(candidate);
18687
+ }
18688
+ function readEntry(entryPath) {
18689
+ try {
18690
+ return import_node_fs10.default.lstatSync(entryPath);
18691
+ } catch (error) {
18692
+ if (error.code === "ENOENT") return void 0;
18693
+ throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
18694
+ }
18695
+ }
18696
+ function isWithinHome(homeDirectory, configDirectory) {
18697
+ const relative = import_node_path10.default.relative(homeDirectory, configDirectory);
18698
+ return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${import_node_path10.default.sep}`) && !import_node_path10.default.isAbsolute(relative);
18699
+ }
18700
+ function assertSafeConfigDirectory(homeDirectory, configDirectory) {
18701
+ const entry = readEntry(configDirectory);
18702
+ if (!entry) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
18703
+ if (entry.isSymbolicLink()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
18704
+ if (!entry.isDirectory()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_NOT_DIRECTORY");
18705
+ try {
18706
+ const canonicalHome = import_node_fs10.default.realpathSync.native(homeDirectory);
18707
+ const canonicalConfigDirectory = import_node_fs10.default.realpathSync.native(configDirectory);
18708
+ if (!isWithinHome(canonicalHome, canonicalConfigDirectory)) {
18709
+ throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
18710
+ }
18711
+ } catch (error) {
18712
+ if (error instanceof UserConfigDirectoryError) throw error;
18713
+ throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
18714
+ }
18715
+ }
18716
+ function ensureUserConfigDirectory(options = {}) {
18717
+ const homeDirectory = resolveUserHome(options.homeDirectory);
18718
+ const configDirectory = import_node_path10.default.join(homeDirectory, ".autopilot");
18719
+ const existing = readEntry(configDirectory);
18720
+ if (existing) assertSafeConfigDirectory(homeDirectory, configDirectory);
18721
+ else {
18722
+ try {
18723
+ import_node_fs10.default.mkdirSync(configDirectory, { recursive: true, mode: 448 });
18724
+ } catch {
18725
+ throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
18726
+ }
18727
+ assertSafeConfigDirectory(homeDirectory, configDirectory);
18728
+ }
18729
+ return configDirectory;
18730
+ }
18731
+
18732
+ // src/node/settings/node-settings-loader.ts
18733
+ var import_node_fs11 = __toESM(require("node:fs"));
18734
+ var import_node_os5 = __toESM(require("node:os"));
18735
+ var import_node_path11 = __toESM(require("node:path"));
18736
+ var import_core11 = require("@autopilot-agent/core");
18737
+ function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = import_node_path11.default) {
18738
+ try {
18739
+ const home = homeDirectory ?? import_node_os5.default.homedir();
18740
+ if (!pathApi.isAbsolute(home)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
18741
+ return pathApi.join(home, ".autopilot", "settings.json");
18742
+ } catch {
18743
+ throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
18744
+ }
18745
+ }
18746
+ function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = import_node_os5.default.homedir(), pathApi = import_node_path11.default) {
18747
+ const root = pathApi.resolve(workspaceRoot);
18748
+ return {
18749
+ user: pathApi.join(homeDirectory, ".autopilot", "settings.json"),
18750
+ project: pathApi.join(root, ".autopilot", "settings.json"),
18751
+ local: pathApi.join(root, ".autopilot", "settings.local.json")
18752
+ };
18753
+ }
18754
+ function isSafeSettingsFile(filePath) {
18755
+ try {
18756
+ const file = import_node_fs11.default.lstatSync(filePath);
18757
+ const configDirectory = import_node_path11.default.dirname(filePath);
18758
+ const directory = import_node_fs11.default.lstatSync(configDirectory);
18759
+ if (!file.isFile() || file.isSymbolicLink() || !directory.isDirectory() || directory.isSymbolicLink()) return false;
18760
+ const canonicalDirectory = import_node_fs11.default.realpathSync.native(configDirectory);
18761
+ const canonicalFile = import_node_fs11.default.realpathSync.native(filePath);
18762
+ const relative = import_node_path11.default.relative(canonicalDirectory, canonicalFile);
18763
+ return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${import_node_path11.default.sep}`) && !import_node_path11.default.isAbsolute(relative);
18764
+ } catch (error) {
18765
+ return error.code === "ENOENT";
18766
+ }
18767
+ }
18768
+ function createNodeSettingsLoader(options = {}) {
18769
+ const debounceMs = options.debounceMs ?? 100;
18770
+ function readSource(scope, filePath) {
18771
+ if (!import_node_fs11.default.existsSync(filePath)) {
18772
+ try {
18773
+ if (import_node_fs11.default.lstatSync(filePath).isSymbolicLink()) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
18774
+ } catch {
18775
+ return void 0;
18776
+ }
18777
+ return void 0;
18778
+ }
18779
+ if (!isSafeSettingsFile(filePath)) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
18780
+ try {
18781
+ return { scope, value: JSON.parse(import_node_fs11.default.readFileSync(filePath, "utf8")), diagnostics: [] };
18782
+ } catch {
18783
+ return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_JSON_INVALID" }] };
18784
+ }
18785
+ }
18786
+ function load2(workspaceRoot) {
18787
+ return loadPaths(resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory));
18788
+ }
18789
+ function loadUser() {
18790
+ return loadPaths({ user: resolveNodeUserSettingsPath(options.homeDirectory) });
18791
+ }
18792
+ function loadPaths(paths) {
18793
+ const sources = Object.entries(paths).map(function readEntry2([scope, filePath]) {
18794
+ return readSource(scope, filePath);
18795
+ }).filter((source) => Boolean(source));
18796
+ const settings = (0, import_core11.resolveAutopilotSettings)(sources.map(({ scope, value }) => ({ scope, value })));
18797
+ const diagnostics = [...settings.diagnostics, ...sources.flatMap((source) => source.diagnostics)];
18798
+ return { paths, settings: { ...settings, diagnostics } };
18799
+ }
18800
+ function watch(workspaceRoot, onReload) {
18801
+ const paths = resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory);
18802
+ return watchPaths(Object.values(paths), function reloadWorkspace() {
18803
+ onReload(load2(workspaceRoot));
18804
+ });
18805
+ }
18806
+ function watchUser(onReload) {
18807
+ return watchPaths([resolveNodeUserSettingsPath(options.homeDirectory)], function reloadUser() {
18808
+ onReload(loadUser());
18809
+ });
18810
+ }
18811
+ function watchPaths(watched, reload) {
18812
+ let timer;
18813
+ let watchers = [];
18814
+ function installWatchers() {
18815
+ for (const watcher of watchers) watcher.close();
18816
+ const uniqueDirectories = [...new Set(watched.flatMap(function collectWatchDirectories(filePath) {
18817
+ const directory = import_node_path11.default.dirname(filePath);
18818
+ return [directory, import_node_path11.default.dirname(directory)];
18819
+ }))].filter(
18820
+ /** 不把用户配置目录的链接目标注册为监听面;父目录仍能观察链接被替换。 */
18821
+ function safeWatchDirectory(directory) {
18822
+ return import_node_fs11.default.existsSync(directory) && import_node_fs11.default.lstatSync(directory).isDirectory() && !import_node_fs11.default.lstatSync(directory).isSymbolicLink();
18823
+ }
18824
+ );
18825
+ watchers = uniqueDirectories.flatMap(function watchParent(directory) {
18826
+ try {
18827
+ const watcher = import_node_fs11.default.watch(directory, function reloadOnTargetFile(_eventType, fileName) {
18828
+ if (!fileName || !watched.some((target) => import_node_path11.default.basename(target) === fileName.toString() || import_node_path11.default.basename(import_node_path11.default.dirname(target)) === fileName.toString())) return;
18829
+ if (timer) clearTimeout(timer);
18830
+ timer = setTimeout(function reloadAfterDebounce() {
18831
+ reload();
18832
+ installWatchers();
18833
+ }, debounceMs);
18834
+ });
18835
+ watcher.unref();
18836
+ watcher.on("error", function ignoreWatcherError() {
18837
+ });
18838
+ return [watcher];
18839
+ } catch {
18840
+ return [];
18841
+ }
18842
+ });
18843
+ }
18844
+ installWatchers();
18845
+ return function stopWatchingSettings() {
18846
+ if (timer) clearTimeout(timer);
18847
+ for (const watcher of watchers) watcher.close();
18848
+ };
18849
+ }
18850
+ return { load: load2, watch, loadUser, watchUser };
18851
+ }
18852
+
18853
+ // src/node/settings/node-external-permission-projector.ts
18854
+ function readScopeValue(filePath, strict = false) {
18855
+ if (strict) {
18856
+ try {
18857
+ import_node_fs12.default.lstatSync(filePath);
18858
+ } catch (error) {
18859
+ if (error.code === "ENOENT") return {};
18860
+ throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
18861
+ }
18862
+ if (!isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
18863
+ } else if (!import_node_fs12.default.existsSync(filePath) || !isSafeSettingsFile(filePath)) return {};
18864
+ let content;
18865
+ try {
18866
+ content = import_node_fs12.default.readFileSync(filePath, "utf8");
18867
+ } catch {
18868
+ if (strict) throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
18869
+ return {};
18870
+ }
18871
+ try {
18872
+ const parsed = JSON.parse(content);
18873
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return { ...parsed };
18874
+ if (strict) throw new Error("EXTERNAL_RULE_SETTINGS_INVALID");
18875
+ return {};
18876
+ } catch {
18877
+ if (strict) throw new Error("EXTERNAL_RULE_SETTINGS_INVALID");
18878
+ return {};
18879
+ }
18880
+ }
18881
+ function readPermissionList(source, key2) {
18882
+ const permissions = source.permissions;
18883
+ if (!permissions || typeof permissions !== "object" || Array.isArray(permissions)) return [];
18884
+ const list = permissions[key2];
18885
+ if (!Array.isArray(list)) return [];
18886
+ return list.filter((entry) => typeof entry === "string");
18887
+ }
18888
+ function createNodeExternalPermissionProjector(options = {}) {
18889
+ function localSettingsPath(workspaceRoot) {
18890
+ return resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory ?? import_node_os6.default.homedir()).local;
18891
+ }
18892
+ return {
18893
+ /** 记住/撤销一条精确外部规则;只写 local 文件,失败抛错由调用方把 grant 标记 pending。 */
18894
+ async project({ workspaceRoot, rule, action }) {
18895
+ if (!(0, import_core13.isValidExternalPermissionRule)(rule)) throw new Error(`EXTERNAL_RULE_INVALID:${rule}`);
18896
+ const filePath = localSettingsPath(workspaceRoot);
18897
+ if (!isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
18898
+ return withFileLock(filePath, async function projectUnderLock() {
18899
+ const source = readScopeValue(filePath, true);
18900
+ if (source.permissions !== void 0 && (!source.permissions || typeof source.permissions !== "object" || Array.isArray(source.permissions))) throw new Error("EXTERNAL_RULE_PERMISSIONS_UNSAFE");
18901
+ const current = readPermissionList(source, "allow");
18902
+ const next = action === "add" ? current.includes(rule) ? current : [...current, rule] : current.filter((entry) => entry !== rule);
18903
+ const permissions = {
18904
+ ...source.permissions && typeof source.permissions === "object" && !Array.isArray(source.permissions) ? source.permissions : {},
18905
+ allow: next
18906
+ };
18907
+ const updated = { ...source, permissions };
18908
+ const resolved = (0, import_core12.resolveAutopilotSettings)([{ scope: "local", value: updated }]);
18909
+ if (resolved.permissions.restricted === true) throw new Error("EXTERNAL_RULE_PERMISSIONS_UNSAFE");
18910
+ if (next.length === 0 && Object.keys(permissions).length === 1) delete updated.permissions;
18911
+ if (import_node_fs12.default.existsSync(filePath) && !isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
18912
+ import_node_fs12.default.mkdirSync(resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory ?? import_node_os6.default.homedir()).local.replace(/[/\\]settings\.local\.json$/u, ""), { recursive: true });
18913
+ atomicReplace(filePath, `${JSON.stringify(updated, null, 2)}
18914
+ `);
18525
18915
  });
18916
+ },
18917
+ /** allow 仅 local 投影;deny 为 User/Project/Local 并集(Core 解析器统一校验语法)。 */
18918
+ async read(workspaceRoot) {
18919
+ const paths = resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory ?? import_node_os6.default.homedir());
18920
+ const resolved = (0, import_core12.resolveAutopilotSettings)([
18921
+ { scope: "user", value: readScopeValue(paths.user) },
18922
+ { scope: "project", value: readScopeValue(paths.project) },
18923
+ { scope: "local", value: readScopeValue(paths.local) }
18924
+ ]);
18925
+ return { allow: resolved.permissions.allow, deny: resolved.permissions.deny, ask: resolved.permissions.ask, ...resolved.permissions.restricted === true ? { restricted: true } : {} };
18926
+ }
18927
+ };
18928
+ }
18929
+
18930
+ // src/node/host-mutation-protection.ts
18931
+ var import_node_path12 = __toESM(require("node:path"));
18932
+ function createNodeHostMutationProtection(options) {
18933
+ const stateRoot = import_node_path12.default.resolve(options.stateRoot);
18934
+ const trustFile = import_node_path12.default.join(resolveNodeTrustRoot(options), "trust.json");
18935
+ const fixedTargets = [
18936
+ { path: getNodeFileMutationLockRoot(), scope: "directory" },
18937
+ { path: stateRoot, scope: "directory" },
18938
+ { path: canonicalizeNodePath(stateRoot), scope: "directory" },
18939
+ { path: trustFile, scope: "file" },
18940
+ ...options.userSettingsPath ? [{ path: import_node_path12.default.resolve(options.userSettingsPath), scope: "file" }] : []
18941
+ ];
18942
+ return {
18943
+ /** 权限配置路径复用真实User/Project/Local resolver,每次保留原路径与canonical判定。 */
18944
+ async getProtectedTargets(workspaceRoot) {
18945
+ const settings = resolveNodeSettingsPaths(options.workspaceRoot ?? workspaceRoot);
18946
+ return Object.freeze([...fixedTargets, ...[settings.user, settings.project, settings.local].map(function configTarget(filePath) {
18947
+ return { path: filePath, scope: "file" };
18948
+ })].map(function freezeTarget(target) {
18949
+ return Object.freeze({ ...target });
18950
+ }));
18526
18951
  }
18527
18952
  };
18528
18953
  }
18529
18954
 
18530
18955
  // src/node/stores/node-checkpoint-store.ts
18531
- var import_node_fs11 = __toESM(require("node:fs"));
18956
+ var import_node_fs13 = __toESM(require("node:fs"));
18532
18957
  function createNodeCheckpointStore(options) {
18533
18958
  const paths = getNodeStatePaths(options.stateRoot);
18534
18959
  function ensureDir() {
18535
18960
  const state = ensureNodeStateRoot(paths.root);
18536
- import_node_fs11.default.mkdirSync(state.checkpointsDir, { recursive: true });
18961
+ import_node_fs13.default.mkdirSync(state.checkpointsDir, { recursive: true });
18537
18962
  }
18538
18963
  function filePath(sessionId) {
18539
18964
  return safeFilePath(paths.checkpointsDir, sessionId, ".jsonl");
@@ -18584,7 +19009,7 @@ function createNodeCheckpointStore(options) {
18584
19009
  ensureDir();
18585
19010
  const target = filePath(sessionId);
18586
19011
  await withFileLock(target, () => {
18587
- if (import_node_fs11.default.existsSync(target)) import_node_fs11.default.unlinkSync(target);
19012
+ if (import_node_fs13.default.existsSync(target)) import_node_fs13.default.unlinkSync(target);
18588
19013
  });
18589
19014
  }
18590
19015
  };
@@ -18601,12 +19026,12 @@ function createNodeEventSink(_options) {
18601
19026
 
18602
19027
  // src/node/stores/node-input-inbox.ts
18603
19028
  var import_node_crypto7 = require("node:crypto");
18604
- var import_node_fs12 = __toESM(require("node:fs"));
19029
+ var import_node_fs14 = __toESM(require("node:fs"));
18605
19030
  function createNodeInputInbox(options) {
18606
19031
  const paths = getNodeStatePaths(options.stateRoot);
18607
19032
  function ensureDir() {
18608
19033
  const state = ensureNodeStateRoot(paths.root);
18609
- import_node_fs12.default.mkdirSync(state.inboxDir, { recursive: true });
19034
+ import_node_fs14.default.mkdirSync(state.inboxDir, { recursive: true });
18610
19035
  }
18611
19036
  function filePath(sessionId) {
18612
19037
  return safeFilePath(paths.inboxDir, sessionId, ".jsonl");
@@ -18693,7 +19118,7 @@ function createNodeInputInbox(options) {
18693
19118
  },
18694
19119
  async cancel(inputId) {
18695
19120
  ensureDir();
18696
- const files = import_node_fs12.default.readdirSync(paths.inboxDir).filter((file) => file.endsWith(".jsonl"));
19121
+ const files = import_node_fs14.default.readdirSync(paths.inboxDir).filter((file) => file.endsWith(".jsonl"));
18697
19122
  for (const file of files) {
18698
19123
  const sessionId = file.slice(0, -6);
18699
19124
  const cancelled = await withFileLock(filePath(sessionId), () => {
@@ -18712,7 +19137,7 @@ function createNodeInputInbox(options) {
18712
19137
  ensureDir();
18713
19138
  const target = filePath(sessionId);
18714
19139
  await withFileLock(target, () => {
18715
- if (import_node_fs12.default.existsSync(target)) import_node_fs12.default.unlinkSync(target);
19140
+ if (import_node_fs14.default.existsSync(target)) import_node_fs14.default.unlinkSync(target);
18716
19141
  });
18717
19142
  },
18718
19143
  async waitForInput(_query) {
@@ -18722,12 +19147,12 @@ function createNodeInputInbox(options) {
18722
19147
 
18723
19148
  // src/node/stores/node-project-store.ts
18724
19149
  var import_node_crypto8 = require("node:crypto");
18725
- var import_node_fs13 = __toESM(require("node:fs"));
19150
+ var import_node_fs15 = __toESM(require("node:fs"));
18726
19151
  function createNodeProjectStore(options) {
18727
19152
  const paths = getNodeStatePaths(options.stateRoot);
18728
19153
  function ensureDir() {
18729
19154
  const state = ensureNodeStateRoot(paths.root);
18730
- import_node_fs13.default.mkdirSync(state.projectsDir, { recursive: true });
19155
+ import_node_fs15.default.mkdirSync(state.projectsDir, { recursive: true });
18731
19156
  }
18732
19157
  function filePath(projectId) {
18733
19158
  return safeFilePath(paths.projectsDir, projectId, ".json");
@@ -18746,7 +19171,7 @@ function createNodeProjectStore(options) {
18746
19171
  async list() {
18747
19172
  ensureDir();
18748
19173
  const projects = [];
18749
- for (const file of import_node_fs13.default.readdirSync(paths.projectsDir).filter((entry) => entry.endsWith(".json"))) {
19174
+ for (const file of import_node_fs15.default.readdirSync(paths.projectsDir).filter((entry) => entry.endsWith(".json"))) {
18750
19175
  const project = readJsonFile(filePath(file.slice(0, -5)));
18751
19176
  if (project) projects.push(project);
18752
19177
  }
@@ -18771,8 +19196,8 @@ function createNodeProjectStore(options) {
18771
19196
  ensureDir();
18772
19197
  const target = filePath(id);
18773
19198
  return withFileLock(target, () => {
18774
- if (!import_node_fs13.default.existsSync(target)) return false;
18775
- import_node_fs13.default.unlinkSync(target);
19199
+ if (!import_node_fs15.default.existsSync(target)) return false;
19200
+ import_node_fs15.default.unlinkSync(target);
18776
19201
  return true;
18777
19202
  });
18778
19203
  }
@@ -18780,31 +19205,31 @@ function createNodeProjectStore(options) {
18780
19205
  }
18781
19206
 
18782
19207
  // src/node/stores/node-session-store.ts
18783
- var import_node_fs15 = __toESM(require("node:fs"));
19208
+ var import_node_fs17 = __toESM(require("node:fs"));
18784
19209
 
18785
19210
  // src/node/chat-state.ts
18786
- var import_node_fs14 = __toESM(require("node:fs"));
18787
- var import_node_os3 = __toESM(require("node:os"));
18788
- var import_node_path9 = __toESM(require("node:path"));
19211
+ var import_node_fs16 = __toESM(require("node:fs"));
19212
+ var import_node_os7 = __toESM(require("node:os"));
19213
+ var import_node_path13 = __toESM(require("node:path"));
18789
19214
  function resolveNodeChatStatePaths(options = {}) {
18790
19215
  try {
18791
- if (options.globalStateRoot !== void 0 && !import_node_path9.default.isAbsolute(options.globalStateRoot)) throw new NodeChatError("CHAT_STATE_ROOT_INVALID");
18792
- const globalRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: import_node_os3.default.homedir() });
18793
- const root = import_node_path9.default.join(globalRoot, "chat");
18794
- return { root, stateRoot: import_node_path9.default.join(root, "state"), attachmentsRoot: import_node_path9.default.join(root, "attachments"), knowledgeRoot: import_node_path9.default.join(root, "knowledge") };
19216
+ if (options.globalStateRoot !== void 0 && !import_node_path13.default.isAbsolute(options.globalStateRoot)) throw new NodeChatError("CHAT_STATE_ROOT_INVALID");
19217
+ const globalRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: import_node_os7.default.homedir() });
19218
+ const root = import_node_path13.default.join(globalRoot, "chat");
19219
+ return { root, stateRoot: import_node_path13.default.join(root, "state"), attachmentsRoot: import_node_path13.default.join(root, "attachments"), knowledgeRoot: import_node_path13.default.join(root, "knowledge") };
18795
19220
  } catch (error) {
18796
19221
  throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
18797
19222
  }
18798
19223
  }
18799
19224
  function assertSafeNodePath(root, target) {
18800
19225
  try {
18801
- const relative = import_node_path9.default.relative(root, target);
18802
- if (relative === ".." || relative.startsWith(`..${import_node_path9.default.sep}`) || import_node_path9.default.isAbsolute(relative)) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
19226
+ const relative = import_node_path13.default.relative(root, target);
19227
+ if (relative === ".." || relative.startsWith(`..${import_node_path13.default.sep}`) || import_node_path13.default.isAbsolute(relative)) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
18803
19228
  let current = root;
18804
- for (const segment of ["", ...relative.split(import_node_path9.default.sep).filter(Boolean)]) {
18805
- if (segment) current = import_node_path9.default.join(current, segment);
19229
+ for (const segment of ["", ...relative.split(import_node_path13.default.sep).filter(Boolean)]) {
19230
+ if (segment) current = import_node_path13.default.join(current, segment);
18806
19231
  try {
18807
- const entry = import_node_fs14.default.lstatSync(current);
19232
+ const entry = import_node_fs16.default.lstatSync(current);
18808
19233
  if (entry.isSymbolicLink() || current !== target && !entry.isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
18809
19234
  } catch (error) {
18810
19235
  if (error.code !== "ENOENT") throw error;
@@ -18818,15 +19243,15 @@ function assertSafeNodePath(root, target) {
18818
19243
  function ensureChatDirectory(root, target) {
18819
19244
  try {
18820
19245
  assertSafeNodePath(root, target);
18821
- import_node_fs14.default.mkdirSync(target, { recursive: true, mode: 448 });
19246
+ import_node_fs16.default.mkdirSync(target, { recursive: true, mode: 448 });
18822
19247
  assertSafeNodePath(root, target);
18823
- if (!import_node_fs14.default.lstatSync(target).isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
19248
+ if (!import_node_fs16.default.lstatSync(target).isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
18824
19249
  } catch (error) {
18825
19250
  throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
18826
19251
  }
18827
19252
  }
18828
19253
  function initializeNodeChatDirectories(paths) {
18829
- ensureChatDirectory(import_node_path9.default.dirname(paths.root), paths.root);
19254
+ ensureChatDirectory(import_node_path13.default.dirname(paths.root), paths.root);
18830
19255
  ensureChatDirectory(paths.root, paths.stateRoot);
18831
19256
  ensureChatDirectory(paths.root, paths.attachmentsRoot);
18832
19257
  }
@@ -18838,7 +19263,7 @@ function createNodeSessionStore(options) {
18838
19263
  function ensureDir() {
18839
19264
  const state = ensureNodeStateRoot(options.stateRoot);
18840
19265
  assertSafeNodePath(state.root, state.sessionsDir);
18841
- import_node_fs15.default.mkdirSync(state.sessionsDir, { recursive: true });
19266
+ import_node_fs17.default.mkdirSync(state.sessionsDir, { recursive: true });
18842
19267
  }
18843
19268
  function filePath(sessionId) {
18844
19269
  const target = safeFilePath(paths.sessionsDir, sessionId, ".json");
@@ -18847,9 +19272,9 @@ function createNodeSessionStore(options) {
18847
19272
  }
18848
19273
  function read(id) {
18849
19274
  const target = filePath(id);
18850
- if (!import_node_fs15.default.existsSync(target)) return null;
19275
+ if (!import_node_fs17.default.existsSync(target)) return null;
18851
19276
  let value;
18852
- const content = import_node_fs15.default.readFileSync(target, "utf8");
19277
+ const content = import_node_fs17.default.readFileSync(target, "utf8");
18853
19278
  try {
18854
19279
  value = JSON.parse(content);
18855
19280
  } catch {
@@ -18877,7 +19302,7 @@ function createNodeSessionStore(options) {
18877
19302
  try {
18878
19303
  ensureDir();
18879
19304
  const sessions = [];
18880
- for (const file of import_node_fs15.default.readdirSync(paths.sessionsDir)) {
19305
+ for (const file of import_node_fs17.default.readdirSync(paths.sessionsDir)) {
18881
19306
  if (!file.endsWith(".json")) continue;
18882
19307
  const session = await this.get(file.slice(0, -5));
18883
19308
  if (session) sessions.push(session);
@@ -18909,7 +19334,7 @@ function createNodeSessionStore(options) {
18909
19334
  const target = filePath(id);
18910
19335
  return await withFileLock(target, function deleteLocked() {
18911
19336
  if (!read(id)) return false;
18912
- import_node_fs15.default.unlinkSync(target);
19337
+ import_node_fs17.default.unlinkSync(target);
18913
19338
  return true;
18914
19339
  });
18915
19340
  } catch (error) {
@@ -18921,11 +19346,11 @@ function createNodeSessionStore(options) {
18921
19346
 
18922
19347
  // src/node/stores/node-transcript-store.ts
18923
19348
  var import_promises3 = __toESM(require("node:fs/promises"));
18924
- var import_node_path10 = __toESM(require("node:path"));
19349
+ var import_node_path14 = __toESM(require("node:path"));
18925
19350
  var transcriptIndexes = /* @__PURE__ */ new Map();
18926
19351
  var transcriptRootInitializations = /* @__PURE__ */ new Map();
18927
19352
  function getTranscriptIndex(filePath) {
18928
- const key2 = import_node_path10.default.resolve(filePath);
19353
+ const key2 = import_node_path14.default.resolve(filePath);
18929
19354
  const existing = transcriptIndexes.get(key2);
18930
19355
  if (existing) return existing;
18931
19356
  const created = { initialized: false, offset: 0, pendingBytes: Buffer.alloc(0), endsWithNewline: true, keys: /* @__PURE__ */ new Set() };
@@ -18936,7 +19361,7 @@ function getEnvelopeKey(envelope) {
18936
19361
  return `${envelope.sessionId}\0${envelope.turnId}\0${envelope.seq}`;
18937
19362
  }
18938
19363
  function ensureTranscriptDirectory(stateRoot) {
18939
- const key2 = import_node_path10.default.resolve(stateRoot);
19364
+ const key2 = import_node_path14.default.resolve(stateRoot);
18940
19365
  const existing = transcriptRootInitializations.get(key2);
18941
19366
  if (existing) return existing;
18942
19367
  const initialization = Promise.resolve().then(async function initializeTranscriptDirectory() {
@@ -18958,7 +19383,7 @@ async function readTranscriptBuffer(filePath) {
18958
19383
  }
18959
19384
  }
18960
19385
  function reportCorruptedLine(filePath) {
18961
- console.warn(`[DURABLE_JSONL_CORRUPTED] file=${import_node_path10.default.basename(filePath)} records=1 lines=unknown`);
19386
+ console.warn(`[DURABLE_JSONL_CORRUPTED] file=${import_node_path14.default.basename(filePath)} records=1 lines=unknown`);
18962
19387
  }
18963
19388
  function parseTranscriptLine(filePath, line, index, parsed) {
18964
19389
  if (line.length === 0) return;
@@ -19110,12 +19535,12 @@ function createNodeTranscriptStore(options) {
19110
19535
  }
19111
19536
 
19112
19537
  // src/node/stores/node-turn-store.ts
19113
- var import_node_fs16 = __toESM(require("node:fs"));
19538
+ var import_node_fs18 = __toESM(require("node:fs"));
19114
19539
  function createNodeTurnStore(options) {
19115
19540
  const paths = getNodeStatePaths(options.stateRoot);
19116
19541
  function ensureDir() {
19117
19542
  const state = ensureNodeStateRoot(paths.root);
19118
- import_node_fs16.default.mkdirSync(state.turnsDir, { recursive: true });
19543
+ import_node_fs18.default.mkdirSync(state.turnsDir, { recursive: true });
19119
19544
  }
19120
19545
  function filePath(turnId) {
19121
19546
  return safeFilePath(paths.turnsDir, turnId, ".json");
@@ -19134,7 +19559,7 @@ function createNodeTurnStore(options) {
19134
19559
  async list(sessionId) {
19135
19560
  ensureDir();
19136
19561
  const turns = [];
19137
- for (const file of import_node_fs16.default.readdirSync(paths.turnsDir).filter((entry) => entry.endsWith(".json"))) {
19562
+ for (const file of import_node_fs18.default.readdirSync(paths.turnsDir).filter((entry) => entry.endsWith(".json"))) {
19138
19563
  const turn = readJsonFile(filePath(file.slice(0, -5)));
19139
19564
  if (turn?.sessionId === sessionId) turns.push(turn);
19140
19565
  }
@@ -19151,7 +19576,7 @@ function createNodeTurnStore(options) {
19151
19576
  for (const turn of turns) {
19152
19577
  const target = filePath(turn.id);
19153
19578
  await withFileLock(target, () => {
19154
- if (import_node_fs16.default.existsSync(target)) import_node_fs16.default.unlinkSync(target);
19579
+ if (import_node_fs18.default.existsSync(target)) import_node_fs18.default.unlinkSync(target);
19155
19580
  });
19156
19581
  }
19157
19582
  }
@@ -19159,12 +19584,12 @@ function createNodeTurnStore(options) {
19159
19584
  }
19160
19585
 
19161
19586
  // src/node/stores/node-lease-store.ts
19162
- var import_node_fs17 = __toESM(require("node:fs"));
19587
+ var import_node_fs19 = __toESM(require("node:fs"));
19163
19588
  function createNodeLeaseStore(options) {
19164
19589
  const paths = getNodeStatePaths(options.stateRoot);
19165
19590
  function ensureDir() {
19166
19591
  const state = ensureNodeStateRoot(paths.root);
19167
- import_node_fs17.default.mkdirSync(state.leasesDir, { recursive: true });
19592
+ import_node_fs19.default.mkdirSync(state.leasesDir, { recursive: true });
19168
19593
  }
19169
19594
  function filePath(sessionId) {
19170
19595
  return safeFilePath(paths.leasesDir, sessionId, ".json");
@@ -19201,7 +19626,7 @@ function createNodeLeaseStore(options) {
19201
19626
  return withFileLock(target, () => {
19202
19627
  const current = readJsonFile(target);
19203
19628
  if (!current || current.lease.leaseId !== input.lease.leaseId || current.lease.ownerId !== input.lease.ownerId) return false;
19204
- if (import_node_fs17.default.existsSync(target)) import_node_fs17.default.unlinkSync(target);
19629
+ if (import_node_fs19.default.existsSync(target)) import_node_fs19.default.unlinkSync(target);
19205
19630
  return true;
19206
19631
  });
19207
19632
  },
@@ -19209,7 +19634,7 @@ function createNodeLeaseStore(options) {
19209
19634
  ensureDir();
19210
19635
  const target = filePath(sessionId);
19211
19636
  await withFileLock(target, () => {
19212
- if (import_node_fs17.default.existsSync(target)) import_node_fs17.default.unlinkSync(target);
19637
+ if (import_node_fs19.default.existsSync(target)) import_node_fs19.default.unlinkSync(target);
19213
19638
  });
19214
19639
  }
19215
19640
  };
@@ -19224,26 +19649,26 @@ function createNodeClock() {
19224
19649
  }
19225
19650
 
19226
19651
  // src/node/stores/node-job-store.ts
19227
- var import_node_fs18 = __toESM(require("node:fs"));
19228
- var import_node_path11 = __toESM(require("node:path"));
19652
+ var import_node_fs20 = __toESM(require("node:fs"));
19653
+ var import_node_path15 = __toESM(require("node:path"));
19229
19654
  function createNodeJobStore(options) {
19230
19655
  const paths = getNodeStatePaths(options.stateRoot);
19231
19656
  function ensureDir() {
19232
19657
  const state = ensureNodeStateRoot(paths.root);
19233
- import_node_fs18.default.mkdirSync(state.jobsDir, { recursive: true });
19658
+ import_node_fs20.default.mkdirSync(state.jobsDir, { recursive: true });
19234
19659
  }
19235
19660
  function filePath(id) {
19236
19661
  return safeFilePath(paths.jobsDir, id, ".json");
19237
19662
  }
19238
19663
  function sessionLockPath(sessionId) {
19239
- return safeFilePath(import_node_path11.default.join(paths.jobsDir, ".session-locks"), sessionId, ".guard");
19664
+ return safeFilePath(import_node_path15.default.join(paths.jobsDir, ".session-locks"), sessionId, ".guard");
19240
19665
  }
19241
19666
  function sameOwner(first, second) {
19242
19667
  return first?.runtimeInstanceId === second.runtimeInstanceId && first.hostProcessId === second.hostProcessId;
19243
19668
  }
19244
19669
  function readAll() {
19245
19670
  ensureDir();
19246
- return import_node_fs18.default.readdirSync(paths.jobsDir).filter((file) => file.endsWith(".json")).flatMap((file) => {
19671
+ return import_node_fs20.default.readdirSync(paths.jobsDir).filter((file) => file.endsWith(".json")).flatMap((file) => {
19247
19672
  const job = readJsonFile(filePath(file.slice(0, -5)));
19248
19673
  return job ? [job] : [];
19249
19674
  });
@@ -19256,7 +19681,7 @@ function createNodeJobStore(options) {
19256
19681
  async create(job) {
19257
19682
  ensureDir();
19258
19683
  return withFileLock(filePath(job.id), function createIfMissing() {
19259
- if (import_node_fs18.default.existsSync(filePath(job.id))) return false;
19684
+ if (import_node_fs20.default.existsSync(filePath(job.id))) return false;
19260
19685
  atomicReplace(filePath(job.id), JSON.stringify(job, null, 2));
19261
19686
  return true;
19262
19687
  });
@@ -19285,7 +19710,7 @@ function createNodeJobStore(options) {
19285
19710
  for (const job of await this.listBySession(sessionId)) {
19286
19711
  const target = filePath(job.id);
19287
19712
  await withFileLock(target, () => {
19288
- if (import_node_fs18.default.existsSync(target)) import_node_fs18.default.unlinkSync(target);
19713
+ if (import_node_fs20.default.existsSync(target)) import_node_fs20.default.unlinkSync(target);
19289
19714
  });
19290
19715
  }
19291
19716
  },
@@ -19314,42 +19739,42 @@ function createNodeJobOwnerProbe() {
19314
19739
 
19315
19740
  // src/node/stores/node-file-mutation-store.ts
19316
19741
  var import_node_crypto9 = require("node:crypto");
19317
- var import_node_fs19 = __toESM(require("node:fs"));
19318
- var import_node_path12 = __toESM(require("node:path"));
19742
+ var import_node_fs21 = __toESM(require("node:fs"));
19743
+ var import_node_path16 = __toESM(require("node:path"));
19319
19744
  var MAX_FILE_SNAPSHOT_BYTES = 512 * 1024;
19320
19745
  var MAX_SESSION_SNAPSHOT_BYTES = 5 * 1024 * 1024;
19321
19746
  function sha256(content) {
19322
19747
  return (0, import_node_crypto9.createHash)("sha256").update(content).digest("hex");
19323
19748
  }
19324
19749
  function writeBlob(blobPath, content) {
19325
- if (import_node_fs19.default.existsSync(blobPath)) return;
19326
- import_node_fs19.default.mkdirSync(import_node_path12.default.dirname(blobPath), { recursive: true });
19750
+ if (import_node_fs21.default.existsSync(blobPath)) return;
19751
+ import_node_fs21.default.mkdirSync(import_node_path16.default.dirname(blobPath), { recursive: true });
19327
19752
  const temporary = `${blobPath}.${process.pid}.${(0, import_node_crypto9.randomUUID)()}.tmp`;
19328
19753
  try {
19329
- const descriptor = import_node_fs19.default.openSync(temporary, "wx");
19754
+ const descriptor = import_node_fs21.default.openSync(temporary, "wx");
19330
19755
  try {
19331
- import_node_fs19.default.writeFileSync(descriptor, content);
19332
- import_node_fs19.default.fsyncSync(descriptor);
19756
+ import_node_fs21.default.writeFileSync(descriptor, content);
19757
+ import_node_fs21.default.fsyncSync(descriptor);
19333
19758
  } finally {
19334
- import_node_fs19.default.closeSync(descriptor);
19759
+ import_node_fs21.default.closeSync(descriptor);
19335
19760
  }
19336
19761
  try {
19337
- import_node_fs19.default.renameSync(temporary, blobPath);
19762
+ import_node_fs21.default.renameSync(temporary, blobPath);
19338
19763
  } catch (error) {
19339
- if (!import_node_fs19.default.existsSync(blobPath)) throw error;
19764
+ if (!import_node_fs21.default.existsSync(blobPath)) throw error;
19340
19765
  }
19341
19766
  } finally {
19342
- if (import_node_fs19.default.existsSync(temporary)) import_node_fs19.default.unlinkSync(temporary);
19767
+ if (import_node_fs21.default.existsSync(temporary)) import_node_fs21.default.unlinkSync(temporary);
19343
19768
  }
19344
19769
  }
19345
19770
  function createNodeFileMutationStore(options) {
19346
19771
  const paths = getNodeStatePaths(options.stateRoot);
19347
19772
  function ensureDir() {
19348
19773
  const state = ensureNodeStateRoot(paths.root);
19349
- import_node_fs19.default.mkdirSync(state.mutationsDir, { recursive: true });
19350
- import_node_fs19.default.mkdirSync(state.mutationBlobsDir, { recursive: true });
19351
- import_node_fs19.default.mkdirSync(state.mutationLocksDir, { recursive: true });
19352
- import_node_fs19.default.mkdirSync(state.undoTransactionsDir, { recursive: true });
19774
+ import_node_fs21.default.mkdirSync(state.mutationsDir, { recursive: true });
19775
+ import_node_fs21.default.mkdirSync(state.mutationBlobsDir, { recursive: true });
19776
+ import_node_fs21.default.mkdirSync(state.mutationLocksDir, { recursive: true });
19777
+ import_node_fs21.default.mkdirSync(state.undoTransactionsDir, { recursive: true });
19353
19778
  }
19354
19779
  function mutationPath(id) {
19355
19780
  return safeFilePath(paths.mutationsDir, id, ".json");
@@ -19363,9 +19788,9 @@ function createNodeFileMutationStore(options) {
19363
19788
  }
19364
19789
  function readAll() {
19365
19790
  ensureDir();
19366
- return import_node_fs19.default.readdirSync(paths.mutationsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
19791
+ return import_node_fs21.default.readdirSync(paths.mutationsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
19367
19792
  try {
19368
- return [JSON.parse(import_node_fs19.default.readFileSync(mutationPath(entry.slice(0, -5)), "utf8"))];
19793
+ return [JSON.parse(import_node_fs21.default.readFileSync(mutationPath(entry.slice(0, -5)), "utf8"))];
19369
19794
  } catch {
19370
19795
  return [];
19371
19796
  }
@@ -19373,9 +19798,9 @@ function createNodeFileMutationStore(options) {
19373
19798
  }
19374
19799
  function readTransactions() {
19375
19800
  ensureDir();
19376
- return import_node_fs19.default.readdirSync(paths.undoTransactionsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
19801
+ return import_node_fs21.default.readdirSync(paths.undoTransactionsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
19377
19802
  try {
19378
- return [JSON.parse(import_node_fs19.default.readFileSync(transactionPath(entry.slice(0, -5)), "utf8"))];
19803
+ return [JSON.parse(import_node_fs21.default.readFileSync(transactionPath(entry.slice(0, -5)), "utf8"))];
19379
19804
  } catch {
19380
19805
  return [];
19381
19806
  }
@@ -19383,7 +19808,7 @@ function createNodeFileMutationStore(options) {
19383
19808
  }
19384
19809
  function sessionBlobBytes(sessionId) {
19385
19810
  const refs3 = new Set(readAll().filter((item) => item.sessionId === sessionId).flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
19386
- return [...refs3].reduce((total, ref) => total + (import_node_fs19.default.statSync(blobPath(ref), { throwIfNoEntry: false })?.size ?? 0), 0);
19811
+ return [...refs3].reduce((total, ref) => total + (import_node_fs21.default.statSync(blobPath(ref), { throwIfNoEntry: false })?.size ?? 0), 0);
19387
19812
  }
19388
19813
  return {
19389
19814
  async prepare(input) {
@@ -19393,7 +19818,7 @@ function createNodeFileMutationStore(options) {
19393
19818
  const refs3 = /* @__PURE__ */ new Map();
19394
19819
  if (input.before) refs3.set(beforeRef, input.before);
19395
19820
  if (input.after) refs3.set(afterRef, input.after);
19396
- const additionalBytes = [...refs3.entries()].filter(([ref]) => !import_node_fs19.default.existsSync(blobPath(ref))).reduce((total, [, content]) => total + content.byteLength, 0);
19821
+ const additionalBytes = [...refs3.entries()].filter(([ref]) => !import_node_fs21.default.existsSync(blobPath(ref))).reduce((total, [, content]) => total + content.byteLength, 0);
19397
19822
  const byteCount = (input.before?.byteLength ?? 0) + (input.after?.byteLength ?? 0);
19398
19823
  const binary2 = Boolean(input.before?.includes(0) || input.after?.includes(0));
19399
19824
  const reversible = !binary2 && byteCount <= MAX_FILE_SNAPSHOT_BYTES && sessionBlobBytes(input.sessionId) + additionalBytes <= MAX_SESSION_SNAPSHOT_BYTES;
@@ -19424,7 +19849,7 @@ function createNodeFileMutationStore(options) {
19424
19849
  async getBlob(ref) {
19425
19850
  ensureDir();
19426
19851
  try {
19427
- const content = import_node_fs19.default.readFileSync(blobPath(ref));
19852
+ const content = import_node_fs21.default.readFileSync(blobPath(ref));
19428
19853
  return sha256(content) === ref ? content : null;
19429
19854
  } catch {
19430
19855
  return null;
@@ -19442,46 +19867,48 @@ function createNodeFileMutationStore(options) {
19442
19867
  },
19443
19868
  async deleteBySession(sessionId) {
19444
19869
  ensureDir();
19445
- for (const mutation of readAll().filter((item) => item.sessionId === sessionId)) import_node_fs19.default.rmSync(mutationPath(mutation.id), { force: true });
19446
- for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId)) import_node_fs19.default.rmSync(transactionPath(transaction.id), { force: true });
19870
+ for (const mutation of readAll().filter((item) => item.sessionId === sessionId)) import_node_fs21.default.rmSync(mutationPath(mutation.id), { force: true });
19871
+ for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId)) import_node_fs21.default.rmSync(transactionPath(transaction.id), { force: true });
19447
19872
  const referenced = new Set(readAll().flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
19448
- for (const entry of import_node_fs19.default.readdirSync(paths.mutationBlobsDir).filter((item) => item.endsWith(".blob"))) if (!referenced.has(entry.slice(0, -5))) import_node_fs19.default.rmSync(import_node_path12.default.join(paths.mutationBlobsDir, entry), { force: true });
19873
+ for (const entry of import_node_fs21.default.readdirSync(paths.mutationBlobsDir).filter((item) => item.endsWith(".blob"))) if (!referenced.has(entry.slice(0, -5))) import_node_fs21.default.rmSync(import_node_path16.default.join(paths.mutationBlobsDir, entry), { force: true });
19449
19874
  },
19450
- async withWorkspaceLock(workspaceRoot, operation) {
19875
+ async withWorkspaceLock(workspaceRoot, operation, canonicalTargets = []) {
19451
19876
  ensureDir();
19452
- const lockId = (0, import_node_crypto9.createHash)("sha256").update(import_node_path12.default.resolve(workspaceRoot)).digest("hex");
19453
- return withFileLock(safeFilePath(paths.mutationLocksDir, lockId, ".lock-target"), operation);
19877
+ const lockId = (0, import_node_crypto9.createHash)("sha256").update(import_node_path16.default.resolve(workspaceRoot)).digest("hex");
19878
+ return withFileLock(safeFilePath(paths.mutationLocksDir, lockId, ".lock-target"), function lockTargets() {
19879
+ return withNodeFileMutationLocks(canonicalTargets, operation);
19880
+ }, { requireExitedOwner: true });
19454
19881
  }
19455
19882
  };
19456
19883
  }
19457
19884
 
19458
19885
  // src/node/stores/node-session-resource-store.ts
19459
- var import_node_fs20 = __toESM(require("node:fs"));
19460
- var import_node_path13 = __toESM(require("node:path"));
19886
+ var import_node_fs22 = __toESM(require("node:fs"));
19887
+ var import_node_path17 = __toESM(require("node:path"));
19461
19888
  function isAttachmentSessionId(sessionId) {
19462
19889
  return /^[0-9a-f-]{36}$/iu.test(sessionId);
19463
19890
  }
19464
19891
  function createNodeSessionResourceStore(workspaceRoot) {
19465
19892
  const root = canonicalizeNodePath(workspaceRoot);
19466
- const uploadsRoot = import_node_path13.default.join(root, ".local", "session-uploads");
19893
+ const uploadsRoot = import_node_path17.default.join(root, ".local", "session-uploads");
19467
19894
  return {
19468
19895
  async deleteBySession(sessionId) {
19469
19896
  if (!isAttachmentSessionId(sessionId)) return;
19470
- const target = import_node_path13.default.join(uploadsRoot, sessionId);
19471
- if (!target.startsWith(`${uploadsRoot}${import_node_path13.default.sep}`)) throw new Error("SESSION_RESOURCE_PATH_INVALID");
19472
- import_node_fs20.default.rmSync(target, { recursive: true, force: true, maxRetries: 2 });
19897
+ const target = import_node_path17.default.join(uploadsRoot, sessionId);
19898
+ if (!target.startsWith(`${uploadsRoot}${import_node_path17.default.sep}`)) throw new Error("SESSION_RESOURCE_PATH_INVALID");
19899
+ import_node_fs22.default.rmSync(target, { recursive: true, force: true, maxRetries: 2 });
19473
19900
  }
19474
19901
  };
19475
19902
  }
19476
19903
 
19477
19904
  // src/node/stores/node-user-question-store.ts
19478
- var import_node_fs21 = __toESM(require("node:fs"));
19905
+ var import_node_fs23 = __toESM(require("node:fs"));
19479
19906
  function createNodeUserQuestionStore(options) {
19480
19907
  const paths = getNodeStatePaths(options.stateRoot);
19481
19908
  const recordsFile = `${paths.questionsDir}/requests.jsonl`;
19482
19909
  function ensureDir() {
19483
19910
  const state = ensureNodeStateRoot(paths.root);
19484
- import_node_fs21.default.mkdirSync(state.questionsDir, { recursive: true });
19911
+ import_node_fs23.default.mkdirSync(state.questionsDir, { recursive: true });
19485
19912
  }
19486
19913
  function answersEqual(left, right) {
19487
19914
  return JSON.stringify(left) === JSON.stringify(right);
@@ -19545,6 +19972,7 @@ function createNodeRuntimePorts(options) {
19545
19972
  throw createNodeIdentityError("WORKSPACE_REQUIRED");
19546
19973
  }
19547
19974
  return {
19975
+ hostMutationProtection: options.productMode === "chat" ? void 0 : createNodeHostMutationProtection(options),
19548
19976
  sessionStore: createNodeSessionStore({ ...storeOptions, productMode: options.productMode }),
19549
19977
  checkpointStore: createNodeCheckpointStore(storeOptions),
19550
19978
  transcriptStore: createNodeTranscriptStore(storeOptions),
@@ -19555,6 +19983,8 @@ function createNodeRuntimePorts(options) {
19555
19983
  workspaceAdapter: options.productMode === "chat" ? { resolveWorkspaceRoot: noWorkspace, canonicalizeWorkspaceRoot: noWorkspace, getWorkspaceInfo: noWorkspace } : createNodeWorkspaceAdapter(workspaceOptions),
19556
19984
  turnStore: createNodeTurnStore(storeOptions),
19557
19985
  approvalStore: createNodeApprovalStore(storeOptions),
19986
+ /** Work授权查询/投影复用既有Stage2端口;注入本身不产生任何grant。 */
19987
+ externalPermissionProjector: options.productMode === "chat" || options.workspaceRoot === void 0 ? void 0 : createNodeExternalPermissionProjector(),
19558
19988
  inputInbox: createNodeInputInbox(storeOptions),
19559
19989
  leaseStore: createNodeLeaseStore(storeOptions),
19560
19990
  jobStore: createNodeJobStore(storeOptions),
@@ -19571,17 +20001,20 @@ function createNodeRuntimePorts(options) {
19571
20001
  * Stage 2:Work 模式装配真实 SRT adapter(绑定 canonical workspaceRoot;tempRoot
19572
20002
  * 必须由宿主显式验证后提供);Chat 保持 unavailable stub——Chat 不开放 Work 工具,
19573
20003
  * 即使伪造 full_access 也不能获得进程沙箱能力。workspaceRoot 缺失时同样 fail-closed。
20004
+ * Talk-Plan1022 S1:Windows 宿主执行模式装配宿主执行 port——不加载 SRT、不要求
20005
+ * provision,进程调用经用户逐次审批后在宿主直接执行;macOS 装配保持不变。
19574
20006
  */
19575
- sandboxPort: options.productMode === "chat" || options.workspaceRoot === void 0 ? (0, import_core12.createUnavailableSandboxPort)() : createNodeSandboxPort({
20007
+ sandboxPort: options.productMode === "chat" || options.workspaceRoot === void 0 ? (0, import_core14.createUnavailableSandboxPort)() : process.platform === "win32" ? createNodeHostExecutionSandboxPort() : createNodeSandboxPort({
19576
20008
  workspaceRoot: options.workspaceRoot,
20009
+ stateRoot: options.stateRoot,
19577
20010
  ...options.sandboxTempRoot !== void 0 ? { tempRoot: options.sandboxTempRoot } : {}
19578
20011
  })
19579
20012
  };
19580
20013
  }
19581
20014
 
19582
20015
  // src/node/stores/node-chat-attachment-store.ts
19583
- var import_node_fs22 = __toESM(require("node:fs"));
19584
- var import_node_path14 = __toESM(require("node:path"));
20016
+ var import_node_fs24 = __toESM(require("node:fs"));
20017
+ var import_node_path18 = __toESM(require("node:path"));
19585
20018
  var import_node_crypto10 = require("node:crypto");
19586
20019
  var CHAT_ATTACHMENT_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
19587
20020
  var MAX_BYTES = 20 * 1024 * 1024;
@@ -19621,12 +20054,12 @@ function createNodeChatAttachmentStore(options) {
19621
20054
  const { paths, sessionStore } = options;
19622
20055
  const now = options.now ?? Date.now;
19623
20056
  const root = paths.attachmentsRoot;
19624
- const dataRoot = import_node_path14.default.join(root, "sessions");
19625
- const retiredRoot = import_node_path14.default.join(root, "retired");
19626
- const deletingRoot = import_node_path14.default.join(root, "deleting");
19627
- const lock = import_node_path14.default.join(root, "lifecycle");
20057
+ const dataRoot = import_node_path18.default.join(root, "sessions");
20058
+ const retiredRoot = import_node_path18.default.join(root, "retired");
20059
+ const deletingRoot = import_node_path18.default.join(root, "deleting");
20060
+ const lock = import_node_path18.default.join(root, "lifecycle");
19628
20061
  function ensure() {
19629
- assertSafeNodePath(import_node_path14.default.dirname(paths.root), paths.root);
20062
+ assertSafeNodePath(import_node_path18.default.dirname(paths.root), paths.root);
19630
20063
  for (const directory of [root, dataRoot, retiredRoot, deletingRoot]) ensureChatDirectory(paths.root, directory);
19631
20064
  assertSafeNodePath(root, `${lock}.lock`);
19632
20065
  }
@@ -19648,9 +20081,9 @@ function createNodeChatAttachmentStore(options) {
19648
20081
  }
19649
20082
  function isSessionDeleting(sessionId) {
19650
20083
  try {
19651
- const target = import_node_path14.default.join(deletingRoot, `${sessionKey(sessionId)}.json`);
20084
+ const target = import_node_path18.default.join(deletingRoot, `${sessionKey(sessionId)}.json`);
19652
20085
  assertSafeNodePath(root, target);
19653
- return import_node_fs22.default.existsSync(target);
20086
+ return import_node_fs24.default.existsSync(target);
19654
20087
  } catch (error) {
19655
20088
  throw toNodeBoundaryError(error, "CHAT_ATTACHMENT_UNAVAILABLE");
19656
20089
  }
@@ -19667,16 +20100,16 @@ function createNodeChatAttachmentStore(options) {
19667
20100
  if (session?.productMode !== "chat" || !["none", "web"].includes(session.chatRetrievalMode ?? "")) throw new NodeChatError("CHAT_UPLOAD_MODE_MISMATCH");
19668
20101
  }
19669
20102
  function records(sessionId) {
19670
- const directory = import_node_path14.default.join(dataRoot, sessionKey(sessionId));
20103
+ const directory = import_node_path18.default.join(dataRoot, sessionKey(sessionId));
19671
20104
  assertSafeNodePath(root, directory);
19672
- if (!import_node_fs22.default.existsSync(directory)) return [];
20105
+ if (!import_node_fs24.default.existsSync(directory)) return [];
19673
20106
  const result = [];
19674
- for (const ref of import_node_fs22.default.readdirSync(directory)) {
20107
+ for (const ref of import_node_fs24.default.readdirSync(directory)) {
19675
20108
  if (!opaque.test(ref)) unavailable();
19676
- const target = import_node_path14.default.join(directory, ref, "metadata.json");
20109
+ const target = import_node_path18.default.join(directory, ref, "metadata.json");
19677
20110
  assertSafeNodePath(root, target);
19678
- if (!import_node_fs22.default.statSync(target).isFile() || import_node_fs22.default.statSync(target).size > 16384) unavailable();
19679
- const record = JSON.parse(import_node_fs22.default.readFileSync(target, "utf8"));
20111
+ if (!import_node_fs24.default.statSync(target).isFile() || import_node_fs24.default.statSync(target).size > 16384) unavailable();
20112
+ const record = JSON.parse(import_node_fs24.default.readFileSync(target, "utf8"));
19680
20113
  if (record.ref !== ref || record.sessionId !== sessionId || record.status !== "active" || !["image", "document"].includes(record.kind) || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0 || record.expiresAt !== record.createdAt + CHAT_ATTACHMENT_TTL_MS || !Array.isArray(record.pages) || record.pages.length > 20) unavailable();
19681
20114
  for (const page of record.pages) if (!opaque.test(page.ref)) unavailable();
19682
20115
  result.push(record);
@@ -19687,7 +20120,7 @@ function createNodeChatAttachmentStore(options) {
19687
20120
  return { ref: record.ref, sessionId: record.sessionId, kind: record.kind, expiresAt: record.expiresAt };
19688
20121
  }
19689
20122
  function active(record) {
19690
- return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !import_node_fs22.default.existsSync(import_node_path14.default.join(retiredRoot, `${record.ref}.json`));
20123
+ return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !import_node_fs24.default.existsSync(import_node_path18.default.join(retiredRoot, `${record.ref}.json`));
19691
20124
  }
19692
20125
  function sanitizeSession(session) {
19693
20126
  try {
@@ -19726,17 +20159,17 @@ function createNodeChatAttachmentStore(options) {
19726
20159
  return !opaque.test(ref);
19727
20160
  }
19728
20161
  )) unavailable();
19729
- const directory = import_node_path14.default.join(dataRoot, item.sessionId, item.ref);
20162
+ const directory = import_node_path18.default.join(dataRoot, item.sessionId, item.ref);
19730
20163
  assertSafeNodePath(root, directory);
19731
- import_node_fs22.default.rmSync(directory, { recursive: true, force: true });
20164
+ import_node_fs24.default.rmSync(directory, { recursive: true, force: true });
19732
20165
  await removePresentationRefs(item.sessionId, item.refs);
19733
- import_node_fs22.default.rmSync(import_node_path14.default.join(retiredRoot, `${item.ref}.json`), { force: true });
20166
+ import_node_fs24.default.rmSync(import_node_path18.default.join(retiredRoot, `${item.ref}.json`), { force: true });
19734
20167
  }
19735
20168
  async function retire(record) {
19736
20169
  const item = { sessionId: record.sessionId, ref: record.ref, refs: [record.ref, ...record.pages.map(function pageRef(page) {
19737
20170
  return page.ref;
19738
20171
  })] };
19739
- atomicReplace(import_node_path14.default.join(retiredRoot, `${record.ref}.json`), JSON.stringify(item));
20172
+ atomicReplace(import_node_path18.default.join(retiredRoot, `${record.ref}.json`), JSON.stringify(item));
19740
20173
  await finishRetirement(item);
19741
20174
  }
19742
20175
  async function put(input) {
@@ -19769,13 +20202,13 @@ function createNodeChatAttachmentStore(options) {
19769
20202
  const createdAt = now();
19770
20203
  if (!Number.isSafeInteger(createdAt) || createdAt < 0) unavailable();
19771
20204
  const ref = (0, import_node_crypto10.randomUUID)();
19772
- const parent = import_node_path14.default.join(dataRoot, sessionKey(input.sessionId));
20205
+ const parent = import_node_path18.default.join(dataRoot, sessionKey(input.sessionId));
19773
20206
  ensureChatDirectory(root, parent);
19774
- const staging = import_node_path14.default.join(root, `staging-${ref}`);
20207
+ const staging = import_node_path18.default.join(root, `staging-${ref}`);
19775
20208
  const record = { ref, sessionId: input.sessionId, kind, mimeType, byteLength: bytes.length, sha256: digest(bytes), createdAt, expiresAt: createdAt + CHAT_ATTACHMENT_TTL_MS, status: "active", displayName: input.displayName.split(/[\\/]/).at(-1).replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 120) || "\u9644\u4EF6", pages: [] };
19776
20209
  try {
19777
20210
  ensureChatDirectory(root, staging);
19778
- import_node_fs22.default.writeFileSync(import_node_path14.default.join(staging, "content"), bytes, { flag: "wx", mode: 384 });
20211
+ import_node_fs24.default.writeFileSync(import_node_path18.default.join(staging, "content"), bytes, { flag: "wx", mode: 384 });
19779
20212
  let pageBytes = 0;
19780
20213
  for (const inputPage of parsed?.pages ?? []) {
19781
20214
  const page = Buffer.from(inputPage);
@@ -19783,17 +20216,17 @@ function createNodeChatAttachmentStore(options) {
19783
20216
  pageBytes += page.length;
19784
20217
  if (!type2.startsWith("image/") || !page.length || page.length > IMAGE_BYTES || pageBytes > MAX_BYTES) unavailable();
19785
20218
  const pageRef = (0, import_node_crypto10.randomUUID)();
19786
- import_node_fs22.default.writeFileSync(import_node_path14.default.join(staging, pageRef), page, { flag: "wx", mode: 384 });
20219
+ import_node_fs24.default.writeFileSync(import_node_path18.default.join(staging, pageRef), page, { flag: "wx", mode: 384 });
19787
20220
  record.pages.push({ ref: pageRef, mimeType: type2, byteLength: page.length, sha256: digest(page) });
19788
20221
  }
19789
- if (parsed) import_node_fs22.default.writeFileSync(import_node_path14.default.join(staging, "parsed.json"), JSON.stringify({ text: parsed.text.slice(0, 16e3) }), { flag: "wx", mode: 384 });
19790
- import_node_fs22.default.writeFileSync(import_node_path14.default.join(staging, "metadata.json"), JSON.stringify(record), { flag: "wx", mode: 384 });
20222
+ if (parsed) import_node_fs24.default.writeFileSync(import_node_path18.default.join(staging, "parsed.json"), JSON.stringify({ text: parsed.text.slice(0, 16e3) }), { flag: "wx", mode: 384 });
20223
+ import_node_fs24.default.writeFileSync(import_node_path18.default.join(staging, "metadata.json"), JSON.stringify(record), { flag: "wx", mode: 384 });
19791
20224
  checkSignal(input.signal);
19792
- import_node_fs22.default.renameSync(staging, import_node_path14.default.join(parent, ref));
20225
+ import_node_fs24.default.renameSync(staging, import_node_path18.default.join(parent, ref));
19793
20226
  const { pages: _pages, ...view } = record;
19794
20227
  return view;
19795
20228
  } finally {
19796
- import_node_fs22.default.rmSync(staging, { recursive: true, force: true });
20229
+ import_node_fs24.default.rmSync(staging, { recursive: true, force: true });
19797
20230
  }
19798
20231
  }, input.signal);
19799
20232
  } catch (error) {
@@ -19835,10 +20268,10 @@ function createNodeChatAttachmentStore(options) {
19835
20268
  return locked(async function readParsed() {
19836
20269
  const { record, page } = await find3(sessionId, ref);
19837
20270
  if (page || record.kind !== "document") unavailable();
19838
- const target = import_node_path14.default.join(dataRoot, sessionId, ref, "parsed.json");
20271
+ const target = import_node_path18.default.join(dataRoot, sessionId, ref, "parsed.json");
19839
20272
  assertSafeNodePath(root, target);
19840
- if (import_node_fs22.default.statSync(target).size > 1e5) unavailable();
19841
- const parsed = JSON.parse(import_node_fs22.default.readFileSync(target, "utf8"));
20273
+ if (import_node_fs24.default.statSync(target).size > 1e5) unavailable();
20274
+ const parsed = JSON.parse(import_node_fs24.default.readFileSync(target, "utf8"));
19842
20275
  if (typeof parsed.text !== "string") unavailable();
19843
20276
  return { text: parsed.text.slice(0, 16e3), pageImages: record.pages.map(function pageGrant(item) {
19844
20277
  return grant({ ...record, ref: item.ref, kind: "image" });
@@ -19848,44 +20281,44 @@ function createNodeChatAttachmentStore(options) {
19848
20281
  async function readBytes(sessionId, ref, signal) {
19849
20282
  return locked(async function readContent() {
19850
20283
  const { record, page } = await find3(sessionId, ref);
19851
- const target = import_node_path14.default.join(dataRoot, sessionId, record.ref, page?.ref ?? "content");
20284
+ const target = import_node_path18.default.join(dataRoot, sessionId, record.ref, page?.ref ?? "content");
19852
20285
  assertSafeNodePath(root, target);
19853
20286
  const metadata = page ?? record;
19854
- if (import_node_fs22.default.statSync(target).size !== metadata.byteLength || metadata.byteLength > MAX_BYTES) unavailable();
19855
- const bytes = import_node_fs22.default.readFileSync(target);
20287
+ if (import_node_fs24.default.statSync(target).size !== metadata.byteLength || metadata.byteLength > MAX_BYTES) unavailable();
20288
+ const bytes = import_node_fs24.default.readFileSync(target);
19856
20289
  if (digest(bytes) !== metadata.sha256) unavailable();
19857
20290
  return { bytes: new Uint8Array(bytes), mimeType: metadata.mimeType };
19858
20291
  }, signal);
19859
20292
  }
19860
20293
  async function deleteBySession(sessionId) {
19861
20294
  await locked(async function deleteSessionAttachments() {
19862
- atomicReplace(import_node_path14.default.join(deletingRoot, `${sessionKey(sessionId)}.json`), JSON.stringify({ sessionId }));
20295
+ atomicReplace(import_node_path18.default.join(deletingRoot, `${sessionKey(sessionId)}.json`), JSON.stringify({ sessionId }));
19863
20296
  for (const record of records(sessionId)) await retire(record);
19864
20297
  await removePresentationRefs(sessionId);
19865
- import_node_fs22.default.rmSync(import_node_path14.default.join(dataRoot, sessionId), { recursive: true, force: true });
20298
+ import_node_fs24.default.rmSync(import_node_path18.default.join(dataRoot, sessionId), { recursive: true, force: true });
19866
20299
  }, void 0, "CHAT_ATTACHMENT_CLEANUP_FAILED");
19867
20300
  }
19868
20301
  async function cleanupExpired(input = {}) {
19869
20302
  const limit = input.limit ?? 32;
19870
20303
  if (!Number.isInteger(limit) || limit < 1 || limit > 128) throw new NodeChatError("CHAT_ATTACHMENT_CLEANUP_FAILED");
19871
20304
  return locked(async function cleanupBatch() {
19872
- for (const file of import_node_fs22.default.readdirSync(root)) {
20305
+ for (const file of import_node_fs24.default.readdirSync(root)) {
19873
20306
  if (!/^staging-[0-9a-f-]{36}$/.test(file)) continue;
19874
- const target = import_node_path14.default.join(root, file);
20307
+ const target = import_node_path18.default.join(root, file);
19875
20308
  assertSafeNodePath(root, target);
19876
- import_node_fs22.default.rmSync(target, { recursive: true, force: true });
20309
+ import_node_fs24.default.rmSync(target, { recursive: true, force: true });
19877
20310
  }
19878
- for (const file of import_node_fs22.default.readdirSync(retiredRoot)) {
20311
+ for (const file of import_node_fs24.default.readdirSync(retiredRoot)) {
19879
20312
  if (!file.endsWith(".json")) continue;
19880
- const target = import_node_path14.default.join(retiredRoot, file);
20313
+ const target = import_node_path18.default.join(retiredRoot, file);
19881
20314
  assertSafeNodePath(root, target);
19882
20315
  checkSignal(input.signal);
19883
- const item = JSON.parse(import_node_fs22.default.readFileSync(target, "utf8"));
20316
+ const item = JSON.parse(import_node_fs24.default.readFileSync(target, "utf8"));
19884
20317
  if (file !== `${item.ref}.json`) unavailable();
19885
20318
  await finishRetirement(item);
19886
20319
  }
19887
20320
  const expired = [];
19888
- for (const sessionId of import_node_fs22.default.readdirSync(dataRoot)) {
20321
+ for (const sessionId of import_node_fs24.default.readdirSync(dataRoot)) {
19889
20322
  for (const record of records(sessionId)) if (record.expiresAt <= now() || isSessionDeleting(sessionId)) expired.push(record);
19890
20323
  }
19891
20324
  expired.sort(function oldestFirst(left, right) {
@@ -20118,197 +20551,9 @@ function createNodeRagRuntime(options) {
20118
20551
  };
20119
20552
  }
20120
20553
 
20121
- // src/node/settings/user-config-directory.ts
20122
- var import_node_fs23 = __toESM(require("node:fs"));
20123
- var import_node_os4 = __toESM(require("node:os"));
20124
- var import_node_path15 = __toESM(require("node:path"));
20125
- var UserConfigDirectoryError = class extends Error {
20126
- constructor(code) {
20127
- super(code);
20128
- this.code = code;
20129
- this.name = "UserConfigDirectoryError";
20130
- }
20131
- };
20132
- function resolveUserHome(homeDirectory) {
20133
- let candidate = homeDirectory;
20134
- if (candidate === void 0) {
20135
- try {
20136
- candidate = import_node_os4.default.homedir();
20137
- } catch {
20138
- throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
20139
- }
20140
- }
20141
- if (!candidate || !import_node_path15.default.isAbsolute(candidate)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
20142
- return import_node_path15.default.resolve(candidate);
20143
- }
20144
- function readEntry(entryPath) {
20145
- try {
20146
- return import_node_fs23.default.lstatSync(entryPath);
20147
- } catch (error) {
20148
- if (error.code === "ENOENT") return void 0;
20149
- throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
20150
- }
20151
- }
20152
- function isWithinHome(homeDirectory, configDirectory) {
20153
- const relative = import_node_path15.default.relative(homeDirectory, configDirectory);
20154
- return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${import_node_path15.default.sep}`) && !import_node_path15.default.isAbsolute(relative);
20155
- }
20156
- function assertSafeConfigDirectory(homeDirectory, configDirectory) {
20157
- const entry = readEntry(configDirectory);
20158
- if (!entry) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
20159
- if (entry.isSymbolicLink()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
20160
- if (!entry.isDirectory()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_NOT_DIRECTORY");
20161
- try {
20162
- const canonicalHome = import_node_fs23.default.realpathSync.native(homeDirectory);
20163
- const canonicalConfigDirectory = import_node_fs23.default.realpathSync.native(configDirectory);
20164
- if (!isWithinHome(canonicalHome, canonicalConfigDirectory)) {
20165
- throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
20166
- }
20167
- } catch (error) {
20168
- if (error instanceof UserConfigDirectoryError) throw error;
20169
- throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
20170
- }
20171
- }
20172
- function ensureUserConfigDirectory(options = {}) {
20173
- const homeDirectory = resolveUserHome(options.homeDirectory);
20174
- const configDirectory = import_node_path15.default.join(homeDirectory, ".autopilot");
20175
- const existing = readEntry(configDirectory);
20176
- if (existing) assertSafeConfigDirectory(homeDirectory, configDirectory);
20177
- else {
20178
- try {
20179
- import_node_fs23.default.mkdirSync(configDirectory, { recursive: true, mode: 448 });
20180
- } catch {
20181
- throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
20182
- }
20183
- assertSafeConfigDirectory(homeDirectory, configDirectory);
20184
- }
20185
- return configDirectory;
20186
- }
20187
-
20188
- // src/node/settings/node-settings-loader.ts
20189
- var import_node_fs24 = __toESM(require("node:fs"));
20190
- var import_node_os5 = __toESM(require("node:os"));
20191
- var import_node_path16 = __toESM(require("node:path"));
20192
- var import_core13 = require("@autopilot-agent/core");
20193
- function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = import_node_path16.default) {
20194
- try {
20195
- const home = homeDirectory ?? import_node_os5.default.homedir();
20196
- if (!pathApi.isAbsolute(home)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
20197
- return pathApi.join(home, ".autopilot", "settings.json");
20198
- } catch {
20199
- throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
20200
- }
20201
- }
20202
- function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = import_node_os5.default.homedir(), pathApi = import_node_path16.default) {
20203
- const root = pathApi.resolve(workspaceRoot);
20204
- return {
20205
- user: pathApi.join(homeDirectory, ".autopilot", "settings.json"),
20206
- project: pathApi.join(root, ".autopilot", "settings.json"),
20207
- local: pathApi.join(root, ".autopilot", "settings.local.json")
20208
- };
20209
- }
20210
- function createNodeSettingsLoader(options = {}) {
20211
- const debounceMs = options.debounceMs ?? 100;
20212
- function isSafeSettingsFile(filePath) {
20213
- try {
20214
- const file = import_node_fs24.default.lstatSync(filePath);
20215
- const configDirectory = import_node_path16.default.dirname(filePath);
20216
- const directory = import_node_fs24.default.lstatSync(configDirectory);
20217
- if (!file.isFile() || file.isSymbolicLink() || !directory.isDirectory() || directory.isSymbolicLink()) return false;
20218
- const canonicalDirectory = import_node_fs24.default.realpathSync.native(configDirectory);
20219
- const canonicalFile = import_node_fs24.default.realpathSync.native(filePath);
20220
- const relative = import_node_path16.default.relative(canonicalDirectory, canonicalFile);
20221
- return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${import_node_path16.default.sep}`) && !import_node_path16.default.isAbsolute(relative);
20222
- } catch (error) {
20223
- return error.code === "ENOENT";
20224
- }
20225
- }
20226
- function readSource(scope, filePath) {
20227
- if (!import_node_fs24.default.existsSync(filePath)) {
20228
- try {
20229
- if (import_node_fs24.default.lstatSync(filePath).isSymbolicLink()) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
20230
- } catch {
20231
- return void 0;
20232
- }
20233
- return void 0;
20234
- }
20235
- if (!isSafeSettingsFile(filePath)) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
20236
- try {
20237
- return { scope, value: JSON.parse(import_node_fs24.default.readFileSync(filePath, "utf8")), diagnostics: [] };
20238
- } catch {
20239
- return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_JSON_INVALID" }] };
20240
- }
20241
- }
20242
- function load2(workspaceRoot) {
20243
- return loadPaths(resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory));
20244
- }
20245
- function loadUser() {
20246
- return loadPaths({ user: resolveNodeUserSettingsPath(options.homeDirectory) });
20247
- }
20248
- function loadPaths(paths) {
20249
- const sources = Object.entries(paths).map(function readEntry2([scope, filePath]) {
20250
- return readSource(scope, filePath);
20251
- }).filter((source) => Boolean(source));
20252
- const settings = (0, import_core13.resolveAutopilotSettings)(sources.map(({ scope, value }) => ({ scope, value })));
20253
- const diagnostics = [...settings.diagnostics, ...sources.flatMap((source) => source.diagnostics)];
20254
- return { paths, settings: { ...settings, diagnostics } };
20255
- }
20256
- function watch(workspaceRoot, onReload) {
20257
- const paths = resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory);
20258
- return watchPaths(Object.values(paths), function reloadWorkspace() {
20259
- onReload(load2(workspaceRoot));
20260
- });
20261
- }
20262
- function watchUser(onReload) {
20263
- return watchPaths([resolveNodeUserSettingsPath(options.homeDirectory)], function reloadUser() {
20264
- onReload(loadUser());
20265
- });
20266
- }
20267
- function watchPaths(watched, reload) {
20268
- let timer;
20269
- let watchers = [];
20270
- function installWatchers() {
20271
- for (const watcher of watchers) watcher.close();
20272
- const uniqueDirectories = [...new Set(watched.flatMap(function collectWatchDirectories(filePath) {
20273
- const directory = import_node_path16.default.dirname(filePath);
20274
- return [directory, import_node_path16.default.dirname(directory)];
20275
- }))].filter(
20276
- /** 不把用户配置目录的链接目标注册为监听面;父目录仍能观察链接被替换。 */
20277
- function safeWatchDirectory(directory) {
20278
- return import_node_fs24.default.existsSync(directory) && import_node_fs24.default.lstatSync(directory).isDirectory() && !import_node_fs24.default.lstatSync(directory).isSymbolicLink();
20279
- }
20280
- );
20281
- watchers = uniqueDirectories.flatMap(function watchParent(directory) {
20282
- try {
20283
- const watcher = import_node_fs24.default.watch(directory, function reloadOnTargetFile(_eventType, fileName) {
20284
- if (!fileName || !watched.some((target) => import_node_path16.default.basename(target) === fileName.toString() || import_node_path16.default.basename(import_node_path16.default.dirname(target)) === fileName.toString())) return;
20285
- if (timer) clearTimeout(timer);
20286
- timer = setTimeout(function reloadAfterDebounce() {
20287
- reload();
20288
- installWatchers();
20289
- }, debounceMs);
20290
- });
20291
- watcher.unref();
20292
- watcher.on("error", function ignoreWatcherError() {
20293
- });
20294
- return [watcher];
20295
- } catch {
20296
- return [];
20297
- }
20298
- });
20299
- }
20300
- installWatchers();
20301
- return function stopWatchingSettings() {
20302
- if (timer) clearTimeout(timer);
20303
- for (const watcher of watchers) watcher.close();
20304
- };
20305
- }
20306
- return { load: load2, watch, loadUser, watchUser };
20307
- }
20308
-
20309
20554
  // src/node/settings/node-settings-writer.ts
20310
20555
  var import_node_fs25 = __toESM(require("node:fs"));
20311
- var import_core14 = require("@autopilot-agent/core");
20556
+ var import_core15 = require("@autopilot-agent/core");
20312
20557
  var CONFIG_KEY_ALLOWLIST = /* @__PURE__ */ new Set([
20313
20558
  "model",
20314
20559
  "effortLevel",
@@ -20353,7 +20598,7 @@ function createNodeSettingsWriter(options = {}) {
20353
20598
  cursor = cursor[part];
20354
20599
  }
20355
20600
  cursor[parts[parts.length - 1]] = parsedValue;
20356
- (0, import_core14.resolveAutopilotSettings)([{ scope, value: target }]);
20601
+ (0, import_core15.resolveAutopilotSettings)([{ scope, value: target }]);
20357
20602
  atomicReplace(getPaths(workspaceRoot)[scope], JSON.stringify(target, null, 2));
20358
20603
  return toSafeView(target);
20359
20604
  }
@@ -20420,7 +20665,7 @@ function parseConfigValue(key2, rawValue) {
20420
20665
  // src/node/settings/node-user-settings-service.ts
20421
20666
  var import_node_crypto11 = require("node:crypto");
20422
20667
  var import_node_fs26 = __toESM(require("node:fs"));
20423
- var import_core15 = require("@autopilot-agent/core");
20668
+ var import_core16 = require("@autopilot-agent/core");
20424
20669
  var RAG_ROLE_CONTRACT = Object.freeze({
20425
20670
  textRerank: { provider: "bailian", key: "RAG_TEXT_RERANK_API_KEY", dimension: false },
20426
20671
  visionRerank: { provider: "bailian", key: "RAG_VISION_RERANK_API_KEY", dimension: false },
@@ -20428,11 +20673,24 @@ var RAG_ROLE_CONTRACT = Object.freeze({
20428
20673
  multimodalEmbedding: { provider: "dashscope", key: "RAG_MULTIMODAL_EMBEDDING_API_KEY", dimension: true }
20429
20674
  });
20430
20675
  var NodeUserSettingsError = class extends Error {
20431
- constructor(code) {
20676
+ constructor(code, diagnostic) {
20432
20677
  super(code);
20433
20678
  this.code = code;
20679
+ this.diagnostic = diagnostic;
20434
20680
  }
20435
20681
  };
20682
+ function safeDiagnostic(diagnostic) {
20683
+ return { code: diagnostic.code, scope: diagnostic.scope, ...diagnostic.field ? { field: diagnostic.field } : {} };
20684
+ }
20685
+ function splitDiagnostics(diagnostics) {
20686
+ const blocking = [];
20687
+ const permissions = [];
20688
+ for (const diagnostic of diagnostics) {
20689
+ if ((0, import_core16.isExternalPermissionDiagnostic)(diagnostic)) permissions.push(safeDiagnostic(diagnostic));
20690
+ else blocking.push(diagnostic);
20691
+ }
20692
+ return { blocking, permissions };
20693
+ }
20436
20694
  function isRecord4(value) {
20437
20695
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
20438
20696
  }
@@ -20512,7 +20770,7 @@ function removeLegacyPrimaryRoutes(raw, environment) {
20512
20770
  for (const key2 of removedKeys) if (!hasCredentialReference(raw, key2)) delete environment[key2];
20513
20771
  }
20514
20772
  function normalizeMainInput(input) {
20515
- const baseUrl = (0, import_core15.normalizeProviderBaseUrl)(input.baseUrl);
20773
+ const baseUrl = (0, import_core16.normalizeProviderBaseUrl)(input.baseUrl);
20516
20774
  const model = parseSettingString(input.model);
20517
20775
  const apiKey = parseApiKey(input.apiKey);
20518
20776
  const availableModels = input.availableModels?.map(function parseModel(value) {
@@ -20534,9 +20792,9 @@ function applyMainCategory(raw, input) {
20534
20792
  return candidate.value;
20535
20793
  }))];
20536
20794
  if (!normalized.apiKey && distinct.length > 1) throw new NodeUserSettingsError("SETTINGS_MIGRATION_CONFLICT");
20537
- const previous = (0, import_core15.resolveAutopilotSettings)([{ scope: "user", value: raw }]);
20795
+ const previous = (0, import_core16.resolveAutopilotSettings)([{ scope: "user", value: raw }]);
20538
20796
  const previousRoute = previous.modelRef && previous.providerRoutes[previous.modelRef.provider];
20539
- const previousBaseUrl = (0, import_core15.normalizeProviderBaseUrl)(previousRoute?.baseUrl ?? previous.firstParty.baseUrl);
20797
+ const previousBaseUrl = (0, import_core16.normalizeProviderBaseUrl)(previousRoute?.baseUrl ?? previous.firstParty.baseUrl);
20540
20798
  const officialDeepSeekMigration = previousBaseUrl === "https://api.deepseek.com" && normalized.baseUrl === "https://api.deepseek.com/anthropic";
20541
20799
  if (!normalized.apiKey && previousBaseUrl !== normalized.baseUrl && !officialDeepSeekMigration) throw new NodeUserSettingsError("SETTINGS_KEY_REQUIRED");
20542
20800
  const apiKey = normalized.apiKey ?? distinct[0];
@@ -20577,10 +20835,10 @@ function applyWebSearch(raw, input) {
20577
20835
  return;
20578
20836
  }
20579
20837
  const provider = input.provider;
20580
- const baseUrl = (0, import_core15.normalizeProviderBaseUrl)(input.baseUrl);
20838
+ const baseUrl = (0, import_core16.normalizeProviderBaseUrl)(input.baseUrl);
20581
20839
  const model = parseSettingString(input.model);
20582
20840
  const environment = { ...isRecord4(raw.env) ? raw.env : {} };
20583
- const mainBaseUrl = (0, import_core15.normalizeProviderBaseUrl)(environment.ANTHROPIC_BASE_URL);
20841
+ const mainBaseUrl = (0, import_core16.normalizeProviderBaseUrl)(environment.ANTHROPIC_BASE_URL);
20584
20842
  const canReuseMainKey = mainBaseUrl === "https://api.deepseek.com/anthropic" && Boolean(readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY"));
20585
20843
  if (input.useMainKey) {
20586
20844
  if (!canReuseMainKey) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
@@ -20595,7 +20853,7 @@ function applyWebSearch(raw, input) {
20595
20853
  const apiKey = parseApiKey(input.apiKey);
20596
20854
  const current = isRecord4(raw.webSearch) ? raw.webSearch : void 0;
20597
20855
  const currentRef = current && isRecord4(current.credentialRef) ? current.credentialRef : void 0;
20598
- const sameConnection = current?.provider === provider && (0, import_core15.normalizeProviderBaseUrl)(current?.baseUrl) === baseUrl;
20856
+ const sameConnection = current?.provider === provider && (0, import_core16.normalizeProviderBaseUrl)(current?.baseUrl) === baseUrl;
20599
20857
  const preservedKeyName = sameConnection ? parseSettingString(currentRef?.key) : void 0;
20600
20858
  const preservedKey = readEnvironmentKey(environment, preservedKeyName);
20601
20859
  if (provider !== "deepseek" && provider !== "openai-compatible" && provider !== "xiaomi-mimo" || !baseUrl || !model || !apiKey && !preservedKey) {
@@ -20614,7 +20872,7 @@ function applyRagRole(raw, role, input) {
20614
20872
  delete rag[role];
20615
20873
  delete environment[contract.key];
20616
20874
  } else {
20617
- const baseUrl = (0, import_core15.normalizeProviderBaseUrl)(input.baseUrl);
20875
+ const baseUrl = (0, import_core16.normalizeProviderBaseUrl)(input.baseUrl);
20618
20876
  const model = parseSettingString(input.model);
20619
20877
  const apiKey = parseApiKey(input.apiKey);
20620
20878
  const current = isRecord4(rag[role]) ? rag[role] : void 0;
@@ -20639,9 +20897,8 @@ function createNodeUserSettingsService(options = {}) {
20639
20897
  const current = readUserSettings(settingsPath);
20640
20898
  assertRevision(current.original, revision);
20641
20899
  update2(current.raw);
20642
- const resolved = (0, import_core15.resolveAutopilotSettings)([{ scope: "user", value: current.raw }]);
20643
- const blockingDiagnostics = resolved.diagnostics;
20644
- if (blockingDiagnostics.length > 0) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
20900
+ const { blocking } = splitDiagnostics((0, import_core16.resolveAutopilotSettings)([{ scope: "user", value: current.raw }]).diagnostics);
20901
+ if (blocking.length > 0) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID", safeDiagnostic(blocking[0]));
20645
20902
  const content = `${JSON.stringify(current.raw, null, 2)}
20646
20903
  `;
20647
20904
  atomicReplace(settingsPath, content);
@@ -20654,7 +20911,7 @@ function createNodeUserSettingsService(options = {}) {
20654
20911
  const maintained = ["deepseek-v4-pro[1m]", "deepseek-v4-flash"];
20655
20912
  const current = readUserSettings(settingsPath);
20656
20913
  const environment = isRecord4(current.raw.env) ? current.raw.env : {};
20657
- const baseUrl = (0, import_core15.normalizeProviderBaseUrl)(environment.ANTHROPIC_BASE_URL);
20914
+ const baseUrl = (0, import_core16.normalizeProviderBaseUrl)(environment.ANTHROPIC_BASE_URL);
20658
20915
  const apiKey = readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY");
20659
20916
  if (baseUrl !== "https://api.deepseek.com/anthropic" || !apiKey) return { models: maintained, source: "maintained" };
20660
20917
  try {
@@ -20677,9 +20934,9 @@ function createNodeUserSettingsService(options = {}) {
20677
20934
  const current = readUserSettings(settingsPath);
20678
20935
  const raw = current.raw;
20679
20936
  const environment = isRecord4(raw.env) ? raw.env : {};
20680
- const resolved = (0, import_core15.resolveAutopilotSettings)([{ scope: "user", value: raw }]);
20681
- const blockingDiagnostics = resolved.diagnostics;
20682
- if (blockingDiagnostics.length > 0) throw new NodeUserSettingsError("SETTINGS_INVALID");
20937
+ const resolved = (0, import_core16.resolveAutopilotSettings)([{ scope: "user", value: raw }]);
20938
+ const { blocking, permissions } = splitDiagnostics(resolved.diagnostics);
20939
+ if (blocking.length > 0) throw new NodeUserSettingsError("SETTINGS_INVALID", safeDiagnostic(blocking[0]));
20683
20940
  const mainBaseUrl = resolved.firstParty.baseUrl ?? "https://api.deepseek.com/anthropic";
20684
20941
  const mainModel = resolved.modelRef?.modelId ?? "deepseek-v4-flash";
20685
20942
  const mainKey = readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY");
@@ -20724,6 +20981,7 @@ function createNodeUserSettingsService(options = {}) {
20724
20981
  model: search?.model ?? "deepseek-v4-flash",
20725
20982
  configured: Boolean(search && searchKey)
20726
20983
  },
20984
+ diagnostics: permissions,
20727
20985
  rag
20728
20986
  };
20729
20987
  },
@@ -20763,15 +21021,15 @@ function createNodeUserSettingsService(options = {}) {
20763
21021
  // src/node/capabilities/memory-retriever.ts
20764
21022
  var import_node_crypto12 = __toESM(require("node:crypto"));
20765
21023
  var import_node_fs27 = __toESM(require("node:fs"));
20766
- var import_node_path17 = __toESM(require("node:path"));
21024
+ var import_node_path19 = __toESM(require("node:path"));
20767
21025
  function getNodeMemoryWorkspaceId(workspaceRoot) {
20768
21026
  return import_node_crypto12.default.createHash("sha256").update(import_node_fs27.default.realpathSync.native(workspaceRoot).toLowerCase()).digest("hex").slice(0, 24);
20769
21027
  }
20770
21028
  function getNodeMemoryDirectory(stateRoot, workspaceRoot) {
20771
- return import_node_path17.default.join(import_node_path17.default.resolve(stateRoot), "memory", getNodeMemoryWorkspaceId(workspaceRoot));
21029
+ return import_node_path19.default.join(import_node_path19.default.resolve(stateRoot), "memory", getNodeMemoryWorkspaceId(workspaceRoot));
20772
21030
  }
20773
21031
  function getLegacyWebMemoryDirectory(workspaceRoot, cwd = process.cwd()) {
20774
- return import_node_path17.default.join(import_node_path17.default.resolve(cwd), ".local", "agent", "workspaces", getNodeMemoryWorkspaceId(workspaceRoot), "memory");
21032
+ return import_node_path19.default.join(import_node_path19.default.resolve(cwd), ".local", "agent", "workspaces", getNodeMemoryWorkspaceId(workspaceRoot), "memory");
20775
21033
  }
20776
21034
  function retrieveNodeMemories(_stateRoot, _workspaceRoot, _query, _maxItems = 5) {
20777
21035
  return [];
@@ -20779,10 +21037,10 @@ function retrieveNodeMemories(_stateRoot, _workspaceRoot, _query, _maxItems = 5)
20779
21037
 
20780
21038
  // src/node/trust-policy.ts
20781
21039
  var import_node_fs28 = __toESM(require("node:fs"));
20782
- var import_node_path18 = __toESM(require("node:path"));
21040
+ var import_node_path20 = __toESM(require("node:path"));
20783
21041
  function createNodeTrustStore(options) {
20784
21042
  const trustRoot = resolveNodeTrustRoot({ stateRoot: options.stateRoot, trustRoot: options.trustRoot });
20785
- const trustFile = import_node_path18.default.join(trustRoot, "trust.json");
21043
+ const trustFile = import_node_path20.default.join(trustRoot, "trust.json");
20786
21044
  const now = options.now ?? (() => Date.now());
20787
21045
  function ensureDir() {
20788
21046
  import_node_fs28.default.mkdirSync(trustRoot, { recursive: true });
@@ -20893,10 +21151,10 @@ function createNodeTrustPolicy(options) {
20893
21151
 
20894
21152
  // src/node/workspace-registry.ts
20895
21153
  var import_node_fs29 = __toESM(require("node:fs"));
20896
- var import_node_path19 = __toESM(require("node:path"));
21154
+ var import_node_path21 = __toESM(require("node:path"));
20897
21155
  function createNodeWorkspaceRegistry(options = {}) {
20898
21156
  const globalStateRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: options.cwd });
20899
- const registryPath = import_node_path19.default.join(globalStateRoot, "workspace-registry.json");
21157
+ const registryPath = import_node_path21.default.join(globalStateRoot, "workspace-registry.json");
20900
21158
  const now = options.now ?? (() => Date.now());
20901
21159
  function load2() {
20902
21160
  if (!import_node_fs29.default.existsSync(registryPath)) return [];
@@ -20924,7 +21182,7 @@ function createNodeWorkspaceRegistry(options = {}) {
20924
21182
  const next = {
20925
21183
  workspaceId,
20926
21184
  workspaceRoot: canonicalRoot,
20927
- displayName: import_node_path19.default.basename(canonicalRoot) || canonicalRoot,
21185
+ displayName: import_node_path21.default.basename(canonicalRoot) || canonicalRoot,
20928
21186
  lastOpenedAt: now()
20929
21187
  };
20930
21188
  const entries2 = load2().filter(function removeExisting(entry) {
@@ -20971,7 +21229,9 @@ function createNodeWorkspaceRegistry(options = {}) {
20971
21229
  createNodeClock,
20972
21230
  createNodeCredentialStore,
20973
21231
  createNodeEventSink,
21232
+ createNodeExternalPermissionProjector,
20974
21233
  createNodeFileMutationStore,
21234
+ createNodeHostExecutionSandboxPort,
20975
21235
  createNodeInputInbox,
20976
21236
  createNodeJobOwnerProbe,
20977
21237
  createNodeJobStore,
@@ -21006,8 +21266,8 @@ function createNodeWorkspaceRegistry(options = {}) {
21006
21266
  getNodeStatePaths,
21007
21267
  getNodeStateSchemaDiagnostic,
21008
21268
  initializeNodeStateRoot,
21269
+ isSafeSettingsFile,
21009
21270
  loadMcpConfigFromWorkspace,
21010
- readWindowsSandboxCapability,
21011
21271
  resolveNodeChatStatePaths,
21012
21272
  resolveNodeGlobalStateRoot,
21013
21273
  resolveNodeSettingsPaths,
@@ -21015,6 +21275,5 @@ function createNodeWorkspaceRegistry(options = {}) {
21015
21275
  resolveNodeTrustRoot,
21016
21276
  resolveNodeUserSettingsPath,
21017
21277
  retrieveNodeMemories,
21018
- runWindowsSandboxSetup,
21019
21278
  serializePosixCommand
21020
21279
  });