@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/README.md +49 -3
- package/dist/index.d.ts +4 -2
- package/dist/index.js +1323 -1064
- package/dist/index.mjs +1281 -1020
- package/dist/node/create-node-runtime-ports.d.ts +1 -0
- package/dist/node/file-mutation-locks.d.ts +2 -0
- package/dist/node/file-utils.d.ts +3 -1
- package/dist/node/host-mutation-protection.d.ts +7 -0
- package/dist/node/sandbox/node-host-execution-sandbox-port.d.ts +2 -0
- package/dist/node/sandbox/node-sandbox-port.d.ts +1 -1
- package/dist/node/settings/node-external-permission-projector.d.ts +12 -0
- package/dist/node/settings/node-settings-loader.d.ts +1 -0
- package/dist/node/settings/node-user-settings-service.d.ts +8 -1
- package/package.json +2 -2
- package/dist/node/sandbox/windows-sandbox-command.d.ts +0 -9
- package/dist/node/sandbox/windows-sandbox-setup.d.ts +0 -8
package/dist/index.mjs
CHANGED
|
@@ -17332,575 +17332,78 @@ function createNodeCapabilityLoader(options = {}) {
|
|
|
17332
17332
|
};
|
|
17333
17333
|
}
|
|
17334
17334
|
|
|
17335
|
-
// src/node/sandbox/node-sandbox-port.ts
|
|
17336
|
-
import {
|
|
17337
|
-
SANDBOX_ERROR_CODES
|
|
17338
|
-
SandboxPortError
|
|
17339
|
-
} from "@autopilot-agent/core";
|
|
17340
|
-
|
|
17341
|
-
|
|
17342
|
-
|
|
17343
|
-
|
|
17344
|
-
|
|
17345
|
-
|
|
17346
|
-
|
|
17347
|
-
|
|
17348
|
-
|
|
17349
|
-
|
|
17350
|
-
}
|
|
17351
|
-
}
|
|
17352
|
-
function
|
|
17353
|
-
return
|
|
17354
|
-
|
|
17355
|
-
|
|
17356
|
-
|
|
17357
|
-
|
|
17358
|
-
|
|
17359
|
-
|
|
17360
|
-
|
|
17361
|
-
|
|
17362
|
-
|
|
17363
|
-
|
|
17364
|
-
|
|
17365
|
-
|
|
17366
|
-
|
|
17367
|
-
|
|
17368
|
-
installed: true,
|
|
17369
|
-
provisioned,
|
|
17370
|
-
...version !== void 0 ? { version } : {},
|
|
17371
|
-
diagnostics: [
|
|
17372
|
-
`wfp=${status.wfp.state}`,
|
|
17373
|
-
`sandbox_user_provisioned=${status.user.provisioned}`,
|
|
17374
|
-
"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"
|
|
17375
|
-
]
|
|
17376
|
-
};
|
|
17377
|
-
}
|
|
17378
|
-
async function readWindowsSandboxCapability(options = {}) {
|
|
17379
|
-
try {
|
|
17380
|
-
const mod = await (options.loadModule ?? loadSrtRuntimeSurface)();
|
|
17381
|
-
const srtWin = { exe: options.srtWinExe ?? mod.VENDORED_SRT_WIN_EXE, prependArgs: [] };
|
|
17382
|
-
const status = await mod.checkWindowsSandboxStatusAsync({ srtWin });
|
|
17383
|
-
return projectWindowsStatus(mod, status);
|
|
17384
|
-
} catch (error) {
|
|
17385
|
-
throw toSandboxPortError(error);
|
|
17386
|
-
}
|
|
17387
|
-
}
|
|
17388
|
-
async function runWindowsSandboxSetup(options = {}) {
|
|
17389
|
-
try {
|
|
17390
|
-
const mod = await (options.loadModule ?? loadSrtRuntimeSurface)();
|
|
17391
|
-
const srtWin = { exe: options.srtWinExe ?? mod.VENDORED_SRT_WIN_EXE, prependArgs: [] };
|
|
17392
|
-
const result = await mod.installWindowsSandboxAsync({ srtWin });
|
|
17393
|
-
const status = {
|
|
17394
|
-
user: { provisioned: result.user.provisioned, credPresent: result.user.credPresent, realUserSid: "" },
|
|
17395
|
-
wfp: { state: result.wfp.state, filters: result.wfp.filters }
|
|
17396
|
-
};
|
|
17397
|
-
const report = projectWindowsStatus(mod, status);
|
|
17398
|
-
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;
|
|
17399
|
-
} catch (error) {
|
|
17400
|
-
throw toSandboxPortError(error);
|
|
17401
|
-
}
|
|
17402
|
-
}
|
|
17403
|
-
function toSandboxPortError(error) {
|
|
17404
|
-
if (error instanceof SandboxPortError) return error;
|
|
17405
|
-
if (isWindowsSandboxError(error)) {
|
|
17406
|
-
if (error.code === "not_provisioned") return new SandboxPortError(SANDBOX_ERROR_CODES.NOT_PROVISIONED, "Windows \u6C99\u7BB1\u672A\u5B8C\u6210 provision\uFF0C\u8BF7\u5148\u663E\u5F0F\u6267\u884C setup");
|
|
17407
|
-
return new SandboxPortError(SANDBOX_ERROR_CODES.UNAVAILABLE, "Windows \u6C99\u7BB1\u72B6\u6001\u63A2\u6D4B\u5931\u8D25");
|
|
17408
|
-
}
|
|
17409
|
-
return new SandboxPortError(SANDBOX_ERROR_CODES.UNAVAILABLE, "Windows \u6C99\u7BB1 backend \u4E0D\u53EF\u7528");
|
|
17410
|
-
}
|
|
17411
|
-
|
|
17412
|
-
// src/node/sandbox/windows-sandbox-command.ts
|
|
17413
|
-
import fs5 from "node:fs";
|
|
17414
|
-
import path4 from "node:path";
|
|
17415
|
-
import { createHash } from "node:crypto";
|
|
17416
|
-
import { SANDBOX_ERROR_CODES as SANDBOX_ERROR_CODES2, SandboxPortError as SandboxPortError2 } from "@autopilot-agent/core";
|
|
17417
|
-
function resolveWindowsSandboxRunner(vendored, explicit) {
|
|
17418
|
-
if (explicit !== void 0) {
|
|
17419
|
-
if (!path4.win32.isAbsolute(explicit)) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, "Windows runner \u5FC5\u987B\u662F\u5BBF\u4E3B\u6307\u5B9A\u7684\u7EDD\u5BF9\u8DEF\u5F84");
|
|
17420
|
-
return explicit;
|
|
17421
|
-
}
|
|
17422
|
-
const publicRunner = path4.win32.join(process.env.ProgramData ?? "C:\\ProgramData", "AutopilotSandbox", "bin", "srt-win.exe");
|
|
17423
|
-
try {
|
|
17424
|
-
if (createHash("sha256").update(fs5.readFileSync(publicRunner)).digest("hex") === createHash("sha256").update(fs5.readFileSync(vendored)).digest("hex")) return publicRunner;
|
|
17425
|
-
} catch {
|
|
17426
|
-
}
|
|
17427
|
-
return vendored;
|
|
17428
|
-
}
|
|
17429
|
-
function resolveWindowsSandboxCommand(program, args) {
|
|
17430
|
-
if (/^(npm|npx)(\.cmd)?$/i.test(program)) {
|
|
17431
|
-
const nodeRoot = fs5.realpathSync.native(path4.dirname(process.execPath));
|
|
17432
|
-
const cli = fs5.realpathSync.native(path4.join(nodeRoot, "node_modules", "npm", "bin", /^npx/i.test(program) ? "npx-cli.js" : "npm-cli.js"));
|
|
17433
|
-
const relative = path4.relative(nodeRoot, cli);
|
|
17434
|
-
if (relative.startsWith("..") || path4.isAbsolute(relative)) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, "\u53D7\u4FE1 npm CLI \u4E0D\u53EF\u7528");
|
|
17435
|
-
return { exe: process.execPath, args: [cli, ...args] };
|
|
17436
|
-
}
|
|
17437
|
-
const candidates = path4.win32.isAbsolute(program) ? [program] : (process.env.PATH ?? "").split(";").filter(Boolean).map(function candidate(directory) {
|
|
17438
|
-
return path4.win32.join(directory.replace(/^"|"$/g, ""), /\.exe$/i.test(program) ? program : `${program}.exe`);
|
|
17439
|
-
});
|
|
17440
|
-
const exe = candidates.find(function exists(candidate) {
|
|
17441
|
-
return fs5.existsSync(candidate) && fs5.statSync(candidate).isFile();
|
|
17442
|
-
});
|
|
17443
|
-
if (exe === void 0 || !/\.exe$/i.test(exe)) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, "Windows \u539F\u751F\u53EF\u6267\u884C\u7A0B\u5E8F\u4E0D\u53EF\u7528\uFF0C\u547D\u4EE4\u672A\u542F\u52A8");
|
|
17444
|
-
return { exe, args: [...args] };
|
|
17445
|
-
}
|
|
17446
|
-
function finalizeWindowsSandboxArgv(argv, target, tempRoot) {
|
|
17447
|
-
const marker = argv.length - target.args.length - 3;
|
|
17448
|
-
const expected = ["--", target.exe, ...target.args, ""];
|
|
17449
|
-
if (marker < 1 || JSON.stringify(argv.slice(marker)) !== JSON.stringify(expected)) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.RUNNER_FAILED, "Windows \u6C99\u7BB1\u5305\u88C5\u7ED3\u6784\u5F02\u5E38\uFF0C\u547D\u4EE4\u672A\u542F\u52A8");
|
|
17450
|
-
const env = tempRoot === void 0 ? [] : ["TEMP", "TMP", "TMPDIR"].flatMap(function entry(key2) {
|
|
17451
|
-
return ["--env", `${key2}=${tempRoot}`];
|
|
17452
|
-
});
|
|
17453
|
-
return [...argv.slice(0, marker), ...env, ...argv.slice(marker, -1)];
|
|
17454
|
-
}
|
|
17455
|
-
|
|
17456
|
-
// src/node/sandbox/node-sandbox-port.ts
|
|
17457
|
-
var windowsManagerOwners = /* @__PURE__ */ new WeakMap();
|
|
17458
|
-
function posixQuote(value) {
|
|
17459
|
-
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
17460
|
-
}
|
|
17461
|
-
function serializePosixCommand(program, args, tempRoot) {
|
|
17462
|
-
const command = [posixQuote(program), ...args.map(posixQuote)].join(" ");
|
|
17463
|
-
return tempRoot !== void 0 ? `TMPDIR=${posixQuote(tempRoot)} ${command}` : command;
|
|
17464
|
-
}
|
|
17465
|
-
function buildSrtRuntimeConfig(policy) {
|
|
17466
|
-
return {
|
|
17467
|
-
network: {
|
|
17468
|
-
allowedDomains: [...policy.allowedDomains],
|
|
17469
|
-
deniedDomains: []
|
|
17470
|
-
},
|
|
17471
|
-
filesystem: {
|
|
17472
|
-
denyRead: [...policy.deniedRead],
|
|
17473
|
-
// read-only:无任何写授权;workspace-write:仅 canonical 工作区;
|
|
17474
|
-
// danger-full-access:宿主显式冻结后的沙箱最大档位,写全开但仍保留 deny 列表与网络边界。
|
|
17475
|
-
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" ? ["/"] : [],
|
|
17476
|
-
denyWrite: [...policy.deniedWrite]
|
|
17477
|
-
},
|
|
17478
|
-
allowAppleEvents: false
|
|
17479
|
-
};
|
|
17480
|
-
}
|
|
17481
|
-
function createNodeSandboxPort(options) {
|
|
17482
|
-
let module;
|
|
17483
|
-
let initPromise;
|
|
17484
|
-
let initConfigKey;
|
|
17485
|
-
let shutdown = false;
|
|
17486
|
-
let cleanupDiagnostic;
|
|
17487
|
-
const activeExecutions = /* @__PURE__ */ new Set();
|
|
17488
|
-
let windowsRunner;
|
|
17489
|
-
const owner = {};
|
|
17490
|
-
async function ensureModule() {
|
|
17491
|
-
if (!module) {
|
|
17492
|
-
try {
|
|
17493
|
-
module = await (options.loadModule ?? loadSrtRuntimeSurface)();
|
|
17494
|
-
} catch {
|
|
17495
|
-
throw new SandboxPortError3(SANDBOX_ERROR_CODES3.UNAVAILABLE, "\u6C99\u7BB1 backend \u52A0\u8F7D\u5931\u8D25");
|
|
17496
|
-
}
|
|
17497
|
-
}
|
|
17498
|
-
return module;
|
|
17499
|
-
}
|
|
17500
|
-
function toPortError(error) {
|
|
17501
|
-
if (error instanceof SandboxPortError3) return error;
|
|
17502
|
-
return new SandboxPortError3(SANDBOX_ERROR_CODES3.RUNNER_FAILED, "\u6C99\u7BB1 runner \u521D\u59CB\u5316\u6216\u5305\u88C5\u5931\u8D25\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
|
|
17503
|
-
}
|
|
17504
|
-
async function ensureInitialized(policy) {
|
|
17505
|
-
if (shutdown) throw new SandboxPortError3(SANDBOX_ERROR_CODES3.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u521D\u59CB\u5316");
|
|
17506
|
-
const mod = await ensureModule();
|
|
17507
|
-
if (!mod.SandboxManager.isSupportedPlatform()) {
|
|
17508
|
-
throw new SandboxPortError3(SANDBOX_ERROR_CODES3.UNAVAILABLE, `\u5F53\u524D\u5E73\u53F0 ${process.platform} \u4E0D\u88AB\u6C99\u7BB1 backend \u652F\u6301`);
|
|
17509
|
-
}
|
|
17510
|
-
const dependencies = process.platform === "win32" ? { errors: [] } : mod.SandboxManager.checkDependencies();
|
|
17511
|
-
if (dependencies.errors.length > 0) {
|
|
17512
|
-
throw new SandboxPortError3(SANDBOX_ERROR_CODES3.UNAVAILABLE, "\u6C99\u7BB1\u5E73\u53F0\u4F9D\u8D56\u7F3A\u5931\uFF0C\u65E0\u6CD5\u63D0\u4F9B\u5DF2\u9694\u79BB\u6267\u884C");
|
|
17513
|
-
}
|
|
17514
|
-
const config = buildSrtRuntimeConfig(policy);
|
|
17515
|
-
if (process.platform === "win32") {
|
|
17516
|
-
if (policy.mode === "danger-full-access") throw new SandboxPortError3(SANDBOX_ERROR_CODES3.UNAVAILABLE, "Windows \u6682\u4E0D\u652F\u6301\u5168\u76D8\u5199\u6388\u6743\uFF0C\u547D\u4EE4\u672A\u542F\u52A8");
|
|
17517
|
-
const currentOwner = windowsManagerOwners.get(mod.SandboxManager);
|
|
17518
|
-
if (currentOwner !== void 0 && currentOwner !== owner) throw new SandboxPortError3(SANDBOX_ERROR_CODES3.SCOPE_CONFLICT, "Windows \u6C99\u7BB1\u5DF2\u88AB\u53E6\u4E00 Port \u7ED1\u5B9A\uFF0C\u62D2\u7EDD\u5E76\u884C\u6539\u5199\u4F1A\u8BDD");
|
|
17519
|
-
windowsManagerOwners.set(mod.SandboxManager, owner);
|
|
17520
|
-
windowsRunner ??= resolveWindowsSandboxRunner(mod.VENDORED_SRT_WIN_EXE, options.windowsSrtWinExe);
|
|
17521
|
-
config.windows = { srtWin: { path: windowsRunner } };
|
|
17522
|
-
if (policy.mode === "read-only") config.filesystem.allowRead = [options.workspaceRoot];
|
|
17523
|
-
}
|
|
17524
|
-
const configKey = JSON.stringify(config);
|
|
17525
|
-
if (initPromise && configKey === initConfigKey) {
|
|
17526
|
-
await initPromise;
|
|
17527
|
-
return mod;
|
|
17528
|
-
}
|
|
17529
|
-
if (initPromise) {
|
|
17530
|
-
try {
|
|
17531
|
-
await initPromise;
|
|
17532
|
-
if (process.platform === "win32") {
|
|
17533
|
-
if (activeExecutions.size > 0) throw new SandboxPortError3(SANDBOX_ERROR_CODES3.SCOPE_CONFLICT, "\u5B58\u5728\u6D3B\u52A8\u6C99\u7BB1\u8FDB\u7A0B\uFF0C\u62D2\u7EDD\u5207\u6362 Windows \u4F1A\u8BDD\u7B56\u7565");
|
|
17534
|
-
await mod.SandboxManager.reset();
|
|
17535
|
-
initPromise = void 0;
|
|
17536
|
-
initConfigKey = void 0;
|
|
17537
|
-
} else {
|
|
17538
|
-
mod.SandboxManager.updateConfig(config);
|
|
17539
|
-
initConfigKey = configKey;
|
|
17540
|
-
return mod;
|
|
17541
|
-
}
|
|
17542
|
-
} catch (error) {
|
|
17543
|
-
throw toPortError(error);
|
|
17544
|
-
}
|
|
17545
|
-
}
|
|
17546
|
-
initConfigKey = configKey;
|
|
17547
|
-
initPromise = (async () => {
|
|
17548
|
-
await mod.SandboxManager.initialize(config);
|
|
17549
|
-
if (!await mod.SandboxManager.waitForNetworkInitialization()) {
|
|
17550
|
-
throw new SandboxPortError3(SANDBOX_ERROR_CODES3.RUNNER_FAILED, "\u6C99\u7BB1\u7F51\u7EDC\u9650\u5236\u672A\u5C31\u7EEA\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
|
|
17551
|
-
}
|
|
17552
|
-
})();
|
|
17553
|
-
try {
|
|
17554
|
-
await initPromise;
|
|
17555
|
-
} catch (error) {
|
|
17556
|
-
initPromise = void 0;
|
|
17557
|
-
initConfigKey = void 0;
|
|
17558
|
-
await mod.SandboxManager.reset().catch(function ignoreResetFailure() {
|
|
17559
|
-
cleanupDiagnostic = "\u6C99\u7BB1\u521D\u59CB\u5316\u5931\u8D25\u540E\u7684 reset \u5931\u8D25";
|
|
17560
|
-
});
|
|
17561
|
-
windowsManagerOwners.delete(mod.SandboxManager);
|
|
17562
|
-
throw toPortError(error);
|
|
17563
|
-
}
|
|
17564
|
-
return mod;
|
|
17565
|
-
}
|
|
17566
|
-
const defaultPolicy = {
|
|
17567
|
-
mode: "workspace-write",
|
|
17568
|
-
workspaceRoot: options.workspaceRoot,
|
|
17569
|
-
...options.tempRoot !== void 0 ? { tempRoot: options.tempRoot } : {},
|
|
17570
|
-
allowedDomains: Object.freeze([]),
|
|
17571
|
-
deniedRead: Object.freeze([]),
|
|
17572
|
-
deniedWrite: Object.freeze([])
|
|
17573
|
-
};
|
|
17574
|
-
function unavailableReport(diagnostics) {
|
|
17575
|
-
return { platform: describePlatform(), backend: "srt", enforcement: "unavailable", installed: false, diagnostics: [...diagnostics] };
|
|
17576
|
-
}
|
|
17577
|
-
return {
|
|
17578
|
-
async status() {
|
|
17579
|
-
if (shutdown) return unavailableReport(["\u6C99\u7BB1\u5DF2 shutdown"]);
|
|
17580
|
-
if (process.platform === "win32") {
|
|
17581
|
-
try {
|
|
17582
|
-
const mod = await ensureModule();
|
|
17583
|
-
windowsRunner ??= resolveWindowsSandboxRunner(mod.VENDORED_SRT_WIN_EXE, options.windowsSrtWinExe);
|
|
17584
|
-
const report = await readWindowsSandboxCapability({ loadModule: options.loadModule, srtWinExe: windowsRunner });
|
|
17585
|
-
if (!report.provisioned) return report;
|
|
17586
|
-
if (initPromise) await initPromise;
|
|
17587
|
-
else await ensureInitialized(defaultPolicy);
|
|
17588
|
-
return { ...report, enforcement: "full", diagnostics: [...report.diagnostics ?? [], "network_fence_verified=true", ...cleanupDiagnostic ? [cleanupDiagnostic] : []] };
|
|
17589
|
-
} catch {
|
|
17590
|
-
return unavailableReport(["Windows \u6C99\u7BB1\u72B6\u6001\u63A2\u6D4B\u5931\u8D25"]);
|
|
17591
|
-
}
|
|
17592
|
-
}
|
|
17593
|
-
if (process.platform !== "darwin") return unavailableReport([`\u5E73\u53F0 ${process.platform} \u4E0D\u5728\u9996\u53D1\u652F\u6301\u5217\u8868`]);
|
|
17594
|
-
try {
|
|
17595
|
-
const mod = await ensureInitialized(defaultPolicy);
|
|
17596
|
-
const version = readSrtVersion();
|
|
17597
|
-
return {
|
|
17598
|
-
platform: "macos",
|
|
17599
|
-
backend: "srt-seatbelt",
|
|
17600
|
-
enforcement: "full",
|
|
17601
|
-
installed: true,
|
|
17602
|
-
provisioned: true,
|
|
17603
|
-
...version !== void 0 ? { version } : {},
|
|
17604
|
-
...cleanupDiagnostic !== void 0 ? { diagnostics: [cleanupDiagnostic] } : {}
|
|
17605
|
-
};
|
|
17606
|
-
} catch (error) {
|
|
17607
|
-
return unavailableReport([error instanceof SandboxPortError3 ? error.message : "\u6C99\u7BB1\u521D\u59CB\u5316\u5931\u8D25"]);
|
|
17608
|
-
}
|
|
17609
|
-
},
|
|
17610
|
-
async setup() {
|
|
17611
|
-
if (shutdown) throw new SandboxPortError3(SANDBOX_ERROR_CODES3.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u6267\u884C setup");
|
|
17612
|
-
if (process.platform === "darwin") return this.status();
|
|
17613
|
-
if (process.platform === "win32") {
|
|
17614
|
-
const mod = await ensureModule();
|
|
17615
|
-
windowsRunner ??= resolveWindowsSandboxRunner(mod.VENDORED_SRT_WIN_EXE, options.windowsSrtWinExe);
|
|
17616
|
-
return runWindowsSandboxSetup({ loadModule: options.loadModule, srtWinExe: windowsRunner });
|
|
17617
|
-
}
|
|
17618
|
-
throw new SandboxPortError3(SANDBOX_ERROR_CODES3.UNAVAILABLE, `\u5E73\u53F0 ${process.platform} \u65E0\u6C99\u7BB1 setup \u6D41\u7A0B`);
|
|
17619
|
-
},
|
|
17620
|
-
async prepare(request) {
|
|
17621
|
-
if (shutdown) throw new SandboxPortError3(SANDBOX_ERROR_CODES3.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u51C6\u5907\u6267\u884C");
|
|
17622
|
-
if (request.policy.workspaceRoot !== void 0 && request.policy.workspaceRoot !== options.workspaceRoot) {
|
|
17623
|
-
throw new SandboxPortError3(SANDBOX_ERROR_CODES3.SCOPE_CONFLICT, "\u6C99\u7BB1\u5DF2\u7ED1\u5B9A\u53E6\u4E00\u5DE5\u4F5C\u533A\uFF0C\u62D2\u7EDD\u5E76\u884C\u591A\u6839\u4F7F\u7528");
|
|
17624
|
-
}
|
|
17625
|
-
if (process.platform !== "darwin" && process.platform !== "win32") {
|
|
17626
|
-
throw new SandboxPortError3(SANDBOX_ERROR_CODES3.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");
|
|
17627
|
-
}
|
|
17628
|
-
const mod = await ensureInitialized(request.policy);
|
|
17629
|
-
const command = serializePosixCommand(request.program, request.args, request.policy.tempRoot ?? options.tempRoot);
|
|
17630
|
-
let wrapped;
|
|
17631
|
-
try {
|
|
17632
|
-
if (process.platform === "win32") {
|
|
17633
|
-
const target = resolveWindowsSandboxCommand(request.program, request.args);
|
|
17634
|
-
wrapped = await mod.SandboxManager.wrapWithSandboxArgv("", target, void 0, void 0, request.cwd, { commandId: request.commandId });
|
|
17635
|
-
wrapped.argv = finalizeWindowsSandboxArgv(wrapped.argv, target, request.policy.tempRoot ?? options.tempRoot);
|
|
17636
|
-
} else {
|
|
17637
|
-
wrapped = await mod.SandboxManager.wrapWithSandboxArgv(command, "/bin/bash", void 0, void 0, request.cwd, { commandId: request.commandId });
|
|
17638
|
-
}
|
|
17639
|
-
} catch (error) {
|
|
17640
|
-
throw toPortError(error);
|
|
17641
|
-
}
|
|
17642
|
-
if (wrapped.argv.length === 0) {
|
|
17643
|
-
throw new SandboxPortError3(SANDBOX_ERROR_CODES3.RUNNER_FAILED, "\u6C99\u7BB1\u5305\u88C5\u8F93\u51FA\u4E3A\u7A7A\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
|
|
17644
|
-
}
|
|
17645
|
-
const enforcement = "full";
|
|
17646
|
-
activeExecutions.add(request.commandId);
|
|
17647
|
-
return {
|
|
17648
|
-
executionId: request.commandId,
|
|
17649
|
-
executable: wrapped.argv[0],
|
|
17650
|
-
args: wrapped.argv.slice(1),
|
|
17651
|
-
env: { ...wrapped.env },
|
|
17652
|
-
enforcement
|
|
17653
|
-
};
|
|
17654
|
-
},
|
|
17655
|
-
async release(executionId) {
|
|
17656
|
-
activeExecutions.delete(executionId);
|
|
17657
|
-
if (!module || !initPromise) return;
|
|
17658
|
-
try {
|
|
17659
|
-
module.SandboxManager.cleanupAfterCommand();
|
|
17660
|
-
cleanupDiagnostic = void 0;
|
|
17661
|
-
} catch {
|
|
17662
|
-
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";
|
|
17663
|
-
}
|
|
17664
|
-
},
|
|
17665
|
-
async shutdown() {
|
|
17666
|
-
if (shutdown) return;
|
|
17667
|
-
shutdown = true;
|
|
17668
|
-
if (module && initPromise) {
|
|
17669
|
-
try {
|
|
17670
|
-
await module.SandboxManager.reset();
|
|
17671
|
-
} catch {
|
|
17672
|
-
cleanupDiagnostic = "\u6C99\u7BB1 shutdown \u65F6 reset \u5931\u8D25\uFF0C\u53EF\u80FD\u5B58\u5728\u5E73\u53F0\u8D44\u6E90\u6B8B\u7559";
|
|
17673
|
-
}
|
|
17674
|
-
}
|
|
17675
|
-
if (module && windowsManagerOwners.get(module.SandboxManager) === owner) windowsManagerOwners.delete(module.SandboxManager);
|
|
17676
|
-
}
|
|
17677
|
-
};
|
|
17678
|
-
}
|
|
17679
|
-
function describePlatform() {
|
|
17680
|
-
if (process.platform === "darwin") return "macos";
|
|
17681
|
-
if (process.platform === "win32") return "windows";
|
|
17682
|
-
if (process.platform === "linux") return "linux";
|
|
17683
|
-
return "unknown";
|
|
17684
|
-
}
|
|
17685
|
-
|
|
17686
|
-
// src/node/workspace-adapter.ts
|
|
17687
|
-
import fs9 from "node:fs";
|
|
17688
|
-
import path8 from "node:path";
|
|
17689
|
-
|
|
17690
|
-
// src/node/state-root.ts
|
|
17691
|
-
import fs8 from "node:fs";
|
|
17692
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
17693
|
-
import os2 from "node:os";
|
|
17694
|
-
import path7 from "node:path";
|
|
17695
|
-
|
|
17696
|
-
// src/node/state-schema-manager.ts
|
|
17697
|
-
import fs6 from "node:fs";
|
|
17698
|
-
import path5 from "node:path";
|
|
17699
|
-
import { randomUUID } from "node:crypto";
|
|
17700
|
-
function assertPlainStateTree(root) {
|
|
17701
|
-
const entry = fs6.lstatSync(root);
|
|
17702
|
-
if (entry.isSymbolicLink() || !entry.isDirectory() && !entry.isFile()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17703
|
-
if (!entry.isDirectory()) return;
|
|
17704
|
-
for (const name of fs6.readdirSync(root)) {
|
|
17705
|
-
if (name.endsWith(".lock")) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17706
|
-
assertPlainStateTree(path5.join(root, name));
|
|
17707
|
-
}
|
|
17708
|
-
}
|
|
17709
|
-
function acquireSchemaLock(root) {
|
|
17710
|
-
const lock = `${root}.schema-lock`;
|
|
17711
|
-
fs6.mkdirSync(path5.dirname(root), { recursive: true });
|
|
17712
|
-
try {
|
|
17713
|
-
const descriptor = fs6.openSync(lock, "wx", 384);
|
|
17714
|
-
fs6.writeFileSync(descriptor, String(process.pid));
|
|
17715
|
-
return descriptor;
|
|
17716
|
-
} catch (error) {
|
|
17717
|
-
if (error.code !== "EEXIST") throw error;
|
|
17718
|
-
if (fs6.lstatSync(lock).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17719
|
-
const pid = Number(fs6.readFileSync(lock, "utf8"));
|
|
17720
|
-
if (!Number.isSafeInteger(pid) || pid <= 0) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17721
|
-
try {
|
|
17722
|
-
process.kill(pid, 0);
|
|
17723
|
-
} catch (ownerError) {
|
|
17724
|
-
if (ownerError.code === "ESRCH") {
|
|
17725
|
-
fs6.unlinkSync(lock);
|
|
17726
|
-
return acquireSchemaLock(root);
|
|
17727
|
-
}
|
|
17728
|
-
}
|
|
17729
|
-
throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17730
|
-
}
|
|
17731
|
-
}
|
|
17732
|
-
function hasDurableState(root) {
|
|
17733
|
-
if (!fs6.existsSync(root)) return false;
|
|
17734
|
-
return fs6.readdirSync(root).some(function isDurableEntry(entry) {
|
|
17735
|
-
return entry !== "schema.json";
|
|
17736
|
-
});
|
|
17737
|
-
}
|
|
17738
|
-
function readManifest(root) {
|
|
17739
|
-
const filePath = path5.join(root, "schema.json");
|
|
17740
|
-
if (!fs6.existsSync(filePath)) return void 0;
|
|
17741
|
-
if (fs6.lstatSync(root).isSymbolicLink() || !fs6.lstatSync(filePath).isFile() || fs6.lstatSync(filePath).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17742
|
-
const content = fs6.readFileSync(filePath, "utf8");
|
|
17743
|
-
let parsed;
|
|
17744
|
-
try {
|
|
17745
|
-
parsed = JSON.parse(content);
|
|
17746
|
-
} catch {
|
|
17747
|
-
throw new NodeStateError("STATE_SCHEMA_MANIFEST_CORRUPTED");
|
|
17748
|
-
}
|
|
17749
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new NodeStateError("STATE_SCHEMA_MANIFEST_CORRUPTED");
|
|
17750
|
-
const manifest = parsed;
|
|
17751
|
-
if (!Number.isInteger(manifest.schemaVersion) || manifest.schemaVersion < 0) {
|
|
17752
|
-
throw new NodeStateError("STATE_SCHEMA_VERSION_INVALID");
|
|
17753
|
-
}
|
|
17754
|
-
return manifest;
|
|
17755
|
-
}
|
|
17756
|
-
function writeManifest(root, schemaVersion, diagnostic) {
|
|
17757
|
-
fs6.mkdirSync(root, { recursive: true });
|
|
17758
|
-
const manifest = { schemaVersion, ...diagnostic ? { lastMigration: diagnostic } : {} };
|
|
17759
|
-
fs6.writeFileSync(path5.join(root, "schema.json"), JSON.stringify(manifest, null, 2), "utf8");
|
|
17760
|
-
}
|
|
17761
|
-
function createBackupPath(root, fromVersion, toVersion) {
|
|
17762
|
-
const backupRoot = path5.join(path5.dirname(root), `${path5.basename(root)}.schema-backups`);
|
|
17763
|
-
const timestamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
17764
|
-
return path5.join(backupRoot, `${timestamp2}-v${fromVersion}-to-v${toVersion}-${randomUUID()}`);
|
|
17765
|
-
}
|
|
17766
|
-
function backupStateRoot(root, fromVersion, toVersion) {
|
|
17767
|
-
if (!hasDurableState(root)) return void 0;
|
|
17768
|
-
assertPlainStateTree(root);
|
|
17769
|
-
const backupPath = createBackupPath(root, fromVersion, toVersion);
|
|
17770
|
-
const backupRoot = path5.dirname(backupPath);
|
|
17771
|
-
if (fs6.existsSync(backupRoot) && fs6.lstatSync(backupRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17772
|
-
fs6.mkdirSync(backupRoot, { recursive: true });
|
|
17773
|
-
fs6.cpSync(root, backupPath, { recursive: true, errorOnExist: true });
|
|
17774
|
-
return backupPath;
|
|
17775
|
-
}
|
|
17776
|
-
function createNodeStateSchemaManager(options) {
|
|
17777
|
-
const root = path5.resolve(options.stateRoot);
|
|
17778
|
-
const originalRoot = `${root}.schema-original`;
|
|
17779
|
-
const stagingRoot = `${root}.schema-staging`;
|
|
17780
|
-
function detectVersion() {
|
|
17781
|
-
try {
|
|
17782
|
-
const manifest = readManifest(root);
|
|
17783
|
-
if (manifest) return manifest.schemaVersion;
|
|
17784
|
-
return hasDurableState(root) ? 0 : options.targetVersion;
|
|
17785
|
-
} catch (error) {
|
|
17786
|
-
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
17787
|
-
}
|
|
17788
|
-
}
|
|
17789
|
-
function getDiagnostics() {
|
|
17790
|
-
try {
|
|
17791
|
-
return readManifest(root)?.lastMigration;
|
|
17792
|
-
} catch (error) {
|
|
17793
|
-
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
17794
|
-
}
|
|
17795
|
-
}
|
|
17796
|
-
function verify(expectedVersion = options.targetVersion) {
|
|
17797
|
-
try {
|
|
17798
|
-
const version = detectVersion();
|
|
17799
|
-
if (version !== expectedVersion) throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
17800
|
-
} catch (error) {
|
|
17801
|
-
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
17802
|
-
}
|
|
17803
|
-
}
|
|
17804
|
-
function backup(fromVersion, toVersion) {
|
|
17805
|
-
try {
|
|
17806
|
-
return backupStateRoot(root, fromVersion, toVersion);
|
|
17807
|
-
} catch (error) {
|
|
17808
|
-
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
17809
|
-
}
|
|
17810
|
-
}
|
|
17811
|
-
function migrate(fromVersion, toVersion = options.targetVersion) {
|
|
17812
|
-
try {
|
|
17813
|
-
if (!fs6.existsSync(originalRoot) && !fs6.existsSync(stagingRoot) && fs6.existsSync(root) && readManifest(root)?.schemaVersion === toVersion) {
|
|
17814
|
-
verify(toVersion);
|
|
17815
|
-
return getDiagnostics();
|
|
17816
|
-
}
|
|
17817
|
-
const descriptor = acquireSchemaLock(root);
|
|
17818
|
-
try {
|
|
17819
|
-
if (fs6.existsSync(originalRoot)) {
|
|
17820
|
-
if (!fs6.lstatSync(originalRoot).isDirectory()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17821
|
-
assertPlainStateTree(originalRoot);
|
|
17822
|
-
if (!fs6.existsSync(root)) fs6.renameSync(originalRoot, root);
|
|
17823
|
-
else if (readManifest(root)?.schemaVersion === toVersion) fs6.rmSync(originalRoot, { recursive: true });
|
|
17824
|
-
else throw new NodeStateError("STATE_SCHEMA_RECOVERY_REQUIRED");
|
|
17825
|
-
}
|
|
17826
|
-
if (fs6.existsSync(stagingRoot)) {
|
|
17827
|
-
assertPlainStateTree(stagingRoot);
|
|
17828
|
-
fs6.rmSync(stagingRoot, { recursive: true });
|
|
17829
|
-
}
|
|
17830
|
-
return migrateLocked(fromVersion ?? detectVersion(), toVersion);
|
|
17831
|
-
} finally {
|
|
17832
|
-
fs6.closeSync(descriptor);
|
|
17833
|
-
fs6.unlinkSync(`${root}.schema-lock`);
|
|
17834
|
-
}
|
|
17835
|
-
} catch (error) {
|
|
17836
|
-
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
17837
|
-
}
|
|
17838
|
-
}
|
|
17839
|
-
function migrateLocked(fromVersion, toVersion) {
|
|
17840
|
-
if (!fs6.existsSync(root) || !hasDurableState(root) && !readManifest(root)) {
|
|
17841
|
-
writeManifest(root, toVersion);
|
|
17842
|
-
return void 0;
|
|
17843
|
-
}
|
|
17844
|
-
if (fromVersion === toVersion) {
|
|
17845
|
-
verify(toVersion);
|
|
17846
|
-
return getDiagnostics();
|
|
17847
|
-
}
|
|
17848
|
-
if (fromVersion > toVersion || fromVersion < 0 || toVersion < 0) {
|
|
17849
|
-
throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
17850
|
-
}
|
|
17851
|
-
if (!Number.isInteger(fromVersion) || !Number.isInteger(toVersion)) {
|
|
17852
|
-
throw new NodeStateError("STATE_SCHEMA_VERSION_INVALID");
|
|
17853
|
-
}
|
|
17854
|
-
const backupPath = backup(fromVersion, toVersion);
|
|
17855
|
-
try {
|
|
17856
|
-
if (fs6.existsSync(root)) fs6.cpSync(root, stagingRoot, { recursive: true, errorOnExist: true });
|
|
17857
|
-
else fs6.mkdirSync(stagingRoot, { recursive: true });
|
|
17858
|
-
let currentVersion = fromVersion;
|
|
17859
|
-
while (currentVersion < toVersion) {
|
|
17860
|
-
const step = options.migrations.find(function findAdjacentMigration(candidate) {
|
|
17861
|
-
return candidate.fromVersion === currentVersion && candidate.toVersion === currentVersion + 1;
|
|
17862
|
-
});
|
|
17863
|
-
if (!step) throw new NodeStateError("STATE_SCHEMA_MIGRATION_MISSING");
|
|
17864
|
-
step.migrate(stagingRoot);
|
|
17865
|
-
currentVersion = step.toVersion;
|
|
17866
|
-
}
|
|
17867
|
-
const diagnostic = backupPath ? { code: "STATE_SCHEMA_MIGRATED", fromVersion, toVersion, backupPath, migratedAt: (/* @__PURE__ */ new Date()).toISOString() } : void 0;
|
|
17868
|
-
writeManifest(stagingRoot, toVersion, diagnostic);
|
|
17869
|
-
const stagedManifest = readManifest(stagingRoot);
|
|
17870
|
-
if (stagedManifest?.schemaVersion !== toVersion) throw new NodeStateError("STATE_SCHEMA_MANIFEST_CORRUPTED");
|
|
17871
|
-
if (!fs6.existsSync(root)) {
|
|
17872
|
-
fs6.renameSync(stagingRoot, root);
|
|
17873
|
-
return diagnostic;
|
|
17874
|
-
}
|
|
17875
|
-
fs6.renameSync(root, originalRoot);
|
|
17876
|
-
try {
|
|
17877
|
-
fs6.renameSync(stagingRoot, root);
|
|
17878
|
-
} catch (error) {
|
|
17879
|
-
fs6.renameSync(originalRoot, root);
|
|
17880
|
-
throw error;
|
|
17881
|
-
}
|
|
17882
|
-
try {
|
|
17883
|
-
fs6.rmSync(originalRoot, { recursive: true, force: true });
|
|
17884
|
-
} catch {
|
|
17885
|
-
}
|
|
17886
|
-
return diagnostic;
|
|
17887
|
-
} catch (error) {
|
|
17888
|
-
try {
|
|
17889
|
-
fs6.rmSync(stagingRoot, { recursive: true, force: true });
|
|
17890
|
-
} catch {
|
|
17891
|
-
}
|
|
17892
|
-
const reason = toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
17893
|
-
throw new NodeStateError("STATE_SCHEMA_MIGRATION_FAILED", { fromVersion, toVersion, backupPath, reasonCode: reason.code });
|
|
17335
|
+
// src/node/sandbox/node-host-execution-sandbox-port.ts
|
|
17336
|
+
import {
|
|
17337
|
+
SANDBOX_ERROR_CODES,
|
|
17338
|
+
SandboxPortError
|
|
17339
|
+
} from "@autopilot-agent/core";
|
|
17340
|
+
function hostExecutionCapabilityReport() {
|
|
17341
|
+
return {
|
|
17342
|
+
platform: "windows",
|
|
17343
|
+
backend: "host-execution",
|
|
17344
|
+
enforcement: "unavailable",
|
|
17345
|
+
installed: false,
|
|
17346
|
+
provisioned: false,
|
|
17347
|
+
diagnostics: [
|
|
17348
|
+
"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"
|
|
17349
|
+
]
|
|
17350
|
+
};
|
|
17351
|
+
}
|
|
17352
|
+
function createNodeHostExecutionSandboxPort() {
|
|
17353
|
+
return {
|
|
17354
|
+
// Talk-Plan1022 CR R2:静态声明宿主执行方式,供 Turn 冻结与恢复比对,不依赖 status 探测。
|
|
17355
|
+
execution: "host",
|
|
17356
|
+
async status() {
|
|
17357
|
+
return hostExecutionCapabilityReport();
|
|
17358
|
+
},
|
|
17359
|
+
async setup() {
|
|
17360
|
+
return hostExecutionCapabilityReport();
|
|
17361
|
+
},
|
|
17362
|
+
async prepare(_request) {
|
|
17363
|
+
throw new SandboxPortError(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");
|
|
17364
|
+
},
|
|
17365
|
+
async release() {
|
|
17366
|
+
},
|
|
17367
|
+
async shutdown() {
|
|
17894
17368
|
}
|
|
17369
|
+
};
|
|
17370
|
+
}
|
|
17371
|
+
|
|
17372
|
+
// src/node/sandbox/node-sandbox-port.ts
|
|
17373
|
+
import {
|
|
17374
|
+
SANDBOX_ERROR_CODES as SANDBOX_ERROR_CODES2,
|
|
17375
|
+
SandboxPortError as SandboxPortError2
|
|
17376
|
+
} from "@autopilot-agent/core";
|
|
17377
|
+
|
|
17378
|
+
// src/node/sandbox/srt-module.ts
|
|
17379
|
+
var SRT_MODULE_SPECIFIER = "@anthropic-ai/sandbox-runtime";
|
|
17380
|
+
function readSrtVersion() {
|
|
17381
|
+
try {
|
|
17382
|
+
if (typeof __require !== "function") return void 0;
|
|
17383
|
+
const pkg = __require(`${SRT_MODULE_SPECIFIER}/package.json`);
|
|
17384
|
+
return typeof pkg.version === "string" ? pkg.version : void 0;
|
|
17385
|
+
} catch {
|
|
17386
|
+
return void 0;
|
|
17895
17387
|
}
|
|
17896
|
-
return { detectVersion, migrate, backup, verify, getDiagnostics };
|
|
17897
17388
|
}
|
|
17389
|
+
var importSrtRuntime = new Function("specifier", "return import(specifier);");
|
|
17390
|
+
function loadSrtRuntimeSurface() {
|
|
17391
|
+
return importSrtRuntime(SRT_MODULE_SPECIFIER);
|
|
17392
|
+
}
|
|
17393
|
+
|
|
17394
|
+
// src/node/sandbox/node-sandbox-port.ts
|
|
17395
|
+
import path8 from "node:path";
|
|
17396
|
+
|
|
17397
|
+
// src/node/file-mutation-locks.ts
|
|
17398
|
+
import os2 from "node:os";
|
|
17399
|
+
import path5 from "node:path";
|
|
17400
|
+
import { createHash } from "node:crypto";
|
|
17898
17401
|
|
|
17899
17402
|
// src/node/file-utils.ts
|
|
17900
|
-
import
|
|
17403
|
+
import fs5 from "node:fs";
|
|
17901
17404
|
import fsp from "node:fs/promises";
|
|
17902
|
-
import { randomUUID
|
|
17903
|
-
import
|
|
17405
|
+
import { randomUUID } from "node:crypto";
|
|
17406
|
+
import path4 from "node:path";
|
|
17904
17407
|
var fileLocks = /* @__PURE__ */ new Map();
|
|
17905
17408
|
var PROCESS_LOCK_RETRY_MS = 10;
|
|
17906
17409
|
var PROCESS_LOCK_TIMEOUT_MS = 3e4;
|
|
@@ -17910,12 +17413,12 @@ function waitForProcessLock() {
|
|
|
17910
17413
|
}
|
|
17911
17414
|
function isStaleProcessLock(lockPath) {
|
|
17912
17415
|
try {
|
|
17913
|
-
const metadata = JSON.parse(
|
|
17914
|
-
const createdAt = typeof metadata.createdAt === "number" ? metadata.createdAt :
|
|
17416
|
+
const metadata = JSON.parse(fs5.readFileSync(lockPath, "utf8"));
|
|
17417
|
+
const createdAt = typeof metadata.createdAt === "number" ? metadata.createdAt : fs5.statSync(lockPath).mtimeMs;
|
|
17915
17418
|
return Date.now() - createdAt > PROCESS_LOCK_STALE_MS;
|
|
17916
17419
|
} catch {
|
|
17917
17420
|
try {
|
|
17918
|
-
return Date.now() -
|
|
17421
|
+
return Date.now() - fs5.statSync(lockPath).mtimeMs > PROCESS_LOCK_STALE_MS;
|
|
17919
17422
|
} catch {
|
|
17920
17423
|
return false;
|
|
17921
17424
|
}
|
|
@@ -17936,7 +17439,7 @@ async function isStaleProcessLockAsync(lockPath) {
|
|
|
17936
17439
|
}
|
|
17937
17440
|
function hasExitedProcessLockOwner(lockPath) {
|
|
17938
17441
|
try {
|
|
17939
|
-
const metadata = JSON.parse(
|
|
17442
|
+
const metadata = JSON.parse(fs5.readFileSync(lockPath, "utf8"));
|
|
17940
17443
|
if (!Number.isInteger(metadata.pid) || metadata.pid <= 0) return false;
|
|
17941
17444
|
try {
|
|
17942
17445
|
process.kill(metadata.pid, 0);
|
|
@@ -17965,23 +17468,23 @@ async function hasExitedProcessLockOwnerAsync(lockPath) {
|
|
|
17965
17468
|
function isProcessLockContention(code) {
|
|
17966
17469
|
return code === "EEXIST" || code === "EPERM" || code === "EACCES";
|
|
17967
17470
|
}
|
|
17968
|
-
async function acquireProcessLock(filePath) {
|
|
17471
|
+
async function acquireProcessLock(filePath, requireExitedOwner = false) {
|
|
17969
17472
|
ensureParentDirectory(filePath);
|
|
17970
17473
|
const lockPath = `${filePath}.lock`;
|
|
17971
|
-
const ownerId =
|
|
17474
|
+
const ownerId = randomUUID();
|
|
17972
17475
|
const startedAt = Date.now();
|
|
17973
17476
|
while (true) {
|
|
17974
17477
|
try {
|
|
17975
|
-
const descriptor =
|
|
17478
|
+
const descriptor = fs5.openSync(lockPath, "wx");
|
|
17976
17479
|
const metadata = { ownerId, pid: process.pid, createdAt: Date.now() };
|
|
17977
|
-
|
|
17480
|
+
fs5.writeFileSync(descriptor, JSON.stringify(metadata), "utf8");
|
|
17978
17481
|
return { lockPath, ownerId, descriptor };
|
|
17979
17482
|
} catch (error) {
|
|
17980
17483
|
const code = error.code;
|
|
17981
17484
|
if (!isProcessLockContention(code)) throw error;
|
|
17982
|
-
if (hasExitedProcessLockOwner(lockPath) || isStaleProcessLock(lockPath)) {
|
|
17485
|
+
if (hasExitedProcessLockOwner(lockPath) || !requireExitedOwner && isStaleProcessLock(lockPath)) {
|
|
17983
17486
|
try {
|
|
17984
|
-
|
|
17487
|
+
fs5.unlinkSync(lockPath);
|
|
17985
17488
|
} catch {
|
|
17986
17489
|
}
|
|
17987
17490
|
continue;
|
|
@@ -17995,17 +17498,17 @@ async function acquireProcessLock(filePath) {
|
|
|
17995
17498
|
}
|
|
17996
17499
|
function releaseProcessLock(handle) {
|
|
17997
17500
|
try {
|
|
17998
|
-
|
|
17501
|
+
fs5.closeSync(handle.descriptor);
|
|
17999
17502
|
} finally {
|
|
18000
17503
|
try {
|
|
18001
|
-
const metadata = JSON.parse(
|
|
18002
|
-
if (metadata.ownerId === handle.ownerId)
|
|
17504
|
+
const metadata = JSON.parse(fs5.readFileSync(handle.lockPath, "utf8"));
|
|
17505
|
+
if (metadata.ownerId === handle.ownerId) fs5.unlinkSync(handle.lockPath);
|
|
18003
17506
|
} catch {
|
|
18004
17507
|
}
|
|
18005
17508
|
}
|
|
18006
17509
|
}
|
|
18007
|
-
async function withFileLock(filePath, operation) {
|
|
18008
|
-
const key2 =
|
|
17510
|
+
async function withFileLock(filePath, operation, options) {
|
|
17511
|
+
const key2 = path4.resolve(filePath);
|
|
18009
17512
|
const previous = fileLocks.get(key2) ?? Promise.resolve();
|
|
18010
17513
|
let release = () => void 0;
|
|
18011
17514
|
const next = new Promise((resolve) => {
|
|
@@ -18015,7 +17518,7 @@ async function withFileLock(filePath, operation) {
|
|
|
18015
17518
|
fileLocks.set(key2, queued);
|
|
18016
17519
|
try {
|
|
18017
17520
|
await previous;
|
|
18018
|
-
const handle = await acquireProcessLock(key2);
|
|
17521
|
+
const handle = await acquireProcessLock(key2, options?.requireExitedOwner);
|
|
18019
17522
|
try {
|
|
18020
17523
|
return await operation();
|
|
18021
17524
|
} finally {
|
|
@@ -18028,9 +17531,9 @@ async function withFileLock(filePath, operation) {
|
|
|
18028
17531
|
}
|
|
18029
17532
|
var asyncFileLocks = /* @__PURE__ */ new Map();
|
|
18030
17533
|
async function acquireAsyncProcessLock(filePath) {
|
|
18031
|
-
await fsp.mkdir(
|
|
17534
|
+
await fsp.mkdir(path4.dirname(filePath), { recursive: true });
|
|
18032
17535
|
const lockPath = `${filePath}.lock`;
|
|
18033
|
-
const ownerId =
|
|
17536
|
+
const ownerId = randomUUID();
|
|
18034
17537
|
const startedAt = Date.now();
|
|
18035
17538
|
while (true) {
|
|
18036
17539
|
try {
|
|
@@ -18067,7 +17570,7 @@ async function releaseAsyncProcessLock(handle) {
|
|
|
18067
17570
|
}
|
|
18068
17571
|
}
|
|
18069
17572
|
async function withAsyncFileLock(filePath, operation) {
|
|
18070
|
-
const key2 =
|
|
17573
|
+
const key2 = path4.resolve(filePath);
|
|
18071
17574
|
const previous = asyncFileLocks.get(key2) ?? Promise.resolve();
|
|
18072
17575
|
let release = () => void 0;
|
|
18073
17576
|
const next = new Promise((resolve) => {
|
|
@@ -18089,40 +17592,40 @@ async function withAsyncFileLock(filePath, operation) {
|
|
|
18089
17592
|
}
|
|
18090
17593
|
}
|
|
18091
17594
|
function ensureParentDirectory(filePath) {
|
|
18092
|
-
|
|
17595
|
+
fs5.mkdirSync(path4.dirname(filePath), { recursive: true });
|
|
18093
17596
|
}
|
|
18094
17597
|
function atomicReplace(filePath, content) {
|
|
18095
17598
|
ensureParentDirectory(filePath);
|
|
18096
|
-
const temporaryPath = `${filePath}.${process.pid}.${
|
|
17599
|
+
const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
18097
17600
|
try {
|
|
18098
|
-
|
|
18099
|
-
|
|
17601
|
+
fs5.writeFileSync(temporaryPath, content, { encoding: "utf8", flag: "wx" });
|
|
17602
|
+
fs5.renameSync(temporaryPath, filePath);
|
|
18100
17603
|
} finally {
|
|
18101
|
-
if (
|
|
17604
|
+
if (fs5.existsSync(temporaryPath)) fs5.unlinkSync(temporaryPath);
|
|
18102
17605
|
}
|
|
18103
17606
|
}
|
|
18104
17607
|
function safeFilePath(directory, key2, extension) {
|
|
18105
17608
|
if (!key2 || key2.includes("/") || key2.includes("\\") || key2 === "." || key2 === "..") {
|
|
18106
17609
|
throw new Error("\u6301\u4E45\u5316 ID \u4E0D\u80FD\u5305\u542B\u8DEF\u5F84\u5206\u9694\u7B26");
|
|
18107
17610
|
}
|
|
18108
|
-
const canonicalDirectory =
|
|
18109
|
-
const candidate =
|
|
18110
|
-
const relative =
|
|
18111
|
-
if (relative === ".." || relative.startsWith(`..${
|
|
17611
|
+
const canonicalDirectory = path4.resolve(directory);
|
|
17612
|
+
const candidate = path4.resolve(canonicalDirectory, `${key2}${extension}`);
|
|
17613
|
+
const relative = path4.relative(canonicalDirectory, candidate);
|
|
17614
|
+
if (relative === ".." || relative.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative)) {
|
|
18112
17615
|
throw new Error("\u6301\u4E45\u5316\u8DEF\u5F84\u8D8A\u51FA\u72B6\u6001\u6839");
|
|
18113
17616
|
}
|
|
18114
17617
|
return candidate;
|
|
18115
17618
|
}
|
|
18116
17619
|
function readJsonFile(filePath) {
|
|
18117
17620
|
try {
|
|
18118
|
-
return JSON.parse(
|
|
17621
|
+
return JSON.parse(fs5.readFileSync(filePath, "utf8"));
|
|
18119
17622
|
} catch {
|
|
18120
17623
|
return null;
|
|
18121
17624
|
}
|
|
18122
17625
|
}
|
|
18123
17626
|
function readJsonLines(filePath) {
|
|
18124
|
-
if (!
|
|
18125
|
-
const sourceLines =
|
|
17627
|
+
if (!fs5.existsSync(filePath)) return { values: [], lines: [], diagnostics: [] };
|
|
17628
|
+
const sourceLines = fs5.readFileSync(filePath, "utf8").split("\n");
|
|
18126
17629
|
const values = [];
|
|
18127
17630
|
const validLines = [];
|
|
18128
17631
|
const diagnostics = [];
|
|
@@ -18130,28 +17633,256 @@ function readJsonLines(filePath) {
|
|
|
18130
17633
|
const line = sourceLines[index];
|
|
18131
17634
|
if (!line) continue;
|
|
18132
17635
|
try {
|
|
18133
|
-
values.push(JSON.parse(line));
|
|
18134
|
-
validLines.push(line);
|
|
18135
|
-
} catch {
|
|
18136
|
-
diagnostics.push({ code: "DURABLE_JSONL_CORRUPTED", line: index + 1, reason: "INVALID_JSON" });
|
|
17636
|
+
values.push(JSON.parse(line));
|
|
17637
|
+
validLines.push(line);
|
|
17638
|
+
} catch {
|
|
17639
|
+
diagnostics.push({ code: "DURABLE_JSONL_CORRUPTED", line: index + 1, reason: "INVALID_JSON" });
|
|
17640
|
+
}
|
|
17641
|
+
}
|
|
17642
|
+
if (diagnostics.length > 0) {
|
|
17643
|
+
console.warn(`[DURABLE_JSONL_CORRUPTED] file=${path4.basename(filePath)} records=${diagnostics.length} lines=${diagnostics.map((item) => item.line).join(",")}`);
|
|
17644
|
+
}
|
|
17645
|
+
return { values, lines: validLines, diagnostics };
|
|
17646
|
+
}
|
|
17647
|
+
function appendJsonLine(filePath, serialized) {
|
|
17648
|
+
ensureParentDirectory(filePath);
|
|
17649
|
+
fs5.appendFileSync(filePath, `${serialized}
|
|
17650
|
+
`, "utf8");
|
|
17651
|
+
}
|
|
17652
|
+
async function appendUniqueJsonLine(filePath, serialized) {
|
|
17653
|
+
await withFileLock(filePath, () => {
|
|
17654
|
+
const existing = readJsonLines(filePath).lines;
|
|
17655
|
+
if (existing.includes(serialized)) return;
|
|
17656
|
+
appendJsonLine(filePath, serialized);
|
|
17657
|
+
});
|
|
17658
|
+
}
|
|
17659
|
+
|
|
17660
|
+
// src/node/file-mutation-locks.ts
|
|
17661
|
+
function getNodeFileMutationLockRoot() {
|
|
17662
|
+
return path5.join(os2.userInfo().homedir, ".autopilot", "file-mutation-locks");
|
|
17663
|
+
}
|
|
17664
|
+
async function withNodeFileMutationLocks(canonicalTargets, operation) {
|
|
17665
|
+
const ids = [...new Set(canonicalTargets.map(function targetId(target) {
|
|
17666
|
+
if (!path5.isAbsolute(target)) throw new Error("\u6587\u4EF6\u76EE\u6807\u9501\u5FC5\u987B\u7ED1\u5B9A canonical \u7EDD\u5BF9\u8DEF\u5F84");
|
|
17667
|
+
const normalized = path5.normalize(target);
|
|
17668
|
+
return createHash("sha256").update(process.platform === "win32" ? normalized.toLowerCase() : normalized).digest("hex");
|
|
17669
|
+
}))].sort();
|
|
17670
|
+
async function lockNext(index) {
|
|
17671
|
+
if (index === ids.length) return operation();
|
|
17672
|
+
return withFileLock(path5.join(getNodeFileMutationLockRoot(), ids[index] + ".target"), function acquireNext() {
|
|
17673
|
+
return lockNext(index + 1);
|
|
17674
|
+
}, { requireExitedOwner: true });
|
|
17675
|
+
}
|
|
17676
|
+
return lockNext(0);
|
|
17677
|
+
}
|
|
17678
|
+
|
|
17679
|
+
// src/node/state-root.ts
|
|
17680
|
+
import fs7 from "node:fs";
|
|
17681
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
17682
|
+
import os3 from "node:os";
|
|
17683
|
+
import path7 from "node:path";
|
|
17684
|
+
|
|
17685
|
+
// src/node/state-schema-manager.ts
|
|
17686
|
+
import fs6 from "node:fs";
|
|
17687
|
+
import path6 from "node:path";
|
|
17688
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
17689
|
+
function assertPlainStateTree(root) {
|
|
17690
|
+
const entry = fs6.lstatSync(root);
|
|
17691
|
+
if (entry.isSymbolicLink() || !entry.isDirectory() && !entry.isFile()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17692
|
+
if (!entry.isDirectory()) return;
|
|
17693
|
+
for (const name of fs6.readdirSync(root)) {
|
|
17694
|
+
if (name.endsWith(".lock")) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17695
|
+
assertPlainStateTree(path6.join(root, name));
|
|
17696
|
+
}
|
|
17697
|
+
}
|
|
17698
|
+
function acquireSchemaLock(root) {
|
|
17699
|
+
const lock = `${root}.schema-lock`;
|
|
17700
|
+
fs6.mkdirSync(path6.dirname(root), { recursive: true });
|
|
17701
|
+
try {
|
|
17702
|
+
const descriptor = fs6.openSync(lock, "wx", 384);
|
|
17703
|
+
fs6.writeFileSync(descriptor, String(process.pid));
|
|
17704
|
+
return descriptor;
|
|
17705
|
+
} catch (error) {
|
|
17706
|
+
if (error.code !== "EEXIST") throw error;
|
|
17707
|
+
if (fs6.lstatSync(lock).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17708
|
+
const pid = Number(fs6.readFileSync(lock, "utf8"));
|
|
17709
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17710
|
+
try {
|
|
17711
|
+
process.kill(pid, 0);
|
|
17712
|
+
} catch (ownerError) {
|
|
17713
|
+
if (ownerError.code === "ESRCH") {
|
|
17714
|
+
fs6.unlinkSync(lock);
|
|
17715
|
+
return acquireSchemaLock(root);
|
|
17716
|
+
}
|
|
17717
|
+
}
|
|
17718
|
+
throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17719
|
+
}
|
|
17720
|
+
}
|
|
17721
|
+
function hasDurableState(root) {
|
|
17722
|
+
if (!fs6.existsSync(root)) return false;
|
|
17723
|
+
return fs6.readdirSync(root).some(function isDurableEntry(entry) {
|
|
17724
|
+
return entry !== "schema.json";
|
|
17725
|
+
});
|
|
17726
|
+
}
|
|
17727
|
+
function readManifest(root) {
|
|
17728
|
+
const filePath = path6.join(root, "schema.json");
|
|
17729
|
+
if (!fs6.existsSync(filePath)) return void 0;
|
|
17730
|
+
if (fs6.lstatSync(root).isSymbolicLink() || !fs6.lstatSync(filePath).isFile() || fs6.lstatSync(filePath).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17731
|
+
const content = fs6.readFileSync(filePath, "utf8");
|
|
17732
|
+
let parsed;
|
|
17733
|
+
try {
|
|
17734
|
+
parsed = JSON.parse(content);
|
|
17735
|
+
} catch {
|
|
17736
|
+
throw new NodeStateError("STATE_SCHEMA_MANIFEST_CORRUPTED");
|
|
17737
|
+
}
|
|
17738
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new NodeStateError("STATE_SCHEMA_MANIFEST_CORRUPTED");
|
|
17739
|
+
const manifest = parsed;
|
|
17740
|
+
if (!Number.isInteger(manifest.schemaVersion) || manifest.schemaVersion < 0) {
|
|
17741
|
+
throw new NodeStateError("STATE_SCHEMA_VERSION_INVALID");
|
|
17742
|
+
}
|
|
17743
|
+
return manifest;
|
|
17744
|
+
}
|
|
17745
|
+
function writeManifest(root, schemaVersion, diagnostic) {
|
|
17746
|
+
fs6.mkdirSync(root, { recursive: true });
|
|
17747
|
+
const manifest = { schemaVersion, ...diagnostic ? { lastMigration: diagnostic } : {} };
|
|
17748
|
+
fs6.writeFileSync(path6.join(root, "schema.json"), JSON.stringify(manifest, null, 2), "utf8");
|
|
17749
|
+
}
|
|
17750
|
+
function createBackupPath(root, fromVersion, toVersion) {
|
|
17751
|
+
const backupRoot = path6.join(path6.dirname(root), `${path6.basename(root)}.schema-backups`);
|
|
17752
|
+
const timestamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
17753
|
+
return path6.join(backupRoot, `${timestamp2}-v${fromVersion}-to-v${toVersion}-${randomUUID2()}`);
|
|
17754
|
+
}
|
|
17755
|
+
function backupStateRoot(root, fromVersion, toVersion) {
|
|
17756
|
+
if (!hasDurableState(root)) return void 0;
|
|
17757
|
+
assertPlainStateTree(root);
|
|
17758
|
+
const backupPath = createBackupPath(root, fromVersion, toVersion);
|
|
17759
|
+
const backupRoot = path6.dirname(backupPath);
|
|
17760
|
+
if (fs6.existsSync(backupRoot) && fs6.lstatSync(backupRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17761
|
+
fs6.mkdirSync(backupRoot, { recursive: true });
|
|
17762
|
+
fs6.cpSync(root, backupPath, { recursive: true, errorOnExist: true });
|
|
17763
|
+
return backupPath;
|
|
17764
|
+
}
|
|
17765
|
+
function createNodeStateSchemaManager(options) {
|
|
17766
|
+
const root = path6.resolve(options.stateRoot);
|
|
17767
|
+
const originalRoot = `${root}.schema-original`;
|
|
17768
|
+
const stagingRoot = `${root}.schema-staging`;
|
|
17769
|
+
function detectVersion() {
|
|
17770
|
+
try {
|
|
17771
|
+
const manifest = readManifest(root);
|
|
17772
|
+
if (manifest) return manifest.schemaVersion;
|
|
17773
|
+
return hasDurableState(root) ? 0 : options.targetVersion;
|
|
17774
|
+
} catch (error) {
|
|
17775
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
17776
|
+
}
|
|
17777
|
+
}
|
|
17778
|
+
function getDiagnostics() {
|
|
17779
|
+
try {
|
|
17780
|
+
return readManifest(root)?.lastMigration;
|
|
17781
|
+
} catch (error) {
|
|
17782
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
17783
|
+
}
|
|
17784
|
+
}
|
|
17785
|
+
function verify(expectedVersion = options.targetVersion) {
|
|
17786
|
+
try {
|
|
17787
|
+
const version = detectVersion();
|
|
17788
|
+
if (version !== expectedVersion) throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
17789
|
+
} catch (error) {
|
|
17790
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
17791
|
+
}
|
|
17792
|
+
}
|
|
17793
|
+
function backup(fromVersion, toVersion) {
|
|
17794
|
+
try {
|
|
17795
|
+
return backupStateRoot(root, fromVersion, toVersion);
|
|
17796
|
+
} catch (error) {
|
|
17797
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
17798
|
+
}
|
|
17799
|
+
}
|
|
17800
|
+
function migrate(fromVersion, toVersion = options.targetVersion) {
|
|
17801
|
+
try {
|
|
17802
|
+
if (!fs6.existsSync(originalRoot) && !fs6.existsSync(stagingRoot) && fs6.existsSync(root) && readManifest(root)?.schemaVersion === toVersion) {
|
|
17803
|
+
verify(toVersion);
|
|
17804
|
+
return getDiagnostics();
|
|
17805
|
+
}
|
|
17806
|
+
const descriptor = acquireSchemaLock(root);
|
|
17807
|
+
try {
|
|
17808
|
+
if (fs6.existsSync(originalRoot)) {
|
|
17809
|
+
if (!fs6.lstatSync(originalRoot).isDirectory()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17810
|
+
assertPlainStateTree(originalRoot);
|
|
17811
|
+
if (!fs6.existsSync(root)) fs6.renameSync(originalRoot, root);
|
|
17812
|
+
else if (readManifest(root)?.schemaVersion === toVersion) fs6.rmSync(originalRoot, { recursive: true });
|
|
17813
|
+
else throw new NodeStateError("STATE_SCHEMA_RECOVERY_REQUIRED");
|
|
17814
|
+
}
|
|
17815
|
+
if (fs6.existsSync(stagingRoot)) {
|
|
17816
|
+
assertPlainStateTree(stagingRoot);
|
|
17817
|
+
fs6.rmSync(stagingRoot, { recursive: true });
|
|
17818
|
+
}
|
|
17819
|
+
return migrateLocked(fromVersion ?? detectVersion(), toVersion);
|
|
17820
|
+
} finally {
|
|
17821
|
+
fs6.closeSync(descriptor);
|
|
17822
|
+
fs6.unlinkSync(`${root}.schema-lock`);
|
|
17823
|
+
}
|
|
17824
|
+
} catch (error) {
|
|
17825
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
18137
17826
|
}
|
|
18138
17827
|
}
|
|
18139
|
-
|
|
18140
|
-
|
|
17828
|
+
function migrateLocked(fromVersion, toVersion) {
|
|
17829
|
+
if (!fs6.existsSync(root) || !hasDurableState(root) && !readManifest(root)) {
|
|
17830
|
+
writeManifest(root, toVersion);
|
|
17831
|
+
return void 0;
|
|
17832
|
+
}
|
|
17833
|
+
if (fromVersion === toVersion) {
|
|
17834
|
+
verify(toVersion);
|
|
17835
|
+
return getDiagnostics();
|
|
17836
|
+
}
|
|
17837
|
+
if (fromVersion > toVersion || fromVersion < 0 || toVersion < 0) {
|
|
17838
|
+
throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
17839
|
+
}
|
|
17840
|
+
if (!Number.isInteger(fromVersion) || !Number.isInteger(toVersion)) {
|
|
17841
|
+
throw new NodeStateError("STATE_SCHEMA_VERSION_INVALID");
|
|
17842
|
+
}
|
|
17843
|
+
const backupPath = backup(fromVersion, toVersion);
|
|
17844
|
+
try {
|
|
17845
|
+
if (fs6.existsSync(root)) fs6.cpSync(root, stagingRoot, { recursive: true, errorOnExist: true });
|
|
17846
|
+
else fs6.mkdirSync(stagingRoot, { recursive: true });
|
|
17847
|
+
let currentVersion = fromVersion;
|
|
17848
|
+
while (currentVersion < toVersion) {
|
|
17849
|
+
const step = options.migrations.find(function findAdjacentMigration(candidate) {
|
|
17850
|
+
return candidate.fromVersion === currentVersion && candidate.toVersion === currentVersion + 1;
|
|
17851
|
+
});
|
|
17852
|
+
if (!step) throw new NodeStateError("STATE_SCHEMA_MIGRATION_MISSING");
|
|
17853
|
+
step.migrate(stagingRoot);
|
|
17854
|
+
currentVersion = step.toVersion;
|
|
17855
|
+
}
|
|
17856
|
+
const diagnostic = backupPath ? { code: "STATE_SCHEMA_MIGRATED", fromVersion, toVersion, backupPath, migratedAt: (/* @__PURE__ */ new Date()).toISOString() } : void 0;
|
|
17857
|
+
writeManifest(stagingRoot, toVersion, diagnostic);
|
|
17858
|
+
const stagedManifest = readManifest(stagingRoot);
|
|
17859
|
+
if (stagedManifest?.schemaVersion !== toVersion) throw new NodeStateError("STATE_SCHEMA_MANIFEST_CORRUPTED");
|
|
17860
|
+
if (!fs6.existsSync(root)) {
|
|
17861
|
+
fs6.renameSync(stagingRoot, root);
|
|
17862
|
+
return diagnostic;
|
|
17863
|
+
}
|
|
17864
|
+
fs6.renameSync(root, originalRoot);
|
|
17865
|
+
try {
|
|
17866
|
+
fs6.renameSync(stagingRoot, root);
|
|
17867
|
+
} catch (error) {
|
|
17868
|
+
fs6.renameSync(originalRoot, root);
|
|
17869
|
+
throw error;
|
|
17870
|
+
}
|
|
17871
|
+
try {
|
|
17872
|
+
fs6.rmSync(originalRoot, { recursive: true, force: true });
|
|
17873
|
+
} catch {
|
|
17874
|
+
}
|
|
17875
|
+
return diagnostic;
|
|
17876
|
+
} catch (error) {
|
|
17877
|
+
try {
|
|
17878
|
+
fs6.rmSync(stagingRoot, { recursive: true, force: true });
|
|
17879
|
+
} catch {
|
|
17880
|
+
}
|
|
17881
|
+
const reason = toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
17882
|
+
throw new NodeStateError("STATE_SCHEMA_MIGRATION_FAILED", { fromVersion, toVersion, backupPath, reasonCode: reason.code });
|
|
17883
|
+
}
|
|
18141
17884
|
}
|
|
18142
|
-
return {
|
|
18143
|
-
}
|
|
18144
|
-
function appendJsonLine(filePath, serialized) {
|
|
18145
|
-
ensureParentDirectory(filePath);
|
|
18146
|
-
fs7.appendFileSync(filePath, `${serialized}
|
|
18147
|
-
`, "utf8");
|
|
18148
|
-
}
|
|
18149
|
-
async function appendUniqueJsonLine(filePath, serialized) {
|
|
18150
|
-
await withFileLock(filePath, () => {
|
|
18151
|
-
const existing = readJsonLines(filePath).lines;
|
|
18152
|
-
if (existing.includes(serialized)) return;
|
|
18153
|
-
appendJsonLine(filePath, serialized);
|
|
18154
|
-
});
|
|
17885
|
+
return { detectVersion, migrate, backup, verify, getDiagnostics };
|
|
18155
17886
|
}
|
|
18156
17887
|
|
|
18157
17888
|
// src/node/session-record.ts
|
|
@@ -18185,22 +17916,22 @@ var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
|
18185
17916
|
fromVersion: 1,
|
|
18186
17917
|
toVersion: 2,
|
|
18187
17918
|
migrate(stagingRoot) {
|
|
18188
|
-
|
|
17919
|
+
fs7.mkdirSync(path7.join(stagingRoot, "jobs"), { recursive: true });
|
|
18189
17920
|
}
|
|
18190
17921
|
}, {
|
|
18191
17922
|
fromVersion: 2,
|
|
18192
17923
|
toVersion: 3,
|
|
18193
17924
|
migrate(stagingRoot) {
|
|
18194
|
-
|
|
18195
|
-
|
|
18196
|
-
|
|
18197
|
-
|
|
17925
|
+
fs7.mkdirSync(path7.join(stagingRoot, "mutations"), { recursive: true });
|
|
17926
|
+
fs7.mkdirSync(path7.join(stagingRoot, "mutation-blobs"), { recursive: true });
|
|
17927
|
+
fs7.mkdirSync(path7.join(stagingRoot, "mutation-locks"), { recursive: true });
|
|
17928
|
+
fs7.mkdirSync(path7.join(stagingRoot, "undo-transactions"), { recursive: true });
|
|
18198
17929
|
}
|
|
18199
17930
|
}, {
|
|
18200
17931
|
fromVersion: 3,
|
|
18201
17932
|
toVersion: 4,
|
|
18202
17933
|
migrate(stagingRoot) {
|
|
18203
|
-
|
|
17934
|
+
fs7.mkdirSync(path7.join(stagingRoot, "questions"), { recursive: true });
|
|
18204
17935
|
}
|
|
18205
17936
|
}, {
|
|
18206
17937
|
fromVersion: 4,
|
|
@@ -18208,24 +17939,24 @@ var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
|
18208
17939
|
/** 仅在迁移副本补写产品身份;缺失归属只能采用唯一已有 Project,不能猜工作区。 */
|
|
18209
17940
|
migrate(stagingRoot) {
|
|
18210
17941
|
const sessions = path7.join(stagingRoot, "sessions");
|
|
18211
|
-
if (!
|
|
17942
|
+
if (!fs7.existsSync(sessions)) return;
|
|
18212
17943
|
const projects = path7.join(stagingRoot, "projects");
|
|
18213
|
-
const candidates =
|
|
17944
|
+
const candidates = fs7.existsSync(projects) ? fs7.readdirSync(projects).filter(
|
|
18214
17945
|
/** 只检查现有 Project 记录,不创建新的工作区身份。 */
|
|
18215
17946
|
function projectFile(file) {
|
|
18216
17947
|
return file.endsWith(".json");
|
|
18217
17948
|
}
|
|
18218
17949
|
) : [];
|
|
18219
|
-
for (const file of
|
|
17950
|
+
for (const file of fs7.readdirSync(sessions)) {
|
|
18220
17951
|
if (!file.endsWith(".json")) continue;
|
|
18221
17952
|
const target = path7.join(sessions, file);
|
|
18222
|
-
const value = JSON.parse(
|
|
17953
|
+
const value = JSON.parse(fs7.readFileSync(target, "utf8"));
|
|
18223
17954
|
if (value && value.productMode === void 0 && value.projectId === void 0 && candidates.length === 1) {
|
|
18224
|
-
const project = JSON.parse(
|
|
17955
|
+
const project = JSON.parse(fs7.readFileSync(path7.join(projects, candidates[0]), "utf8"));
|
|
18225
17956
|
if (project.id === candidates[0].slice(0, -5) && typeof project.workspaceRoot === "string" && project.workspaceRoot) value.projectId = project.id;
|
|
18226
17957
|
}
|
|
18227
17958
|
const session = normalizeNodeSession(value, file.slice(0, -5));
|
|
18228
|
-
|
|
17959
|
+
fs7.writeFileSync(target, JSON.stringify(session, null, 2), "utf8");
|
|
18229
17960
|
}
|
|
18230
17961
|
}
|
|
18231
17962
|
}, {
|
|
@@ -18237,7 +17968,7 @@ var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
|
18237
17968
|
function canonicalizeNodePath(candidate, baseDirectory = process.cwd()) {
|
|
18238
17969
|
const resolved = path7.resolve(baseDirectory, candidate);
|
|
18239
17970
|
try {
|
|
18240
|
-
return
|
|
17971
|
+
return fs7.realpathSync.native(resolved);
|
|
18241
17972
|
} catch {
|
|
18242
17973
|
return resolved;
|
|
18243
17974
|
}
|
|
@@ -18249,7 +17980,7 @@ function createNodeWorkspaceId(workspaceRoot, baseDirectory) {
|
|
|
18249
17980
|
}
|
|
18250
17981
|
function resolveNodeGlobalStateRoot(options = {}) {
|
|
18251
17982
|
const baseDirectory = options.cwd ?? process.cwd();
|
|
18252
|
-
const defaultRoot = process.env.LOCALAPPDATA ? path7.join(process.env.LOCALAPPDATA, "autopilot-agent") : path7.join(
|
|
17983
|
+
const defaultRoot = process.env.LOCALAPPDATA ? path7.join(process.env.LOCALAPPDATA, "autopilot-agent") : path7.join(os3.homedir(), ".autopilot-agent");
|
|
18253
17984
|
return canonicalizeNodePath(options.globalStateRoot ?? defaultRoot, baseDirectory);
|
|
18254
17985
|
}
|
|
18255
17986
|
function resolveNodeStateRoot(options = {}) {
|
|
@@ -18283,57 +18014,302 @@ function getNodeStatePaths(stateRoot) {
|
|
|
18283
18014
|
questionsDir: path7.join(root, "questions")
|
|
18284
18015
|
};
|
|
18285
18016
|
}
|
|
18286
|
-
function assertNodeStateSchema(stateRoot) {
|
|
18287
|
-
const paths = getNodeStatePaths(stateRoot);
|
|
18288
|
-
if (!
|
|
18289
|
-
createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS }).verify();
|
|
18290
|
-
}
|
|
18291
|
-
function ensureNodeStateRoot(stateRoot) {
|
|
18292
|
-
return initializeNodeStateRoot(stateRoot);
|
|
18293
|
-
}
|
|
18294
|
-
function initializeNodeStateRoot(stateRoot) {
|
|
18295
|
-
try {
|
|
18296
|
-
if (
|
|
18297
|
-
const paths = getNodeStatePaths(stateRoot);
|
|
18298
|
-
const manager = createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS });
|
|
18299
|
-
manager.migrate();
|
|
18300
|
-
return paths;
|
|
18301
|
-
} catch (error) {
|
|
18302
|
-
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
18303
|
-
}
|
|
18304
|
-
}
|
|
18305
|
-
function getNodeStateSchemaDiagnostic(stateRoot) {
|
|
18306
|
-
const paths = getNodeStatePaths(stateRoot);
|
|
18307
|
-
return createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS }).getDiagnostics();
|
|
18308
|
-
}
|
|
18309
|
-
function getNodeStateCorruptionDiagnostics(stateRoot) {
|
|
18310
|
-
const paths = getNodeStatePaths(stateRoot);
|
|
18311
|
-
const directories = [paths.approvalsDir, paths.checkpointsDir, paths.inboxDir, paths.transcriptsDir, paths.questionsDir];
|
|
18312
|
-
const diagnostics = [];
|
|
18313
|
-
for (const directory of directories) {
|
|
18314
|
-
if (!
|
|
18315
|
-
for (const entry of
|
|
18316
|
-
const filePath = path7.join(directory, entry);
|
|
18317
|
-
const result = readJsonLines(filePath);
|
|
18318
|
-
for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file: path7.relative(paths.root, filePath) });
|
|
18319
|
-
}
|
|
18320
|
-
}
|
|
18321
|
-
return diagnostics;
|
|
18017
|
+
function assertNodeStateSchema(stateRoot) {
|
|
18018
|
+
const paths = getNodeStatePaths(stateRoot);
|
|
18019
|
+
if (!fs7.existsSync(paths.schemaFile)) return;
|
|
18020
|
+
createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS }).verify();
|
|
18021
|
+
}
|
|
18022
|
+
function ensureNodeStateRoot(stateRoot) {
|
|
18023
|
+
return initializeNodeStateRoot(stateRoot);
|
|
18024
|
+
}
|
|
18025
|
+
function initializeNodeStateRoot(stateRoot) {
|
|
18026
|
+
try {
|
|
18027
|
+
if (fs7.existsSync(stateRoot) && fs7.lstatSync(stateRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
18028
|
+
const paths = getNodeStatePaths(stateRoot);
|
|
18029
|
+
const manager = createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS });
|
|
18030
|
+
manager.migrate();
|
|
18031
|
+
return paths;
|
|
18032
|
+
} catch (error) {
|
|
18033
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
18034
|
+
}
|
|
18035
|
+
}
|
|
18036
|
+
function getNodeStateSchemaDiagnostic(stateRoot) {
|
|
18037
|
+
const paths = getNodeStatePaths(stateRoot);
|
|
18038
|
+
return createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS }).getDiagnostics();
|
|
18039
|
+
}
|
|
18040
|
+
function getNodeStateCorruptionDiagnostics(stateRoot) {
|
|
18041
|
+
const paths = getNodeStatePaths(stateRoot);
|
|
18042
|
+
const directories = [paths.approvalsDir, paths.checkpointsDir, paths.inboxDir, paths.transcriptsDir, paths.questionsDir];
|
|
18043
|
+
const diagnostics = [];
|
|
18044
|
+
for (const directory of directories) {
|
|
18045
|
+
if (!fs7.existsSync(directory)) continue;
|
|
18046
|
+
for (const entry of fs7.readdirSync(directory).filter((file) => file.endsWith(".jsonl"))) {
|
|
18047
|
+
const filePath = path7.join(directory, entry);
|
|
18048
|
+
const result = readJsonLines(filePath);
|
|
18049
|
+
for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file: path7.relative(paths.root, filePath) });
|
|
18050
|
+
}
|
|
18051
|
+
}
|
|
18052
|
+
return diagnostics;
|
|
18053
|
+
}
|
|
18054
|
+
|
|
18055
|
+
// src/node/sandbox/node-sandbox-port.ts
|
|
18056
|
+
var managerOwners = /* @__PURE__ */ new WeakMap();
|
|
18057
|
+
function posixQuote(value) {
|
|
18058
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
18059
|
+
}
|
|
18060
|
+
function serializePosixCommand(program, args, tempRoot) {
|
|
18061
|
+
const command = [posixQuote(program), ...args.map(posixQuote)].join(" ");
|
|
18062
|
+
return tempRoot !== void 0 ? `TMPDIR=${posixQuote(tempRoot)} ${command}` : command;
|
|
18063
|
+
}
|
|
18064
|
+
function buildSrtRuntimeConfig(policy) {
|
|
18065
|
+
if ("externalWriteCapability" in policy && policy.externalWriteCapability !== void 0) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.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");
|
|
18066
|
+
return {
|
|
18067
|
+
network: {
|
|
18068
|
+
allowedDomains: [...policy.allowedDomains],
|
|
18069
|
+
deniedDomains: []
|
|
18070
|
+
},
|
|
18071
|
+
filesystem: {
|
|
18072
|
+
denyRead: [...policy.deniedRead],
|
|
18073
|
+
// 所有可写模式仅授予工作区与受控 temp;模式本身不授予任何外部修改能力。
|
|
18074
|
+
allowWrite: policy.mode !== "read-only" && policy.workspaceRoot !== void 0 ? [.../* @__PURE__ */ new Set([policy.workspaceRoot, ...policy.tempRoot !== void 0 ? [policy.tempRoot] : []])] : [],
|
|
18075
|
+
denyWrite: [...policy.deniedWrite]
|
|
18076
|
+
},
|
|
18077
|
+
allowAppleEvents: false
|
|
18078
|
+
};
|
|
18079
|
+
}
|
|
18080
|
+
function formatSandboxFailureDiagnostic(phase, error) {
|
|
18081
|
+
const source = error && typeof error === "object" ? error : {};
|
|
18082
|
+
const code = typeof source.code === "string" && /^(EPERM|EACCES|ENOENT|ENOTDIR|EINVAL|EBUSY|ETIMEDOUT|not_provisioned)$/.test(source.code) ? source.code : void 0;
|
|
18083
|
+
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;
|
|
18084
|
+
return [`phase=${phase}`, ...code ? [`cause=${code}`] : [], ...win32 ? [`win32=${win32}`] : []].join(";");
|
|
18085
|
+
}
|
|
18086
|
+
function createNodeSandboxPort(options) {
|
|
18087
|
+
let module;
|
|
18088
|
+
let initPromise;
|
|
18089
|
+
let initConfigKey;
|
|
18090
|
+
let shutdown = false;
|
|
18091
|
+
let cleanupDiagnostic;
|
|
18092
|
+
const activeExecutions = /* @__PURE__ */ new Set();
|
|
18093
|
+
const owner = {};
|
|
18094
|
+
let operationTail = Promise.resolve();
|
|
18095
|
+
function serializeOperation(operation) {
|
|
18096
|
+
const result = operationTail.then(operation);
|
|
18097
|
+
operationTail = result.catch(function retainQueue() {
|
|
18098
|
+
});
|
|
18099
|
+
return result;
|
|
18100
|
+
}
|
|
18101
|
+
function protectAuthority(policy) {
|
|
18102
|
+
const settingsRoot = path8.join(options.workspaceRoot, ".autopilot");
|
|
18103
|
+
const writes = [getNodeFileMutationLockRoot(), ...["settings.json", "settings.local.json", "mcp.json"].map(function settingsPath(file) {
|
|
18104
|
+
return path8.join(settingsRoot, file);
|
|
18105
|
+
})];
|
|
18106
|
+
const state = options.stateRoot ? [options.stateRoot, canonicalizeNodePath(options.stateRoot)] : [];
|
|
18107
|
+
return { ...policy, deniedRead: [.../* @__PURE__ */ new Set([...policy.deniedRead, ...state])], deniedWrite: [.../* @__PURE__ */ new Set([...policy.deniedWrite, ...state, ...writes, ...writes.map(function canonical(candidate) {
|
|
18108
|
+
return canonicalizeNodePath(candidate);
|
|
18109
|
+
})])] };
|
|
18110
|
+
}
|
|
18111
|
+
async function ensureModule() {
|
|
18112
|
+
if (!module) {
|
|
18113
|
+
try {
|
|
18114
|
+
module = await (options.loadModule ?? loadSrtRuntimeSurface)();
|
|
18115
|
+
} catch (error) {
|
|
18116
|
+
throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, formatSandboxFailureDiagnostic("module-load", error));
|
|
18117
|
+
}
|
|
18118
|
+
}
|
|
18119
|
+
return module;
|
|
18120
|
+
}
|
|
18121
|
+
function toPortError(error, phase, fallbackCode = SANDBOX_ERROR_CODES2.UNAVAILABLE) {
|
|
18122
|
+
if (error instanceof SandboxPortError2 && error.message.startsWith("phase=")) return error;
|
|
18123
|
+
return new SandboxPortError2(error instanceof SandboxPortError2 ? error.code : fallbackCode, formatSandboxFailureDiagnostic(phase, error));
|
|
18124
|
+
}
|
|
18125
|
+
async function ensureInitialized(policy) {
|
|
18126
|
+
if (shutdown) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u521D\u59CB\u5316");
|
|
18127
|
+
if (cleanupDiagnostic) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.CLEANUP_FAILED, "\u6C99\u7BB1\u6E05\u7406\u672A\u786E\u8BA4\uFF0C\u7981\u6B62\u7EE7\u7EED\u6267\u884C");
|
|
18128
|
+
const mod = await ensureModule();
|
|
18129
|
+
if (!mod.SandboxManager.isSupportedPlatform()) {
|
|
18130
|
+
throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, `\u5F53\u524D\u5E73\u53F0 ${process.platform} \u4E0D\u88AB\u6C99\u7BB1 backend \u652F\u6301`);
|
|
18131
|
+
}
|
|
18132
|
+
const dependencies = mod.SandboxManager.checkDependencies();
|
|
18133
|
+
if (dependencies.errors.length > 0) {
|
|
18134
|
+
throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, "\u6C99\u7BB1\u5E73\u53F0\u4F9D\u8D56\u7F3A\u5931\uFF0C\u65E0\u6CD5\u63D0\u4F9B\u5DF2\u9694\u79BB\u6267\u884C");
|
|
18135
|
+
}
|
|
18136
|
+
const currentOwner = managerOwners.get(mod.SandboxManager);
|
|
18137
|
+
if (currentOwner !== void 0 && currentOwner !== owner) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.SCOPE_CONFLICT, "\u5171\u4EAB\u6C99\u7BB1\u5DF2\u88AB\u53E6\u4E00 Port \u7ED1\u5B9A\uFF0C\u62D2\u7EDD\u7B56\u7565\u6DF7\u7528");
|
|
18138
|
+
const protectedPolicy = protectAuthority(policy);
|
|
18139
|
+
const config = buildSrtRuntimeConfig(protectedPolicy);
|
|
18140
|
+
const configKey = JSON.stringify(config);
|
|
18141
|
+
if (initPromise && configKey === initConfigKey) {
|
|
18142
|
+
await initPromise;
|
|
18143
|
+
return mod;
|
|
18144
|
+
}
|
|
18145
|
+
if (initPromise) {
|
|
18146
|
+
try {
|
|
18147
|
+
await initPromise;
|
|
18148
|
+
if (activeExecutions.size > 0) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.SCOPE_CONFLICT, "\u5B58\u5728\u6D3B\u52A8\u6C99\u7BB1\u6267\u884C\uFF0C\u62D2\u7EDD\u5207\u6362\u5171\u4EAB\u7B56\u7565");
|
|
18149
|
+
mod.SandboxManager.updateConfig(config);
|
|
18150
|
+
initConfigKey = configKey;
|
|
18151
|
+
return mod;
|
|
18152
|
+
} catch (error) {
|
|
18153
|
+
throw toPortError(error, "initialize");
|
|
18154
|
+
}
|
|
18155
|
+
}
|
|
18156
|
+
managerOwners.set(mod.SandboxManager, owner);
|
|
18157
|
+
initConfigKey = configKey;
|
|
18158
|
+
initPromise = (async () => {
|
|
18159
|
+
await mod.SandboxManager.initialize(config);
|
|
18160
|
+
if (!await mod.SandboxManager.waitForNetworkInitialization()) {
|
|
18161
|
+
throw new SandboxPortError2(SANDBOX_ERROR_CODES2.RUNNER_FAILED, "\u6C99\u7BB1\u7F51\u7EDC\u9650\u5236\u672A\u5C31\u7EEA\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
|
|
18162
|
+
}
|
|
18163
|
+
})();
|
|
18164
|
+
try {
|
|
18165
|
+
await initPromise;
|
|
18166
|
+
} catch (error) {
|
|
18167
|
+
initPromise = void 0;
|
|
18168
|
+
initConfigKey = void 0;
|
|
18169
|
+
await mod.SandboxManager.reset().catch(function ignoreResetFailure() {
|
|
18170
|
+
cleanupDiagnostic = "\u6C99\u7BB1\u521D\u59CB\u5316\u5931\u8D25\u540E\u7684 reset \u5931\u8D25";
|
|
18171
|
+
});
|
|
18172
|
+
if (!cleanupDiagnostic) managerOwners.delete(mod.SandboxManager);
|
|
18173
|
+
throw toPortError(error, "initialize");
|
|
18174
|
+
}
|
|
18175
|
+
return mod;
|
|
18176
|
+
}
|
|
18177
|
+
const defaultPolicy = {
|
|
18178
|
+
mode: "workspace-write",
|
|
18179
|
+
workspaceRoot: options.workspaceRoot,
|
|
18180
|
+
...options.tempRoot !== void 0 ? { tempRoot: options.tempRoot } : {},
|
|
18181
|
+
allowedDomains: Object.freeze([]),
|
|
18182
|
+
deniedRead: Object.freeze([]),
|
|
18183
|
+
deniedWrite: Object.freeze([])
|
|
18184
|
+
};
|
|
18185
|
+
function unavailableReport(diagnostics) {
|
|
18186
|
+
return { platform: describePlatform(), backend: "srt", enforcement: "unavailable", installed: false, diagnostics: [...diagnostics] };
|
|
18187
|
+
}
|
|
18188
|
+
return {
|
|
18189
|
+
async status() {
|
|
18190
|
+
return serializeOperation(async function statusLocked() {
|
|
18191
|
+
if (shutdown) return unavailableReport(["\u6C99\u7BB1\u5DF2 shutdown"]);
|
|
18192
|
+
if (cleanupDiagnostic) return unavailableReport([cleanupDiagnostic]);
|
|
18193
|
+
if (process.platform !== "darwin") return unavailableReport([`\u5E73\u53F0 ${process.platform} \u4E0D\u5728\u652F\u6301\u5217\u8868`]);
|
|
18194
|
+
try {
|
|
18195
|
+
const mod = await ensureInitialized(defaultPolicy);
|
|
18196
|
+
const version = readSrtVersion();
|
|
18197
|
+
return {
|
|
18198
|
+
platform: "macos",
|
|
18199
|
+
backend: "srt-seatbelt",
|
|
18200
|
+
enforcement: "full",
|
|
18201
|
+
installed: true,
|
|
18202
|
+
provisioned: true,
|
|
18203
|
+
...version !== void 0 ? { version } : {},
|
|
18204
|
+
...cleanupDiagnostic !== void 0 ? { diagnostics: [cleanupDiagnostic] } : {}
|
|
18205
|
+
};
|
|
18206
|
+
} catch (error) {
|
|
18207
|
+
return unavailableReport([error instanceof SandboxPortError2 ? error.message : "\u6C99\u7BB1\u521D\u59CB\u5316\u5931\u8D25"]);
|
|
18208
|
+
}
|
|
18209
|
+
});
|
|
18210
|
+
},
|
|
18211
|
+
async setup() {
|
|
18212
|
+
if (shutdown) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u6267\u884C setup");
|
|
18213
|
+
if (activeExecutions.size > 0) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.SCOPE_CONFLICT, "\u4ECD\u6709\u6D3B\u52A8\u6267\u884C\uFF0C\u7981\u6B62\u6267\u884C\u7CFB\u7EDF setup");
|
|
18214
|
+
if (process.platform === "darwin") return this.status();
|
|
18215
|
+
throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, `\u5E73\u53F0 ${process.platform} \u65E0\u6C99\u7BB1 setup \u6D41\u7A0B`);
|
|
18216
|
+
},
|
|
18217
|
+
async prepare(request) {
|
|
18218
|
+
return serializeOperation(async function prepareLocked() {
|
|
18219
|
+
if ("externalWriteCapability" in request.policy && request.policy.externalWriteCapability !== void 0) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, "\u5916\u90E8\u7CBE\u786E\u6587\u4EF6\u80FD\u529B\u5C1A\u672A\u901A\u8FC7 OS \u95E8\u7981\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
|
|
18220
|
+
if (shutdown) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, "\u6C99\u7BB1\u5DF2 shutdown\uFF0C\u65E0\u6CD5\u51C6\u5907\u6267\u884C");
|
|
18221
|
+
if (!options.stateRoot) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.UNAVAILABLE, "\u672A\u7ED1\u5B9A\u6388\u6743\u72B6\u6001\u4FDD\u62A4\u57DF\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
|
|
18222
|
+
if (activeExecutions.has(request.commandId)) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.SCOPE_CONFLICT, "\u6267\u884C\u5DF2\u7ED1\u5B9A\uFF0C\u7981\u6B62\u590D\u7528\u6D3B\u52A8 executionId");
|
|
18223
|
+
if (request.policy.workspaceRoot !== void 0 && request.policy.workspaceRoot !== options.workspaceRoot) {
|
|
18224
|
+
throw new SandboxPortError2(SANDBOX_ERROR_CODES2.SCOPE_CONFLICT, "\u6C99\u7BB1\u5DF2\u7ED1\u5B9A\u53E6\u4E00\u5DE5\u4F5C\u533A\uFF0C\u62D2\u7EDD\u5E76\u884C\u591A\u6839\u4F7F\u7528");
|
|
18225
|
+
}
|
|
18226
|
+
if (process.platform !== "darwin") {
|
|
18227
|
+
throw new SandboxPortError2(SANDBOX_ERROR_CODES2.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");
|
|
18228
|
+
}
|
|
18229
|
+
const mod = await ensureInitialized(request.policy);
|
|
18230
|
+
activeExecutions.add(request.commandId);
|
|
18231
|
+
try {
|
|
18232
|
+
const command = serializePosixCommand(request.program, request.args, request.policy.tempRoot ?? options.tempRoot);
|
|
18233
|
+
let wrapped;
|
|
18234
|
+
try {
|
|
18235
|
+
wrapped = await mod.SandboxManager.wrapWithSandboxArgv(command, "/bin/bash", void 0, void 0, request.cwd, { commandId: request.commandId });
|
|
18236
|
+
} catch (error) {
|
|
18237
|
+
throw toPortError(error, "wrap", SANDBOX_ERROR_CODES2.RUNNER_FAILED);
|
|
18238
|
+
}
|
|
18239
|
+
if (wrapped.argv.length === 0) {
|
|
18240
|
+
throw new SandboxPortError2(SANDBOX_ERROR_CODES2.RUNNER_FAILED, "\u6C99\u7BB1\u5305\u88C5\u8F93\u51FA\u4E3A\u7A7A\uFF0C\u76EE\u6807\u547D\u4EE4\u672A\u542F\u52A8");
|
|
18241
|
+
}
|
|
18242
|
+
const enforcement = "full";
|
|
18243
|
+
return {
|
|
18244
|
+
executionId: request.commandId,
|
|
18245
|
+
executable: wrapped.argv[0],
|
|
18246
|
+
args: wrapped.argv.slice(1),
|
|
18247
|
+
env: { ...wrapped.env },
|
|
18248
|
+
enforcement
|
|
18249
|
+
};
|
|
18250
|
+
} catch (error) {
|
|
18251
|
+
activeExecutions.delete(request.commandId);
|
|
18252
|
+
try {
|
|
18253
|
+
mod.SandboxManager.cleanupAfterCommand();
|
|
18254
|
+
} catch {
|
|
18255
|
+
cleanupDiagnostic = "\u6C99\u7BB1\u5305\u88C5\u5931\u8D25\u540E\u7684\u6E05\u7406\u672A\u786E\u8BA4";
|
|
18256
|
+
}
|
|
18257
|
+
throw error;
|
|
18258
|
+
}
|
|
18259
|
+
});
|
|
18260
|
+
},
|
|
18261
|
+
async release(executionId) {
|
|
18262
|
+
return serializeOperation(async function releaseLocked() {
|
|
18263
|
+
if (!activeExecutions.has(executionId)) return;
|
|
18264
|
+
activeExecutions.delete(executionId);
|
|
18265
|
+
if (!module || !initPromise) return;
|
|
18266
|
+
try {
|
|
18267
|
+
module.SandboxManager.cleanupAfterCommand();
|
|
18268
|
+
} catch {
|
|
18269
|
+
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";
|
|
18270
|
+
}
|
|
18271
|
+
});
|
|
18272
|
+
},
|
|
18273
|
+
async shutdown() {
|
|
18274
|
+
return serializeOperation(async function shutdownLocked() {
|
|
18275
|
+
if (shutdown) return;
|
|
18276
|
+
if (activeExecutions.size > 0) throw new SandboxPortError2(SANDBOX_ERROR_CODES2.CLEANUP_FAILED, "\u4ECD\u6709\u6D3B\u52A8\u6267\u884C\uFF0C\u7981\u6B62\u63D0\u524D shutdown");
|
|
18277
|
+
shutdown = true;
|
|
18278
|
+
if (module && initPromise) {
|
|
18279
|
+
try {
|
|
18280
|
+
await module.SandboxManager.reset();
|
|
18281
|
+
cleanupDiagnostic = void 0;
|
|
18282
|
+
} catch {
|
|
18283
|
+
cleanupDiagnostic = "\u6C99\u7BB1 shutdown \u65F6 reset \u5931\u8D25\uFF0C\u53EF\u80FD\u5B58\u5728\u5E73\u53F0\u8D44\u6E90\u6B8B\u7559";
|
|
18284
|
+
}
|
|
18285
|
+
}
|
|
18286
|
+
if (module && !cleanupDiagnostic && managerOwners.get(module.SandboxManager) === owner) managerOwners.delete(module.SandboxManager);
|
|
18287
|
+
});
|
|
18288
|
+
}
|
|
18289
|
+
};
|
|
18290
|
+
}
|
|
18291
|
+
function describePlatform() {
|
|
18292
|
+
if (process.platform === "darwin") return "macos";
|
|
18293
|
+
if (process.platform === "win32") return "windows";
|
|
18294
|
+
if (process.platform === "linux") return "linux";
|
|
18295
|
+
return "unknown";
|
|
18322
18296
|
}
|
|
18323
18297
|
|
|
18324
18298
|
// src/node/workspace-adapter.ts
|
|
18299
|
+
import fs8 from "node:fs";
|
|
18300
|
+
import path9 from "node:path";
|
|
18325
18301
|
function findWorkspaceRoot(startDirectory) {
|
|
18326
18302
|
let current = canonicalizeNodePath(startDirectory);
|
|
18327
18303
|
while (true) {
|
|
18328
|
-
const manifestPath =
|
|
18329
|
-
if (
|
|
18304
|
+
const manifestPath = path9.join(current, "package.json");
|
|
18305
|
+
if (fs8.existsSync(manifestPath)) {
|
|
18330
18306
|
try {
|
|
18331
|
-
const manifest = JSON.parse(
|
|
18307
|
+
const manifest = JSON.parse(fs8.readFileSync(manifestPath, "utf8"));
|
|
18332
18308
|
if (manifest.workspaces) return canonicalizeNodePath(current);
|
|
18333
18309
|
} catch {
|
|
18334
18310
|
}
|
|
18335
18311
|
}
|
|
18336
|
-
const parent =
|
|
18312
|
+
const parent = path9.dirname(current);
|
|
18337
18313
|
if (parent === current) throw new Error("\u65E0\u6CD5\u5B9A\u4F4D Agent \u5DE5\u4F5C\u533A\uFF1B\u8BF7\u8BBE\u7F6E AGENT_WORKSPACE_ROOT");
|
|
18338
18314
|
current = parent;
|
|
18339
18315
|
}
|
|
@@ -18352,20 +18328,20 @@ function createNodeWorkspaceAdapter(options = {}) {
|
|
|
18352
18328
|
const root = canonicalizeWorkspaceRoot(workspaceRoot);
|
|
18353
18329
|
const markers = [];
|
|
18354
18330
|
for (const marker of ["AGENTS.md", ".autopilot", ".claude"]) {
|
|
18355
|
-
if (
|
|
18331
|
+
if (fs8.existsSync(path9.join(root, marker))) markers.push(marker);
|
|
18356
18332
|
}
|
|
18357
18333
|
return {
|
|
18358
18334
|
root,
|
|
18359
18335
|
hasTrustMarker: markers.length > 0,
|
|
18360
18336
|
trustMarkers: markers,
|
|
18361
|
-
displayName:
|
|
18337
|
+
displayName: path9.basename(root)
|
|
18362
18338
|
};
|
|
18363
18339
|
}
|
|
18364
18340
|
return { resolveWorkspaceRoot, canonicalizeWorkspaceRoot, getWorkspaceInfo };
|
|
18365
18341
|
}
|
|
18366
18342
|
|
|
18367
18343
|
// src/node/stores/node-approval-store.ts
|
|
18368
|
-
import
|
|
18344
|
+
import fs9 from "node:fs";
|
|
18369
18345
|
import { AgentRuntimeError as AgentRuntimeError2 } from "@autopilot-agent/core";
|
|
18370
18346
|
function createNodeApprovalStore(options) {
|
|
18371
18347
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
@@ -18373,16 +18349,141 @@ function createNodeApprovalStore(options) {
|
|
|
18373
18349
|
const grantsFile = `${paths.approvalsDir}/grants.jsonl`;
|
|
18374
18350
|
function ensureDir() {
|
|
18375
18351
|
const state = ensureNodeStateRoot(paths.root);
|
|
18376
|
-
|
|
18352
|
+
fs9.mkdirSync(state.approvalsDir, { recursive: true });
|
|
18377
18353
|
}
|
|
18378
18354
|
return {
|
|
18355
|
+
/** 待审批私有身份复用 decisions.jsonl;记录类型不与真实 decision 混淆。 */
|
|
18356
|
+
async saveExecutionApproval(request) {
|
|
18357
|
+
ensureDir();
|
|
18358
|
+
return withFileLock(decisionsFile, function freezeRequest() {
|
|
18359
|
+
const records = readJsonLines(decisionsFile).values;
|
|
18360
|
+
if (records.some(function sameRequest(record) {
|
|
18361
|
+
return record.recordType === "external_execution_request" && record.sessionId === request.sessionId && record.turnId === request.turnId && record.approvalId === request.approvalId;
|
|
18362
|
+
})) return false;
|
|
18363
|
+
appendJsonLine(decisionsFile, JSON.stringify(request));
|
|
18364
|
+
return true;
|
|
18365
|
+
});
|
|
18366
|
+
},
|
|
18367
|
+
/** 仅读取当前审批键的私有冻结请求,不经 transcript 公开目标。 */
|
|
18368
|
+
async getExecutionApproval(input) {
|
|
18369
|
+
ensureDir();
|
|
18370
|
+
return withFileLock(decisionsFile, function readRequest() {
|
|
18371
|
+
const records = readJsonLines(decisionsFile).values;
|
|
18372
|
+
return records.find(function sameRequest(record) {
|
|
18373
|
+
return record.recordType === "external_execution_request" && record.sessionId === input.sessionId && record.turnId === input.turnId && record.approvalId === input.approvalId;
|
|
18374
|
+
}) ?? null;
|
|
18375
|
+
});
|
|
18376
|
+
},
|
|
18377
|
+
/** 同一文件锁内核验真实批准、当前约束、TTL及未消费状态,跨进程只成功一次。 */
|
|
18378
|
+
async consumeExecutionApproval(input) {
|
|
18379
|
+
ensureDir();
|
|
18380
|
+
return withFileLock(decisionsFile, function consumeRequest() {
|
|
18381
|
+
const records = readJsonLines(decisionsFile).values;
|
|
18382
|
+
const matching = records.filter(function sameKey(record) {
|
|
18383
|
+
return record.sessionId === input.sessionId && record.turnId === input.turnId && record.approvalId === input.approvalId;
|
|
18384
|
+
});
|
|
18385
|
+
if (matching.some(function consumed(record) {
|
|
18386
|
+
return "recordType" in record && record.recordType === "external_execution_consumed";
|
|
18387
|
+
})) return false;
|
|
18388
|
+
const request = matching.find(function frozen(record) {
|
|
18389
|
+
return "recordType" in record && record.recordType === "external_execution_request";
|
|
18390
|
+
});
|
|
18391
|
+
const decision = matching.find(function approved(record) {
|
|
18392
|
+
return !("recordType" in record);
|
|
18393
|
+
});
|
|
18394
|
+
if (request && decision && (decision.toolName !== request.toolName || decision.expiresAt !== request.expiresAt)) return false;
|
|
18395
|
+
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;
|
|
18396
|
+
appendJsonLine(decisionsFile, JSON.stringify({ recordType: "external_execution_consumed", sessionId: input.sessionId, turnId: input.turnId, approvalId: input.approvalId }));
|
|
18397
|
+
return true;
|
|
18398
|
+
});
|
|
18399
|
+
},
|
|
18400
|
+
/** Talk-Plan1013 Stage5 R2:文件审批冻结记录复用 decisions.jsonl;recordType 与 execution 记录区分。 */
|
|
18401
|
+
async saveFileApproval(request) {
|
|
18402
|
+
ensureDir();
|
|
18403
|
+
return withFileLock(decisionsFile, function freezeFileRequest() {
|
|
18404
|
+
const records = readJsonLines(decisionsFile).values;
|
|
18405
|
+
if (records.some(function sameRequest(record) {
|
|
18406
|
+
return record.recordType === "external_file_request" && record.sessionId === request.sessionId && record.turnId === request.turnId && record.approvalId === request.approvalId;
|
|
18407
|
+
})) return false;
|
|
18408
|
+
appendJsonLine(decisionsFile, JSON.stringify(request));
|
|
18409
|
+
return true;
|
|
18410
|
+
});
|
|
18411
|
+
},
|
|
18412
|
+
/** 仅读取当前审批键的文件冻结记录,不与真实 decision 混淆。 */
|
|
18413
|
+
async getFileApproval(input) {
|
|
18414
|
+
ensureDir();
|
|
18415
|
+
return withFileLock(decisionsFile, function readFileRequest() {
|
|
18416
|
+
const records = readJsonLines(decisionsFile).values;
|
|
18417
|
+
return records.find(function sameRequest(record) {
|
|
18418
|
+
return record.recordType === "external_file_request" && record.sessionId === input.sessionId && record.turnId === input.turnId && record.approvalId === input.approvalId;
|
|
18419
|
+
}) ?? null;
|
|
18420
|
+
});
|
|
18421
|
+
},
|
|
18422
|
+
/** 同一文件锁内核验真实批准、当前约束、TTL及未消费状态,跨进程只成功一次。 */
|
|
18423
|
+
async consumeFileApproval(input) {
|
|
18424
|
+
ensureDir();
|
|
18425
|
+
return withFileLock(decisionsFile, function consumeFileRequest() {
|
|
18426
|
+
const records = readJsonLines(decisionsFile).values;
|
|
18427
|
+
const matching = records.filter(function sameKey(record) {
|
|
18428
|
+
return record.sessionId === input.sessionId && record.turnId === input.turnId && record.approvalId === input.approvalId;
|
|
18429
|
+
});
|
|
18430
|
+
if (matching.some(function consumed(record) {
|
|
18431
|
+
return "recordType" in record && record.recordType === "external_file_consumed";
|
|
18432
|
+
})) return false;
|
|
18433
|
+
const request = matching.find(function frozen(record) {
|
|
18434
|
+
return "recordType" in record && record.recordType === "external_file_request";
|
|
18435
|
+
});
|
|
18436
|
+
const decision = matching.find(function approved(record) {
|
|
18437
|
+
return !("recordType" in record);
|
|
18438
|
+
});
|
|
18439
|
+
if (request && decision && (decision.toolName !== request.toolName || decision.expiresAt !== request.expiresAt)) return false;
|
|
18440
|
+
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;
|
|
18441
|
+
appendJsonLine(decisionsFile, JSON.stringify({ recordType: "external_file_consumed", sessionId: input.sessionId, turnId: input.turnId, approvalId: input.approvalId }));
|
|
18442
|
+
return true;
|
|
18443
|
+
});
|
|
18444
|
+
},
|
|
18445
|
+
/** R1:降级审批冻结记录复用 decisions.jsonl;recordType 与 execution/file 记录区分。 */
|
|
18446
|
+
async saveDegradeApproval(request) {
|
|
18447
|
+
ensureDir();
|
|
18448
|
+
return withFileLock(decisionsFile, function freezeDegradeRequest() {
|
|
18449
|
+
const records = readJsonLines(decisionsFile).values;
|
|
18450
|
+
if (records.some(function sameRequest(record) {
|
|
18451
|
+
return record.recordType === "sandbox_degrade_request" && record.sessionId === request.sessionId && record.turnId === request.turnId && record.approvalId === request.approvalId;
|
|
18452
|
+
})) return false;
|
|
18453
|
+
appendJsonLine(decisionsFile, JSON.stringify(request));
|
|
18454
|
+
return true;
|
|
18455
|
+
});
|
|
18456
|
+
},
|
|
18457
|
+
/** R1:同一文件锁内核验真实批准、当前约束、TTL及未消费状态,跨进程只成功一次。 */
|
|
18458
|
+
async consumeDegradeApproval(input) {
|
|
18459
|
+
ensureDir();
|
|
18460
|
+
return withFileLock(decisionsFile, function consumeDegradeRequest() {
|
|
18461
|
+
const records = readJsonLines(decisionsFile).values;
|
|
18462
|
+
const matching = records.filter(function sameKey(record) {
|
|
18463
|
+
return record.sessionId === input.sessionId && record.turnId === input.turnId && record.approvalId === input.approvalId;
|
|
18464
|
+
});
|
|
18465
|
+
if (matching.some(function consumed(record) {
|
|
18466
|
+
return "recordType" in record && record.recordType === "sandbox_degrade_consumed";
|
|
18467
|
+
})) return false;
|
|
18468
|
+
const request = matching.find(function frozen(record) {
|
|
18469
|
+
return "recordType" in record && record.recordType === "sandbox_degrade_request";
|
|
18470
|
+
});
|
|
18471
|
+
const decision = matching.find(function approved(record) {
|
|
18472
|
+
return !("recordType" in record);
|
|
18473
|
+
});
|
|
18474
|
+
if (request && decision && (decision.toolName !== request.toolName || decision.expiresAt !== request.expiresAt)) return false;
|
|
18475
|
+
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;
|
|
18476
|
+
appendJsonLine(decisionsFile, JSON.stringify({ recordType: "sandbox_degrade_consumed", sessionId: input.sessionId, turnId: input.turnId, approvalId: input.approvalId }));
|
|
18477
|
+
return true;
|
|
18478
|
+
});
|
|
18479
|
+
},
|
|
18379
18480
|
async getDecision(input) {
|
|
18380
18481
|
ensureDir();
|
|
18381
18482
|
return withFileLock(decisionsFile, () => {
|
|
18382
18483
|
const decisions = readJsonLines(decisionsFile).values;
|
|
18383
18484
|
for (let index = decisions.length - 1; index >= 0; index--) {
|
|
18384
18485
|
const decision = decisions[index];
|
|
18385
|
-
if (decision.sessionId === input.sessionId && decision.turnId === input.turnId && decision.approvalId === input.approvalId) {
|
|
18486
|
+
if (!("recordType" in decision) && decision.sessionId === input.sessionId && decision.turnId === input.turnId && decision.approvalId === input.approvalId) {
|
|
18386
18487
|
return decision;
|
|
18387
18488
|
}
|
|
18388
18489
|
}
|
|
@@ -18394,7 +18495,7 @@ function createNodeApprovalStore(options) {
|
|
|
18394
18495
|
ensureDir();
|
|
18395
18496
|
return withFileLock(decisionsFile, () => {
|
|
18396
18497
|
const existing = readJsonLines(decisionsFile).values;
|
|
18397
|
-
if (existing.some((candidate) => candidate.sessionId === decision.sessionId && candidate.turnId === decision.turnId && candidate.approvalId === decision.approvalId)) return false;
|
|
18498
|
+
if (existing.some((candidate) => !("recordType" in candidate) && candidate.sessionId === decision.sessionId && candidate.turnId === decision.turnId && candidate.approvalId === decision.approvalId)) return false;
|
|
18398
18499
|
appendJsonLine(decisionsFile, JSON.stringify(decision));
|
|
18399
18500
|
return true;
|
|
18400
18501
|
});
|
|
@@ -18442,7 +18543,7 @@ function createNodeApprovalStore(options) {
|
|
|
18442
18543
|
const grants = readJsonLines(grantsFile).values;
|
|
18443
18544
|
let deleted = false;
|
|
18444
18545
|
const remaining = grants.filter((grant) => {
|
|
18445
|
-
const matches3 = grant.toolName === input.toolName && grant.constraint === input.constraint && grant.scope === "allow_workspace" && grant.workspaceRoot && canonicalizeNodePath(grant.workspaceRoot) === workspaceRoot;
|
|
18546
|
+
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);
|
|
18446
18547
|
if (matches3) deleted = true;
|
|
18447
18548
|
return !matches3;
|
|
18448
18549
|
});
|
|
@@ -18456,21 +18557,349 @@ function createNodeApprovalStore(options) {
|
|
|
18456
18557
|
const remaining = readJsonLines(decisionsFile).values.filter((decision) => decision.sessionId !== sessionId);
|
|
18457
18558
|
atomicReplace(decisionsFile, remaining.map((decision) => JSON.stringify(decision)).join("\n") + (remaining.length ? "\n" : ""));
|
|
18458
18559
|
});
|
|
18459
|
-
await withFileLock(grantsFile, () => {
|
|
18460
|
-
const remaining = readJsonLines(grantsFile).values.filter((grant) => !(grant.scope === "allow_session" && grant.sessionId === sessionId));
|
|
18461
|
-
atomicReplace(grantsFile, remaining.map((grant) => JSON.stringify(grant)).join("\n") + (remaining.length ? "\n" : ""));
|
|
18560
|
+
await withFileLock(grantsFile, () => {
|
|
18561
|
+
const remaining = readJsonLines(grantsFile).values.filter((grant) => !(grant.scope === "allow_session" && grant.sessionId === sessionId));
|
|
18562
|
+
atomicReplace(grantsFile, remaining.map((grant) => JSON.stringify(grant)).join("\n") + (remaining.length ? "\n" : ""));
|
|
18563
|
+
});
|
|
18564
|
+
},
|
|
18565
|
+
/** Talk-Plan1013 Stage 2:按 canonical workspace / sessionId 过滤列出授权。 */
|
|
18566
|
+
async listPersistentGrants(input) {
|
|
18567
|
+
ensureDir();
|
|
18568
|
+
const workspaceRoot = input.workspaceRoot !== void 0 ? canonicalizeNodePath(input.workspaceRoot) : void 0;
|
|
18569
|
+
return withFileLock(grantsFile, () => {
|
|
18570
|
+
return readJsonLines(grantsFile).values.filter((grant) => {
|
|
18571
|
+
if (workspaceRoot !== void 0 && !(grant.workspaceRoot && canonicalizeNodePath(grant.workspaceRoot) === workspaceRoot)) return false;
|
|
18572
|
+
if (input.sessionId !== void 0 && grant.sessionId !== input.sessionId) return false;
|
|
18573
|
+
return true;
|
|
18574
|
+
});
|
|
18575
|
+
});
|
|
18576
|
+
},
|
|
18577
|
+
/** Talk-Plan1013 Stage 2:锁内更新授权投影状态;先写 grant 后投影失败时由调用方回写 pending。 */
|
|
18578
|
+
async setGrantProjection(input) {
|
|
18579
|
+
ensureDir();
|
|
18580
|
+
const workspaceRoot = canonicalizeNodePath(input.workspaceRoot);
|
|
18581
|
+
return withFileLock(grantsFile, () => {
|
|
18582
|
+
const grants = readJsonLines(grantsFile).values;
|
|
18583
|
+
for (let index = grants.length - 1; index >= 0; index--) {
|
|
18584
|
+
const grant = grants[index];
|
|
18585
|
+
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);
|
|
18586
|
+
if (!matches3) continue;
|
|
18587
|
+
const updated = { ...grant, projection: input.projection };
|
|
18588
|
+
const rewritten = grants.map((candidate, candidateIndex) => candidateIndex === index ? updated : candidate);
|
|
18589
|
+
atomicReplace(grantsFile, rewritten.map((candidate) => JSON.stringify(candidate)).join("\n") + "\n");
|
|
18590
|
+
return updated;
|
|
18591
|
+
}
|
|
18592
|
+
return null;
|
|
18593
|
+
});
|
|
18594
|
+
}
|
|
18595
|
+
};
|
|
18596
|
+
}
|
|
18597
|
+
|
|
18598
|
+
// src/node/settings/node-external-permission-projector.ts
|
|
18599
|
+
import fs12 from "node:fs";
|
|
18600
|
+
import os6 from "node:os";
|
|
18601
|
+
import { resolveAutopilotSettings as resolveAutopilotSettings2 } from "@autopilot-agent/core";
|
|
18602
|
+
import { isValidExternalPermissionRule } from "@autopilot-agent/core";
|
|
18603
|
+
|
|
18604
|
+
// src/node/settings/user-config-directory.ts
|
|
18605
|
+
import fs10 from "node:fs";
|
|
18606
|
+
import os4 from "node:os";
|
|
18607
|
+
import path10 from "node:path";
|
|
18608
|
+
var UserConfigDirectoryError = class extends Error {
|
|
18609
|
+
constructor(code) {
|
|
18610
|
+
super(code);
|
|
18611
|
+
this.code = code;
|
|
18612
|
+
this.name = "UserConfigDirectoryError";
|
|
18613
|
+
}
|
|
18614
|
+
};
|
|
18615
|
+
function resolveUserHome(homeDirectory) {
|
|
18616
|
+
let candidate = homeDirectory;
|
|
18617
|
+
if (candidate === void 0) {
|
|
18618
|
+
try {
|
|
18619
|
+
candidate = os4.homedir();
|
|
18620
|
+
} catch {
|
|
18621
|
+
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18622
|
+
}
|
|
18623
|
+
}
|
|
18624
|
+
if (!candidate || !path10.isAbsolute(candidate)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18625
|
+
return path10.resolve(candidate);
|
|
18626
|
+
}
|
|
18627
|
+
function readEntry(entryPath) {
|
|
18628
|
+
try {
|
|
18629
|
+
return fs10.lstatSync(entryPath);
|
|
18630
|
+
} catch (error) {
|
|
18631
|
+
if (error.code === "ENOENT") return void 0;
|
|
18632
|
+
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18633
|
+
}
|
|
18634
|
+
}
|
|
18635
|
+
function isWithinHome(homeDirectory, configDirectory) {
|
|
18636
|
+
const relative = path10.relative(homeDirectory, configDirectory);
|
|
18637
|
+
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path10.sep}`) && !path10.isAbsolute(relative);
|
|
18638
|
+
}
|
|
18639
|
+
function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
18640
|
+
const entry = readEntry(configDirectory);
|
|
18641
|
+
if (!entry) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18642
|
+
if (entry.isSymbolicLink()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
18643
|
+
if (!entry.isDirectory()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_NOT_DIRECTORY");
|
|
18644
|
+
try {
|
|
18645
|
+
const canonicalHome = fs10.realpathSync.native(homeDirectory);
|
|
18646
|
+
const canonicalConfigDirectory = fs10.realpathSync.native(configDirectory);
|
|
18647
|
+
if (!isWithinHome(canonicalHome, canonicalConfigDirectory)) {
|
|
18648
|
+
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
18649
|
+
}
|
|
18650
|
+
} catch (error) {
|
|
18651
|
+
if (error instanceof UserConfigDirectoryError) throw error;
|
|
18652
|
+
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18653
|
+
}
|
|
18654
|
+
}
|
|
18655
|
+
function ensureUserConfigDirectory(options = {}) {
|
|
18656
|
+
const homeDirectory = resolveUserHome(options.homeDirectory);
|
|
18657
|
+
const configDirectory = path10.join(homeDirectory, ".autopilot");
|
|
18658
|
+
const existing = readEntry(configDirectory);
|
|
18659
|
+
if (existing) assertSafeConfigDirectory(homeDirectory, configDirectory);
|
|
18660
|
+
else {
|
|
18661
|
+
try {
|
|
18662
|
+
fs10.mkdirSync(configDirectory, { recursive: true, mode: 448 });
|
|
18663
|
+
} catch {
|
|
18664
|
+
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18665
|
+
}
|
|
18666
|
+
assertSafeConfigDirectory(homeDirectory, configDirectory);
|
|
18667
|
+
}
|
|
18668
|
+
return configDirectory;
|
|
18669
|
+
}
|
|
18670
|
+
|
|
18671
|
+
// src/node/settings/node-settings-loader.ts
|
|
18672
|
+
import fs11 from "node:fs";
|
|
18673
|
+
import os5 from "node:os";
|
|
18674
|
+
import path11 from "node:path";
|
|
18675
|
+
import {
|
|
18676
|
+
resolveAutopilotSettings
|
|
18677
|
+
} from "@autopilot-agent/core";
|
|
18678
|
+
function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = path11) {
|
|
18679
|
+
try {
|
|
18680
|
+
const home = homeDirectory ?? os5.homedir();
|
|
18681
|
+
if (!pathApi.isAbsolute(home)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18682
|
+
return pathApi.join(home, ".autopilot", "settings.json");
|
|
18683
|
+
} catch {
|
|
18684
|
+
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18685
|
+
}
|
|
18686
|
+
}
|
|
18687
|
+
function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = os5.homedir(), pathApi = path11) {
|
|
18688
|
+
const root = pathApi.resolve(workspaceRoot);
|
|
18689
|
+
return {
|
|
18690
|
+
user: pathApi.join(homeDirectory, ".autopilot", "settings.json"),
|
|
18691
|
+
project: pathApi.join(root, ".autopilot", "settings.json"),
|
|
18692
|
+
local: pathApi.join(root, ".autopilot", "settings.local.json")
|
|
18693
|
+
};
|
|
18694
|
+
}
|
|
18695
|
+
function isSafeSettingsFile(filePath) {
|
|
18696
|
+
try {
|
|
18697
|
+
const file = fs11.lstatSync(filePath);
|
|
18698
|
+
const configDirectory = path11.dirname(filePath);
|
|
18699
|
+
const directory = fs11.lstatSync(configDirectory);
|
|
18700
|
+
if (!file.isFile() || file.isSymbolicLink() || !directory.isDirectory() || directory.isSymbolicLink()) return false;
|
|
18701
|
+
const canonicalDirectory = fs11.realpathSync.native(configDirectory);
|
|
18702
|
+
const canonicalFile = fs11.realpathSync.native(filePath);
|
|
18703
|
+
const relative = path11.relative(canonicalDirectory, canonicalFile);
|
|
18704
|
+
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path11.sep}`) && !path11.isAbsolute(relative);
|
|
18705
|
+
} catch (error) {
|
|
18706
|
+
return error.code === "ENOENT";
|
|
18707
|
+
}
|
|
18708
|
+
}
|
|
18709
|
+
function createNodeSettingsLoader(options = {}) {
|
|
18710
|
+
const debounceMs = options.debounceMs ?? 100;
|
|
18711
|
+
function readSource(scope, filePath) {
|
|
18712
|
+
if (!fs11.existsSync(filePath)) {
|
|
18713
|
+
try {
|
|
18714
|
+
if (fs11.lstatSync(filePath).isSymbolicLink()) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
18715
|
+
} catch {
|
|
18716
|
+
return void 0;
|
|
18717
|
+
}
|
|
18718
|
+
return void 0;
|
|
18719
|
+
}
|
|
18720
|
+
if (!isSafeSettingsFile(filePath)) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
18721
|
+
try {
|
|
18722
|
+
return { scope, value: JSON.parse(fs11.readFileSync(filePath, "utf8")), diagnostics: [] };
|
|
18723
|
+
} catch {
|
|
18724
|
+
return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_JSON_INVALID" }] };
|
|
18725
|
+
}
|
|
18726
|
+
}
|
|
18727
|
+
function load2(workspaceRoot) {
|
|
18728
|
+
return loadPaths(resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory));
|
|
18729
|
+
}
|
|
18730
|
+
function loadUser() {
|
|
18731
|
+
return loadPaths({ user: resolveNodeUserSettingsPath(options.homeDirectory) });
|
|
18732
|
+
}
|
|
18733
|
+
function loadPaths(paths) {
|
|
18734
|
+
const sources = Object.entries(paths).map(function readEntry2([scope, filePath]) {
|
|
18735
|
+
return readSource(scope, filePath);
|
|
18736
|
+
}).filter((source) => Boolean(source));
|
|
18737
|
+
const settings = resolveAutopilotSettings(sources.map(({ scope, value }) => ({ scope, value })));
|
|
18738
|
+
const diagnostics = [...settings.diagnostics, ...sources.flatMap((source) => source.diagnostics)];
|
|
18739
|
+
return { paths, settings: { ...settings, diagnostics } };
|
|
18740
|
+
}
|
|
18741
|
+
function watch(workspaceRoot, onReload) {
|
|
18742
|
+
const paths = resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory);
|
|
18743
|
+
return watchPaths(Object.values(paths), function reloadWorkspace() {
|
|
18744
|
+
onReload(load2(workspaceRoot));
|
|
18745
|
+
});
|
|
18746
|
+
}
|
|
18747
|
+
function watchUser(onReload) {
|
|
18748
|
+
return watchPaths([resolveNodeUserSettingsPath(options.homeDirectory)], function reloadUser() {
|
|
18749
|
+
onReload(loadUser());
|
|
18750
|
+
});
|
|
18751
|
+
}
|
|
18752
|
+
function watchPaths(watched, reload) {
|
|
18753
|
+
let timer;
|
|
18754
|
+
let watchers = [];
|
|
18755
|
+
function installWatchers() {
|
|
18756
|
+
for (const watcher of watchers) watcher.close();
|
|
18757
|
+
const uniqueDirectories = [...new Set(watched.flatMap(function collectWatchDirectories(filePath) {
|
|
18758
|
+
const directory = path11.dirname(filePath);
|
|
18759
|
+
return [directory, path11.dirname(directory)];
|
|
18760
|
+
}))].filter(
|
|
18761
|
+
/** 不把用户配置目录的链接目标注册为监听面;父目录仍能观察链接被替换。 */
|
|
18762
|
+
function safeWatchDirectory(directory) {
|
|
18763
|
+
return fs11.existsSync(directory) && fs11.lstatSync(directory).isDirectory() && !fs11.lstatSync(directory).isSymbolicLink();
|
|
18764
|
+
}
|
|
18765
|
+
);
|
|
18766
|
+
watchers = uniqueDirectories.flatMap(function watchParent(directory) {
|
|
18767
|
+
try {
|
|
18768
|
+
const watcher = fs11.watch(directory, function reloadOnTargetFile(_eventType, fileName) {
|
|
18769
|
+
if (!fileName || !watched.some((target) => path11.basename(target) === fileName.toString() || path11.basename(path11.dirname(target)) === fileName.toString())) return;
|
|
18770
|
+
if (timer) clearTimeout(timer);
|
|
18771
|
+
timer = setTimeout(function reloadAfterDebounce() {
|
|
18772
|
+
reload();
|
|
18773
|
+
installWatchers();
|
|
18774
|
+
}, debounceMs);
|
|
18775
|
+
});
|
|
18776
|
+
watcher.unref();
|
|
18777
|
+
watcher.on("error", function ignoreWatcherError() {
|
|
18778
|
+
});
|
|
18779
|
+
return [watcher];
|
|
18780
|
+
} catch {
|
|
18781
|
+
return [];
|
|
18782
|
+
}
|
|
18783
|
+
});
|
|
18784
|
+
}
|
|
18785
|
+
installWatchers();
|
|
18786
|
+
return function stopWatchingSettings() {
|
|
18787
|
+
if (timer) clearTimeout(timer);
|
|
18788
|
+
for (const watcher of watchers) watcher.close();
|
|
18789
|
+
};
|
|
18790
|
+
}
|
|
18791
|
+
return { load: load2, watch, loadUser, watchUser };
|
|
18792
|
+
}
|
|
18793
|
+
|
|
18794
|
+
// src/node/settings/node-external-permission-projector.ts
|
|
18795
|
+
function readScopeValue(filePath, strict = false) {
|
|
18796
|
+
if (strict) {
|
|
18797
|
+
try {
|
|
18798
|
+
fs12.lstatSync(filePath);
|
|
18799
|
+
} catch (error) {
|
|
18800
|
+
if (error.code === "ENOENT") return {};
|
|
18801
|
+
throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
|
|
18802
|
+
}
|
|
18803
|
+
if (!isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
|
|
18804
|
+
} else if (!fs12.existsSync(filePath) || !isSafeSettingsFile(filePath)) return {};
|
|
18805
|
+
let content;
|
|
18806
|
+
try {
|
|
18807
|
+
content = fs12.readFileSync(filePath, "utf8");
|
|
18808
|
+
} catch {
|
|
18809
|
+
if (strict) throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
|
|
18810
|
+
return {};
|
|
18811
|
+
}
|
|
18812
|
+
try {
|
|
18813
|
+
const parsed = JSON.parse(content);
|
|
18814
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return { ...parsed };
|
|
18815
|
+
if (strict) throw new Error("EXTERNAL_RULE_SETTINGS_INVALID");
|
|
18816
|
+
return {};
|
|
18817
|
+
} catch {
|
|
18818
|
+
if (strict) throw new Error("EXTERNAL_RULE_SETTINGS_INVALID");
|
|
18819
|
+
return {};
|
|
18820
|
+
}
|
|
18821
|
+
}
|
|
18822
|
+
function readPermissionList(source, key2) {
|
|
18823
|
+
const permissions = source.permissions;
|
|
18824
|
+
if (!permissions || typeof permissions !== "object" || Array.isArray(permissions)) return [];
|
|
18825
|
+
const list = permissions[key2];
|
|
18826
|
+
if (!Array.isArray(list)) return [];
|
|
18827
|
+
return list.filter((entry) => typeof entry === "string");
|
|
18828
|
+
}
|
|
18829
|
+
function createNodeExternalPermissionProjector(options = {}) {
|
|
18830
|
+
function localSettingsPath(workspaceRoot) {
|
|
18831
|
+
return resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory ?? os6.homedir()).local;
|
|
18832
|
+
}
|
|
18833
|
+
return {
|
|
18834
|
+
/** 记住/撤销一条精确外部规则;只写 local 文件,失败抛错由调用方把 grant 标记 pending。 */
|
|
18835
|
+
async project({ workspaceRoot, rule, action }) {
|
|
18836
|
+
if (!isValidExternalPermissionRule(rule)) throw new Error(`EXTERNAL_RULE_INVALID:${rule}`);
|
|
18837
|
+
const filePath = localSettingsPath(workspaceRoot);
|
|
18838
|
+
if (!isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
|
|
18839
|
+
return withFileLock(filePath, async function projectUnderLock() {
|
|
18840
|
+
const source = readScopeValue(filePath, true);
|
|
18841
|
+
if (source.permissions !== void 0 && (!source.permissions || typeof source.permissions !== "object" || Array.isArray(source.permissions))) throw new Error("EXTERNAL_RULE_PERMISSIONS_UNSAFE");
|
|
18842
|
+
const current = readPermissionList(source, "allow");
|
|
18843
|
+
const next = action === "add" ? current.includes(rule) ? current : [...current, rule] : current.filter((entry) => entry !== rule);
|
|
18844
|
+
const permissions = {
|
|
18845
|
+
...source.permissions && typeof source.permissions === "object" && !Array.isArray(source.permissions) ? source.permissions : {},
|
|
18846
|
+
allow: next
|
|
18847
|
+
};
|
|
18848
|
+
const updated = { ...source, permissions };
|
|
18849
|
+
const resolved = resolveAutopilotSettings2([{ scope: "local", value: updated }]);
|
|
18850
|
+
if (resolved.permissions.restricted === true) throw new Error("EXTERNAL_RULE_PERMISSIONS_UNSAFE");
|
|
18851
|
+
if (next.length === 0 && Object.keys(permissions).length === 1) delete updated.permissions;
|
|
18852
|
+
if (fs12.existsSync(filePath) && !isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
|
|
18853
|
+
fs12.mkdirSync(resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory ?? os6.homedir()).local.replace(/[/\\]settings\.local\.json$/u, ""), { recursive: true });
|
|
18854
|
+
atomicReplace(filePath, `${JSON.stringify(updated, null, 2)}
|
|
18855
|
+
`);
|
|
18462
18856
|
});
|
|
18857
|
+
},
|
|
18858
|
+
/** allow 仅 local 投影;deny 为 User/Project/Local 并集(Core 解析器统一校验语法)。 */
|
|
18859
|
+
async read(workspaceRoot) {
|
|
18860
|
+
const paths = resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory ?? os6.homedir());
|
|
18861
|
+
const resolved = resolveAutopilotSettings2([
|
|
18862
|
+
{ scope: "user", value: readScopeValue(paths.user) },
|
|
18863
|
+
{ scope: "project", value: readScopeValue(paths.project) },
|
|
18864
|
+
{ scope: "local", value: readScopeValue(paths.local) }
|
|
18865
|
+
]);
|
|
18866
|
+
return { allow: resolved.permissions.allow, deny: resolved.permissions.deny, ask: resolved.permissions.ask, ...resolved.permissions.restricted === true ? { restricted: true } : {} };
|
|
18867
|
+
}
|
|
18868
|
+
};
|
|
18869
|
+
}
|
|
18870
|
+
|
|
18871
|
+
// src/node/host-mutation-protection.ts
|
|
18872
|
+
import path12 from "node:path";
|
|
18873
|
+
function createNodeHostMutationProtection(options) {
|
|
18874
|
+
const stateRoot = path12.resolve(options.stateRoot);
|
|
18875
|
+
const trustFile = path12.join(resolveNodeTrustRoot(options), "trust.json");
|
|
18876
|
+
const fixedTargets = [
|
|
18877
|
+
{ path: getNodeFileMutationLockRoot(), scope: "directory" },
|
|
18878
|
+
{ path: stateRoot, scope: "directory" },
|
|
18879
|
+
{ path: canonicalizeNodePath(stateRoot), scope: "directory" },
|
|
18880
|
+
{ path: trustFile, scope: "file" },
|
|
18881
|
+
...options.userSettingsPath ? [{ path: path12.resolve(options.userSettingsPath), scope: "file" }] : []
|
|
18882
|
+
];
|
|
18883
|
+
return {
|
|
18884
|
+
/** 权限配置路径复用真实User/Project/Local resolver,每次保留原路径与canonical判定。 */
|
|
18885
|
+
async getProtectedTargets(workspaceRoot) {
|
|
18886
|
+
const settings = resolveNodeSettingsPaths(options.workspaceRoot ?? workspaceRoot);
|
|
18887
|
+
return Object.freeze([...fixedTargets, ...[settings.user, settings.project, settings.local].map(function configTarget(filePath) {
|
|
18888
|
+
return { path: filePath, scope: "file" };
|
|
18889
|
+
})].map(function freezeTarget(target) {
|
|
18890
|
+
return Object.freeze({ ...target });
|
|
18891
|
+
}));
|
|
18463
18892
|
}
|
|
18464
18893
|
};
|
|
18465
18894
|
}
|
|
18466
18895
|
|
|
18467
18896
|
// src/node/stores/node-checkpoint-store.ts
|
|
18468
|
-
import
|
|
18897
|
+
import fs13 from "node:fs";
|
|
18469
18898
|
function createNodeCheckpointStore(options) {
|
|
18470
18899
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
18471
18900
|
function ensureDir() {
|
|
18472
18901
|
const state = ensureNodeStateRoot(paths.root);
|
|
18473
|
-
|
|
18902
|
+
fs13.mkdirSync(state.checkpointsDir, { recursive: true });
|
|
18474
18903
|
}
|
|
18475
18904
|
function filePath(sessionId) {
|
|
18476
18905
|
return safeFilePath(paths.checkpointsDir, sessionId, ".jsonl");
|
|
@@ -18521,7 +18950,7 @@ function createNodeCheckpointStore(options) {
|
|
|
18521
18950
|
ensureDir();
|
|
18522
18951
|
const target = filePath(sessionId);
|
|
18523
18952
|
await withFileLock(target, () => {
|
|
18524
|
-
if (
|
|
18953
|
+
if (fs13.existsSync(target)) fs13.unlinkSync(target);
|
|
18525
18954
|
});
|
|
18526
18955
|
}
|
|
18527
18956
|
};
|
|
@@ -18538,12 +18967,12 @@ function createNodeEventSink(_options) {
|
|
|
18538
18967
|
|
|
18539
18968
|
// src/node/stores/node-input-inbox.ts
|
|
18540
18969
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
18541
|
-
import
|
|
18970
|
+
import fs14 from "node:fs";
|
|
18542
18971
|
function createNodeInputInbox(options) {
|
|
18543
18972
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
18544
18973
|
function ensureDir() {
|
|
18545
18974
|
const state = ensureNodeStateRoot(paths.root);
|
|
18546
|
-
|
|
18975
|
+
fs14.mkdirSync(state.inboxDir, { recursive: true });
|
|
18547
18976
|
}
|
|
18548
18977
|
function filePath(sessionId) {
|
|
18549
18978
|
return safeFilePath(paths.inboxDir, sessionId, ".jsonl");
|
|
@@ -18630,7 +19059,7 @@ function createNodeInputInbox(options) {
|
|
|
18630
19059
|
},
|
|
18631
19060
|
async cancel(inputId) {
|
|
18632
19061
|
ensureDir();
|
|
18633
|
-
const files =
|
|
19062
|
+
const files = fs14.readdirSync(paths.inboxDir).filter((file) => file.endsWith(".jsonl"));
|
|
18634
19063
|
for (const file of files) {
|
|
18635
19064
|
const sessionId = file.slice(0, -6);
|
|
18636
19065
|
const cancelled = await withFileLock(filePath(sessionId), () => {
|
|
@@ -18649,7 +19078,7 @@ function createNodeInputInbox(options) {
|
|
|
18649
19078
|
ensureDir();
|
|
18650
19079
|
const target = filePath(sessionId);
|
|
18651
19080
|
await withFileLock(target, () => {
|
|
18652
|
-
if (
|
|
19081
|
+
if (fs14.existsSync(target)) fs14.unlinkSync(target);
|
|
18653
19082
|
});
|
|
18654
19083
|
},
|
|
18655
19084
|
async waitForInput(_query) {
|
|
@@ -18659,12 +19088,12 @@ function createNodeInputInbox(options) {
|
|
|
18659
19088
|
|
|
18660
19089
|
// src/node/stores/node-project-store.ts
|
|
18661
19090
|
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
18662
|
-
import
|
|
19091
|
+
import fs15 from "node:fs";
|
|
18663
19092
|
function createNodeProjectStore(options) {
|
|
18664
19093
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
18665
19094
|
function ensureDir() {
|
|
18666
19095
|
const state = ensureNodeStateRoot(paths.root);
|
|
18667
|
-
|
|
19096
|
+
fs15.mkdirSync(state.projectsDir, { recursive: true });
|
|
18668
19097
|
}
|
|
18669
19098
|
function filePath(projectId) {
|
|
18670
19099
|
return safeFilePath(paths.projectsDir, projectId, ".json");
|
|
@@ -18683,7 +19112,7 @@ function createNodeProjectStore(options) {
|
|
|
18683
19112
|
async list() {
|
|
18684
19113
|
ensureDir();
|
|
18685
19114
|
const projects = [];
|
|
18686
|
-
for (const file of
|
|
19115
|
+
for (const file of fs15.readdirSync(paths.projectsDir).filter((entry) => entry.endsWith(".json"))) {
|
|
18687
19116
|
const project = readJsonFile(filePath(file.slice(0, -5)));
|
|
18688
19117
|
if (project) projects.push(project);
|
|
18689
19118
|
}
|
|
@@ -18708,8 +19137,8 @@ function createNodeProjectStore(options) {
|
|
|
18708
19137
|
ensureDir();
|
|
18709
19138
|
const target = filePath(id);
|
|
18710
19139
|
return withFileLock(target, () => {
|
|
18711
|
-
if (!
|
|
18712
|
-
|
|
19140
|
+
if (!fs15.existsSync(target)) return false;
|
|
19141
|
+
fs15.unlinkSync(target);
|
|
18713
19142
|
return true;
|
|
18714
19143
|
});
|
|
18715
19144
|
}
|
|
@@ -18717,31 +19146,31 @@ function createNodeProjectStore(options) {
|
|
|
18717
19146
|
}
|
|
18718
19147
|
|
|
18719
19148
|
// src/node/stores/node-session-store.ts
|
|
18720
|
-
import
|
|
19149
|
+
import fs17 from "node:fs";
|
|
18721
19150
|
|
|
18722
19151
|
// src/node/chat-state.ts
|
|
18723
|
-
import
|
|
18724
|
-
import
|
|
18725
|
-
import
|
|
19152
|
+
import fs16 from "node:fs";
|
|
19153
|
+
import os7 from "node:os";
|
|
19154
|
+
import path13 from "node:path";
|
|
18726
19155
|
function resolveNodeChatStatePaths(options = {}) {
|
|
18727
19156
|
try {
|
|
18728
|
-
if (options.globalStateRoot !== void 0 && !
|
|
18729
|
-
const globalRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd:
|
|
18730
|
-
const root =
|
|
18731
|
-
return { root, stateRoot:
|
|
19157
|
+
if (options.globalStateRoot !== void 0 && !path13.isAbsolute(options.globalStateRoot)) throw new NodeChatError("CHAT_STATE_ROOT_INVALID");
|
|
19158
|
+
const globalRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: os7.homedir() });
|
|
19159
|
+
const root = path13.join(globalRoot, "chat");
|
|
19160
|
+
return { root, stateRoot: path13.join(root, "state"), attachmentsRoot: path13.join(root, "attachments"), knowledgeRoot: path13.join(root, "knowledge") };
|
|
18732
19161
|
} catch (error) {
|
|
18733
19162
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
18734
19163
|
}
|
|
18735
19164
|
}
|
|
18736
19165
|
function assertSafeNodePath(root, target) {
|
|
18737
19166
|
try {
|
|
18738
|
-
const relative =
|
|
18739
|
-
if (relative === ".." || relative.startsWith(`..${
|
|
19167
|
+
const relative = path13.relative(root, target);
|
|
19168
|
+
if (relative === ".." || relative.startsWith(`..${path13.sep}`) || path13.isAbsolute(relative)) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
18740
19169
|
let current = root;
|
|
18741
|
-
for (const segment of ["", ...relative.split(
|
|
18742
|
-
if (segment) current =
|
|
19170
|
+
for (const segment of ["", ...relative.split(path13.sep).filter(Boolean)]) {
|
|
19171
|
+
if (segment) current = path13.join(current, segment);
|
|
18743
19172
|
try {
|
|
18744
|
-
const entry =
|
|
19173
|
+
const entry = fs16.lstatSync(current);
|
|
18745
19174
|
if (entry.isSymbolicLink() || current !== target && !entry.isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
18746
19175
|
} catch (error) {
|
|
18747
19176
|
if (error.code !== "ENOENT") throw error;
|
|
@@ -18755,15 +19184,15 @@ function assertSafeNodePath(root, target) {
|
|
|
18755
19184
|
function ensureChatDirectory(root, target) {
|
|
18756
19185
|
try {
|
|
18757
19186
|
assertSafeNodePath(root, target);
|
|
18758
|
-
|
|
19187
|
+
fs16.mkdirSync(target, { recursive: true, mode: 448 });
|
|
18759
19188
|
assertSafeNodePath(root, target);
|
|
18760
|
-
if (!
|
|
19189
|
+
if (!fs16.lstatSync(target).isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
18761
19190
|
} catch (error) {
|
|
18762
19191
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
18763
19192
|
}
|
|
18764
19193
|
}
|
|
18765
19194
|
function initializeNodeChatDirectories(paths) {
|
|
18766
|
-
ensureChatDirectory(
|
|
19195
|
+
ensureChatDirectory(path13.dirname(paths.root), paths.root);
|
|
18767
19196
|
ensureChatDirectory(paths.root, paths.stateRoot);
|
|
18768
19197
|
ensureChatDirectory(paths.root, paths.attachmentsRoot);
|
|
18769
19198
|
}
|
|
@@ -18775,7 +19204,7 @@ function createNodeSessionStore(options) {
|
|
|
18775
19204
|
function ensureDir() {
|
|
18776
19205
|
const state = ensureNodeStateRoot(options.stateRoot);
|
|
18777
19206
|
assertSafeNodePath(state.root, state.sessionsDir);
|
|
18778
|
-
|
|
19207
|
+
fs17.mkdirSync(state.sessionsDir, { recursive: true });
|
|
18779
19208
|
}
|
|
18780
19209
|
function filePath(sessionId) {
|
|
18781
19210
|
const target = safeFilePath(paths.sessionsDir, sessionId, ".json");
|
|
@@ -18784,9 +19213,9 @@ function createNodeSessionStore(options) {
|
|
|
18784
19213
|
}
|
|
18785
19214
|
function read(id) {
|
|
18786
19215
|
const target = filePath(id);
|
|
18787
|
-
if (!
|
|
19216
|
+
if (!fs17.existsSync(target)) return null;
|
|
18788
19217
|
let value;
|
|
18789
|
-
const content =
|
|
19218
|
+
const content = fs17.readFileSync(target, "utf8");
|
|
18790
19219
|
try {
|
|
18791
19220
|
value = JSON.parse(content);
|
|
18792
19221
|
} catch {
|
|
@@ -18814,7 +19243,7 @@ function createNodeSessionStore(options) {
|
|
|
18814
19243
|
try {
|
|
18815
19244
|
ensureDir();
|
|
18816
19245
|
const sessions = [];
|
|
18817
|
-
for (const file of
|
|
19246
|
+
for (const file of fs17.readdirSync(paths.sessionsDir)) {
|
|
18818
19247
|
if (!file.endsWith(".json")) continue;
|
|
18819
19248
|
const session = await this.get(file.slice(0, -5));
|
|
18820
19249
|
if (session) sessions.push(session);
|
|
@@ -18846,7 +19275,7 @@ function createNodeSessionStore(options) {
|
|
|
18846
19275
|
const target = filePath(id);
|
|
18847
19276
|
return await withFileLock(target, function deleteLocked() {
|
|
18848
19277
|
if (!read(id)) return false;
|
|
18849
|
-
|
|
19278
|
+
fs17.unlinkSync(target);
|
|
18850
19279
|
return true;
|
|
18851
19280
|
});
|
|
18852
19281
|
} catch (error) {
|
|
@@ -18858,11 +19287,11 @@ function createNodeSessionStore(options) {
|
|
|
18858
19287
|
|
|
18859
19288
|
// src/node/stores/node-transcript-store.ts
|
|
18860
19289
|
import fsp2 from "node:fs/promises";
|
|
18861
|
-
import
|
|
19290
|
+
import path14 from "node:path";
|
|
18862
19291
|
var transcriptIndexes = /* @__PURE__ */ new Map();
|
|
18863
19292
|
var transcriptRootInitializations = /* @__PURE__ */ new Map();
|
|
18864
19293
|
function getTranscriptIndex(filePath) {
|
|
18865
|
-
const key2 =
|
|
19294
|
+
const key2 = path14.resolve(filePath);
|
|
18866
19295
|
const existing = transcriptIndexes.get(key2);
|
|
18867
19296
|
if (existing) return existing;
|
|
18868
19297
|
const created = { initialized: false, offset: 0, pendingBytes: Buffer.alloc(0), endsWithNewline: true, keys: /* @__PURE__ */ new Set() };
|
|
@@ -18873,7 +19302,7 @@ function getEnvelopeKey(envelope) {
|
|
|
18873
19302
|
return `${envelope.sessionId}\0${envelope.turnId}\0${envelope.seq}`;
|
|
18874
19303
|
}
|
|
18875
19304
|
function ensureTranscriptDirectory(stateRoot) {
|
|
18876
|
-
const key2 =
|
|
19305
|
+
const key2 = path14.resolve(stateRoot);
|
|
18877
19306
|
const existing = transcriptRootInitializations.get(key2);
|
|
18878
19307
|
if (existing) return existing;
|
|
18879
19308
|
const initialization = Promise.resolve().then(async function initializeTranscriptDirectory() {
|
|
@@ -18895,7 +19324,7 @@ async function readTranscriptBuffer(filePath) {
|
|
|
18895
19324
|
}
|
|
18896
19325
|
}
|
|
18897
19326
|
function reportCorruptedLine(filePath) {
|
|
18898
|
-
console.warn(`[DURABLE_JSONL_CORRUPTED] file=${
|
|
19327
|
+
console.warn(`[DURABLE_JSONL_CORRUPTED] file=${path14.basename(filePath)} records=1 lines=unknown`);
|
|
18899
19328
|
}
|
|
18900
19329
|
function parseTranscriptLine(filePath, line, index, parsed) {
|
|
18901
19330
|
if (line.length === 0) return;
|
|
@@ -19047,12 +19476,12 @@ function createNodeTranscriptStore(options) {
|
|
|
19047
19476
|
}
|
|
19048
19477
|
|
|
19049
19478
|
// src/node/stores/node-turn-store.ts
|
|
19050
|
-
import
|
|
19479
|
+
import fs18 from "node:fs";
|
|
19051
19480
|
function createNodeTurnStore(options) {
|
|
19052
19481
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19053
19482
|
function ensureDir() {
|
|
19054
19483
|
const state = ensureNodeStateRoot(paths.root);
|
|
19055
|
-
|
|
19484
|
+
fs18.mkdirSync(state.turnsDir, { recursive: true });
|
|
19056
19485
|
}
|
|
19057
19486
|
function filePath(turnId) {
|
|
19058
19487
|
return safeFilePath(paths.turnsDir, turnId, ".json");
|
|
@@ -19071,7 +19500,7 @@ function createNodeTurnStore(options) {
|
|
|
19071
19500
|
async list(sessionId) {
|
|
19072
19501
|
ensureDir();
|
|
19073
19502
|
const turns = [];
|
|
19074
|
-
for (const file of
|
|
19503
|
+
for (const file of fs18.readdirSync(paths.turnsDir).filter((entry) => entry.endsWith(".json"))) {
|
|
19075
19504
|
const turn = readJsonFile(filePath(file.slice(0, -5)));
|
|
19076
19505
|
if (turn?.sessionId === sessionId) turns.push(turn);
|
|
19077
19506
|
}
|
|
@@ -19088,7 +19517,7 @@ function createNodeTurnStore(options) {
|
|
|
19088
19517
|
for (const turn of turns) {
|
|
19089
19518
|
const target = filePath(turn.id);
|
|
19090
19519
|
await withFileLock(target, () => {
|
|
19091
|
-
if (
|
|
19520
|
+
if (fs18.existsSync(target)) fs18.unlinkSync(target);
|
|
19092
19521
|
});
|
|
19093
19522
|
}
|
|
19094
19523
|
}
|
|
@@ -19096,12 +19525,12 @@ function createNodeTurnStore(options) {
|
|
|
19096
19525
|
}
|
|
19097
19526
|
|
|
19098
19527
|
// src/node/stores/node-lease-store.ts
|
|
19099
|
-
import
|
|
19528
|
+
import fs19 from "node:fs";
|
|
19100
19529
|
function createNodeLeaseStore(options) {
|
|
19101
19530
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19102
19531
|
function ensureDir() {
|
|
19103
19532
|
const state = ensureNodeStateRoot(paths.root);
|
|
19104
|
-
|
|
19533
|
+
fs19.mkdirSync(state.leasesDir, { recursive: true });
|
|
19105
19534
|
}
|
|
19106
19535
|
function filePath(sessionId) {
|
|
19107
19536
|
return safeFilePath(paths.leasesDir, sessionId, ".json");
|
|
@@ -19138,7 +19567,7 @@ function createNodeLeaseStore(options) {
|
|
|
19138
19567
|
return withFileLock(target, () => {
|
|
19139
19568
|
const current = readJsonFile(target);
|
|
19140
19569
|
if (!current || current.lease.leaseId !== input.lease.leaseId || current.lease.ownerId !== input.lease.ownerId) return false;
|
|
19141
|
-
if (
|
|
19570
|
+
if (fs19.existsSync(target)) fs19.unlinkSync(target);
|
|
19142
19571
|
return true;
|
|
19143
19572
|
});
|
|
19144
19573
|
},
|
|
@@ -19146,7 +19575,7 @@ function createNodeLeaseStore(options) {
|
|
|
19146
19575
|
ensureDir();
|
|
19147
19576
|
const target = filePath(sessionId);
|
|
19148
19577
|
await withFileLock(target, () => {
|
|
19149
|
-
if (
|
|
19578
|
+
if (fs19.existsSync(target)) fs19.unlinkSync(target);
|
|
19150
19579
|
});
|
|
19151
19580
|
}
|
|
19152
19581
|
};
|
|
@@ -19161,26 +19590,26 @@ function createNodeClock() {
|
|
|
19161
19590
|
}
|
|
19162
19591
|
|
|
19163
19592
|
// src/node/stores/node-job-store.ts
|
|
19164
|
-
import
|
|
19165
|
-
import
|
|
19593
|
+
import fs20 from "node:fs";
|
|
19594
|
+
import path15 from "node:path";
|
|
19166
19595
|
function createNodeJobStore(options) {
|
|
19167
19596
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19168
19597
|
function ensureDir() {
|
|
19169
19598
|
const state = ensureNodeStateRoot(paths.root);
|
|
19170
|
-
|
|
19599
|
+
fs20.mkdirSync(state.jobsDir, { recursive: true });
|
|
19171
19600
|
}
|
|
19172
19601
|
function filePath(id) {
|
|
19173
19602
|
return safeFilePath(paths.jobsDir, id, ".json");
|
|
19174
19603
|
}
|
|
19175
19604
|
function sessionLockPath(sessionId) {
|
|
19176
|
-
return safeFilePath(
|
|
19605
|
+
return safeFilePath(path15.join(paths.jobsDir, ".session-locks"), sessionId, ".guard");
|
|
19177
19606
|
}
|
|
19178
19607
|
function sameOwner(first, second) {
|
|
19179
19608
|
return first?.runtimeInstanceId === second.runtimeInstanceId && first.hostProcessId === second.hostProcessId;
|
|
19180
19609
|
}
|
|
19181
19610
|
function readAll() {
|
|
19182
19611
|
ensureDir();
|
|
19183
|
-
return
|
|
19612
|
+
return fs20.readdirSync(paths.jobsDir).filter((file) => file.endsWith(".json")).flatMap((file) => {
|
|
19184
19613
|
const job = readJsonFile(filePath(file.slice(0, -5)));
|
|
19185
19614
|
return job ? [job] : [];
|
|
19186
19615
|
});
|
|
@@ -19193,7 +19622,7 @@ function createNodeJobStore(options) {
|
|
|
19193
19622
|
async create(job) {
|
|
19194
19623
|
ensureDir();
|
|
19195
19624
|
return withFileLock(filePath(job.id), function createIfMissing() {
|
|
19196
|
-
if (
|
|
19625
|
+
if (fs20.existsSync(filePath(job.id))) return false;
|
|
19197
19626
|
atomicReplace(filePath(job.id), JSON.stringify(job, null, 2));
|
|
19198
19627
|
return true;
|
|
19199
19628
|
});
|
|
@@ -19222,7 +19651,7 @@ function createNodeJobStore(options) {
|
|
|
19222
19651
|
for (const job of await this.listBySession(sessionId)) {
|
|
19223
19652
|
const target = filePath(job.id);
|
|
19224
19653
|
await withFileLock(target, () => {
|
|
19225
|
-
if (
|
|
19654
|
+
if (fs20.existsSync(target)) fs20.unlinkSync(target);
|
|
19226
19655
|
});
|
|
19227
19656
|
}
|
|
19228
19657
|
},
|
|
@@ -19251,42 +19680,42 @@ function createNodeJobOwnerProbe() {
|
|
|
19251
19680
|
|
|
19252
19681
|
// src/node/stores/node-file-mutation-store.ts
|
|
19253
19682
|
import { createHash as createHash3, randomUUID as randomUUID5 } from "node:crypto";
|
|
19254
|
-
import
|
|
19255
|
-
import
|
|
19683
|
+
import fs21 from "node:fs";
|
|
19684
|
+
import path16 from "node:path";
|
|
19256
19685
|
var MAX_FILE_SNAPSHOT_BYTES = 512 * 1024;
|
|
19257
19686
|
var MAX_SESSION_SNAPSHOT_BYTES = 5 * 1024 * 1024;
|
|
19258
19687
|
function sha256(content) {
|
|
19259
19688
|
return createHash3("sha256").update(content).digest("hex");
|
|
19260
19689
|
}
|
|
19261
19690
|
function writeBlob(blobPath, content) {
|
|
19262
|
-
if (
|
|
19263
|
-
|
|
19691
|
+
if (fs21.existsSync(blobPath)) return;
|
|
19692
|
+
fs21.mkdirSync(path16.dirname(blobPath), { recursive: true });
|
|
19264
19693
|
const temporary = `${blobPath}.${process.pid}.${randomUUID5()}.tmp`;
|
|
19265
19694
|
try {
|
|
19266
|
-
const descriptor =
|
|
19695
|
+
const descriptor = fs21.openSync(temporary, "wx");
|
|
19267
19696
|
try {
|
|
19268
|
-
|
|
19269
|
-
|
|
19697
|
+
fs21.writeFileSync(descriptor, content);
|
|
19698
|
+
fs21.fsyncSync(descriptor);
|
|
19270
19699
|
} finally {
|
|
19271
|
-
|
|
19700
|
+
fs21.closeSync(descriptor);
|
|
19272
19701
|
}
|
|
19273
19702
|
try {
|
|
19274
|
-
|
|
19703
|
+
fs21.renameSync(temporary, blobPath);
|
|
19275
19704
|
} catch (error) {
|
|
19276
|
-
if (!
|
|
19705
|
+
if (!fs21.existsSync(blobPath)) throw error;
|
|
19277
19706
|
}
|
|
19278
19707
|
} finally {
|
|
19279
|
-
if (
|
|
19708
|
+
if (fs21.existsSync(temporary)) fs21.unlinkSync(temporary);
|
|
19280
19709
|
}
|
|
19281
19710
|
}
|
|
19282
19711
|
function createNodeFileMutationStore(options) {
|
|
19283
19712
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19284
19713
|
function ensureDir() {
|
|
19285
19714
|
const state = ensureNodeStateRoot(paths.root);
|
|
19286
|
-
|
|
19287
|
-
|
|
19288
|
-
|
|
19289
|
-
|
|
19715
|
+
fs21.mkdirSync(state.mutationsDir, { recursive: true });
|
|
19716
|
+
fs21.mkdirSync(state.mutationBlobsDir, { recursive: true });
|
|
19717
|
+
fs21.mkdirSync(state.mutationLocksDir, { recursive: true });
|
|
19718
|
+
fs21.mkdirSync(state.undoTransactionsDir, { recursive: true });
|
|
19290
19719
|
}
|
|
19291
19720
|
function mutationPath(id) {
|
|
19292
19721
|
return safeFilePath(paths.mutationsDir, id, ".json");
|
|
@@ -19300,9 +19729,9 @@ function createNodeFileMutationStore(options) {
|
|
|
19300
19729
|
}
|
|
19301
19730
|
function readAll() {
|
|
19302
19731
|
ensureDir();
|
|
19303
|
-
return
|
|
19732
|
+
return fs21.readdirSync(paths.mutationsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
|
|
19304
19733
|
try {
|
|
19305
|
-
return [JSON.parse(
|
|
19734
|
+
return [JSON.parse(fs21.readFileSync(mutationPath(entry.slice(0, -5)), "utf8"))];
|
|
19306
19735
|
} catch {
|
|
19307
19736
|
return [];
|
|
19308
19737
|
}
|
|
@@ -19310,9 +19739,9 @@ function createNodeFileMutationStore(options) {
|
|
|
19310
19739
|
}
|
|
19311
19740
|
function readTransactions() {
|
|
19312
19741
|
ensureDir();
|
|
19313
|
-
return
|
|
19742
|
+
return fs21.readdirSync(paths.undoTransactionsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
|
|
19314
19743
|
try {
|
|
19315
|
-
return [JSON.parse(
|
|
19744
|
+
return [JSON.parse(fs21.readFileSync(transactionPath(entry.slice(0, -5)), "utf8"))];
|
|
19316
19745
|
} catch {
|
|
19317
19746
|
return [];
|
|
19318
19747
|
}
|
|
@@ -19320,7 +19749,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19320
19749
|
}
|
|
19321
19750
|
function sessionBlobBytes(sessionId) {
|
|
19322
19751
|
const refs3 = new Set(readAll().filter((item) => item.sessionId === sessionId).flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
|
|
19323
|
-
return [...refs3].reduce((total, ref) => total + (
|
|
19752
|
+
return [...refs3].reduce((total, ref) => total + (fs21.statSync(blobPath(ref), { throwIfNoEntry: false })?.size ?? 0), 0);
|
|
19324
19753
|
}
|
|
19325
19754
|
return {
|
|
19326
19755
|
async prepare(input) {
|
|
@@ -19330,7 +19759,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19330
19759
|
const refs3 = /* @__PURE__ */ new Map();
|
|
19331
19760
|
if (input.before) refs3.set(beforeRef, input.before);
|
|
19332
19761
|
if (input.after) refs3.set(afterRef, input.after);
|
|
19333
|
-
const additionalBytes = [...refs3.entries()].filter(([ref]) => !
|
|
19762
|
+
const additionalBytes = [...refs3.entries()].filter(([ref]) => !fs21.existsSync(blobPath(ref))).reduce((total, [, content]) => total + content.byteLength, 0);
|
|
19334
19763
|
const byteCount = (input.before?.byteLength ?? 0) + (input.after?.byteLength ?? 0);
|
|
19335
19764
|
const binary2 = Boolean(input.before?.includes(0) || input.after?.includes(0));
|
|
19336
19765
|
const reversible = !binary2 && byteCount <= MAX_FILE_SNAPSHOT_BYTES && sessionBlobBytes(input.sessionId) + additionalBytes <= MAX_SESSION_SNAPSHOT_BYTES;
|
|
@@ -19361,7 +19790,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19361
19790
|
async getBlob(ref) {
|
|
19362
19791
|
ensureDir();
|
|
19363
19792
|
try {
|
|
19364
|
-
const content =
|
|
19793
|
+
const content = fs21.readFileSync(blobPath(ref));
|
|
19365
19794
|
return sha256(content) === ref ? content : null;
|
|
19366
19795
|
} catch {
|
|
19367
19796
|
return null;
|
|
@@ -19379,46 +19808,48 @@ function createNodeFileMutationStore(options) {
|
|
|
19379
19808
|
},
|
|
19380
19809
|
async deleteBySession(sessionId) {
|
|
19381
19810
|
ensureDir();
|
|
19382
|
-
for (const mutation of readAll().filter((item) => item.sessionId === sessionId))
|
|
19383
|
-
for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId))
|
|
19811
|
+
for (const mutation of readAll().filter((item) => item.sessionId === sessionId)) fs21.rmSync(mutationPath(mutation.id), { force: true });
|
|
19812
|
+
for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId)) fs21.rmSync(transactionPath(transaction.id), { force: true });
|
|
19384
19813
|
const referenced = new Set(readAll().flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
|
|
19385
|
-
for (const entry of
|
|
19814
|
+
for (const entry of fs21.readdirSync(paths.mutationBlobsDir).filter((item) => item.endsWith(".blob"))) if (!referenced.has(entry.slice(0, -5))) fs21.rmSync(path16.join(paths.mutationBlobsDir, entry), { force: true });
|
|
19386
19815
|
},
|
|
19387
|
-
async withWorkspaceLock(workspaceRoot, operation) {
|
|
19816
|
+
async withWorkspaceLock(workspaceRoot, operation, canonicalTargets = []) {
|
|
19388
19817
|
ensureDir();
|
|
19389
|
-
const lockId = createHash3("sha256").update(
|
|
19390
|
-
return withFileLock(safeFilePath(paths.mutationLocksDir, lockId, ".lock-target"),
|
|
19818
|
+
const lockId = createHash3("sha256").update(path16.resolve(workspaceRoot)).digest("hex");
|
|
19819
|
+
return withFileLock(safeFilePath(paths.mutationLocksDir, lockId, ".lock-target"), function lockTargets() {
|
|
19820
|
+
return withNodeFileMutationLocks(canonicalTargets, operation);
|
|
19821
|
+
}, { requireExitedOwner: true });
|
|
19391
19822
|
}
|
|
19392
19823
|
};
|
|
19393
19824
|
}
|
|
19394
19825
|
|
|
19395
19826
|
// src/node/stores/node-session-resource-store.ts
|
|
19396
|
-
import
|
|
19397
|
-
import
|
|
19827
|
+
import fs22 from "node:fs";
|
|
19828
|
+
import path17 from "node:path";
|
|
19398
19829
|
function isAttachmentSessionId(sessionId) {
|
|
19399
19830
|
return /^[0-9a-f-]{36}$/iu.test(sessionId);
|
|
19400
19831
|
}
|
|
19401
19832
|
function createNodeSessionResourceStore(workspaceRoot) {
|
|
19402
19833
|
const root = canonicalizeNodePath(workspaceRoot);
|
|
19403
|
-
const uploadsRoot =
|
|
19834
|
+
const uploadsRoot = path17.join(root, ".local", "session-uploads");
|
|
19404
19835
|
return {
|
|
19405
19836
|
async deleteBySession(sessionId) {
|
|
19406
19837
|
if (!isAttachmentSessionId(sessionId)) return;
|
|
19407
|
-
const target =
|
|
19408
|
-
if (!target.startsWith(`${uploadsRoot}${
|
|
19409
|
-
|
|
19838
|
+
const target = path17.join(uploadsRoot, sessionId);
|
|
19839
|
+
if (!target.startsWith(`${uploadsRoot}${path17.sep}`)) throw new Error("SESSION_RESOURCE_PATH_INVALID");
|
|
19840
|
+
fs22.rmSync(target, { recursive: true, force: true, maxRetries: 2 });
|
|
19410
19841
|
}
|
|
19411
19842
|
};
|
|
19412
19843
|
}
|
|
19413
19844
|
|
|
19414
19845
|
// src/node/stores/node-user-question-store.ts
|
|
19415
|
-
import
|
|
19846
|
+
import fs23 from "node:fs";
|
|
19416
19847
|
function createNodeUserQuestionStore(options) {
|
|
19417
19848
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19418
19849
|
const recordsFile = `${paths.questionsDir}/requests.jsonl`;
|
|
19419
19850
|
function ensureDir() {
|
|
19420
19851
|
const state = ensureNodeStateRoot(paths.root);
|
|
19421
|
-
|
|
19852
|
+
fs23.mkdirSync(state.questionsDir, { recursive: true });
|
|
19422
19853
|
}
|
|
19423
19854
|
function answersEqual(left, right) {
|
|
19424
19855
|
return JSON.stringify(left) === JSON.stringify(right);
|
|
@@ -19482,6 +19913,7 @@ function createNodeRuntimePorts(options) {
|
|
|
19482
19913
|
throw createNodeIdentityError("WORKSPACE_REQUIRED");
|
|
19483
19914
|
}
|
|
19484
19915
|
return {
|
|
19916
|
+
hostMutationProtection: options.productMode === "chat" ? void 0 : createNodeHostMutationProtection(options),
|
|
19485
19917
|
sessionStore: createNodeSessionStore({ ...storeOptions, productMode: options.productMode }),
|
|
19486
19918
|
checkpointStore: createNodeCheckpointStore(storeOptions),
|
|
19487
19919
|
transcriptStore: createNodeTranscriptStore(storeOptions),
|
|
@@ -19492,6 +19924,8 @@ function createNodeRuntimePorts(options) {
|
|
|
19492
19924
|
workspaceAdapter: options.productMode === "chat" ? { resolveWorkspaceRoot: noWorkspace, canonicalizeWorkspaceRoot: noWorkspace, getWorkspaceInfo: noWorkspace } : createNodeWorkspaceAdapter(workspaceOptions),
|
|
19493
19925
|
turnStore: createNodeTurnStore(storeOptions),
|
|
19494
19926
|
approvalStore: createNodeApprovalStore(storeOptions),
|
|
19927
|
+
/** Work授权查询/投影复用既有Stage2端口;注入本身不产生任何grant。 */
|
|
19928
|
+
externalPermissionProjector: options.productMode === "chat" || options.workspaceRoot === void 0 ? void 0 : createNodeExternalPermissionProjector(),
|
|
19495
19929
|
inputInbox: createNodeInputInbox(storeOptions),
|
|
19496
19930
|
leaseStore: createNodeLeaseStore(storeOptions),
|
|
19497
19931
|
jobStore: createNodeJobStore(storeOptions),
|
|
@@ -19508,17 +19942,20 @@ function createNodeRuntimePorts(options) {
|
|
|
19508
19942
|
* Stage 2:Work 模式装配真实 SRT adapter(绑定 canonical workspaceRoot;tempRoot
|
|
19509
19943
|
* 必须由宿主显式验证后提供);Chat 保持 unavailable stub——Chat 不开放 Work 工具,
|
|
19510
19944
|
* 即使伪造 full_access 也不能获得进程沙箱能力。workspaceRoot 缺失时同样 fail-closed。
|
|
19945
|
+
* Talk-Plan1022 S1:Windows 宿主执行模式装配宿主执行 port——不加载 SRT、不要求
|
|
19946
|
+
* provision,进程调用经用户逐次审批后在宿主直接执行;macOS 装配保持不变。
|
|
19511
19947
|
*/
|
|
19512
|
-
sandboxPort: options.productMode === "chat" || options.workspaceRoot === void 0 ? createUnavailableSandboxPort() : createNodeSandboxPort({
|
|
19948
|
+
sandboxPort: options.productMode === "chat" || options.workspaceRoot === void 0 ? createUnavailableSandboxPort() : process.platform === "win32" ? createNodeHostExecutionSandboxPort() : createNodeSandboxPort({
|
|
19513
19949
|
workspaceRoot: options.workspaceRoot,
|
|
19950
|
+
stateRoot: options.stateRoot,
|
|
19514
19951
|
...options.sandboxTempRoot !== void 0 ? { tempRoot: options.sandboxTempRoot } : {}
|
|
19515
19952
|
})
|
|
19516
19953
|
};
|
|
19517
19954
|
}
|
|
19518
19955
|
|
|
19519
19956
|
// src/node/stores/node-chat-attachment-store.ts
|
|
19520
|
-
import
|
|
19521
|
-
import
|
|
19957
|
+
import fs24 from "node:fs";
|
|
19958
|
+
import path18 from "node:path";
|
|
19522
19959
|
import { createHash as createHash4, randomUUID as randomUUID6 } from "node:crypto";
|
|
19523
19960
|
var CHAT_ATTACHMENT_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
19524
19961
|
var MAX_BYTES = 20 * 1024 * 1024;
|
|
@@ -19558,12 +19995,12 @@ function createNodeChatAttachmentStore(options) {
|
|
|
19558
19995
|
const { paths, sessionStore } = options;
|
|
19559
19996
|
const now = options.now ?? Date.now;
|
|
19560
19997
|
const root = paths.attachmentsRoot;
|
|
19561
|
-
const dataRoot =
|
|
19562
|
-
const retiredRoot =
|
|
19563
|
-
const deletingRoot =
|
|
19564
|
-
const lock =
|
|
19998
|
+
const dataRoot = path18.join(root, "sessions");
|
|
19999
|
+
const retiredRoot = path18.join(root, "retired");
|
|
20000
|
+
const deletingRoot = path18.join(root, "deleting");
|
|
20001
|
+
const lock = path18.join(root, "lifecycle");
|
|
19565
20002
|
function ensure() {
|
|
19566
|
-
assertSafeNodePath(
|
|
20003
|
+
assertSafeNodePath(path18.dirname(paths.root), paths.root);
|
|
19567
20004
|
for (const directory of [root, dataRoot, retiredRoot, deletingRoot]) ensureChatDirectory(paths.root, directory);
|
|
19568
20005
|
assertSafeNodePath(root, `${lock}.lock`);
|
|
19569
20006
|
}
|
|
@@ -19585,9 +20022,9 @@ function createNodeChatAttachmentStore(options) {
|
|
|
19585
20022
|
}
|
|
19586
20023
|
function isSessionDeleting(sessionId) {
|
|
19587
20024
|
try {
|
|
19588
|
-
const target =
|
|
20025
|
+
const target = path18.join(deletingRoot, `${sessionKey(sessionId)}.json`);
|
|
19589
20026
|
assertSafeNodePath(root, target);
|
|
19590
|
-
return
|
|
20027
|
+
return fs24.existsSync(target);
|
|
19591
20028
|
} catch (error) {
|
|
19592
20029
|
throw toNodeBoundaryError(error, "CHAT_ATTACHMENT_UNAVAILABLE");
|
|
19593
20030
|
}
|
|
@@ -19604,16 +20041,16 @@ function createNodeChatAttachmentStore(options) {
|
|
|
19604
20041
|
if (session?.productMode !== "chat" || !["none", "web"].includes(session.chatRetrievalMode ?? "")) throw new NodeChatError("CHAT_UPLOAD_MODE_MISMATCH");
|
|
19605
20042
|
}
|
|
19606
20043
|
function records(sessionId) {
|
|
19607
|
-
const directory =
|
|
20044
|
+
const directory = path18.join(dataRoot, sessionKey(sessionId));
|
|
19608
20045
|
assertSafeNodePath(root, directory);
|
|
19609
|
-
if (!
|
|
20046
|
+
if (!fs24.existsSync(directory)) return [];
|
|
19610
20047
|
const result = [];
|
|
19611
|
-
for (const ref of
|
|
20048
|
+
for (const ref of fs24.readdirSync(directory)) {
|
|
19612
20049
|
if (!opaque.test(ref)) unavailable();
|
|
19613
|
-
const target =
|
|
20050
|
+
const target = path18.join(directory, ref, "metadata.json");
|
|
19614
20051
|
assertSafeNodePath(root, target);
|
|
19615
|
-
if (!
|
|
19616
|
-
const record = JSON.parse(
|
|
20052
|
+
if (!fs24.statSync(target).isFile() || fs24.statSync(target).size > 16384) unavailable();
|
|
20053
|
+
const record = JSON.parse(fs24.readFileSync(target, "utf8"));
|
|
19617
20054
|
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();
|
|
19618
20055
|
for (const page of record.pages) if (!opaque.test(page.ref)) unavailable();
|
|
19619
20056
|
result.push(record);
|
|
@@ -19624,7 +20061,7 @@ function createNodeChatAttachmentStore(options) {
|
|
|
19624
20061
|
return { ref: record.ref, sessionId: record.sessionId, kind: record.kind, expiresAt: record.expiresAt };
|
|
19625
20062
|
}
|
|
19626
20063
|
function active(record) {
|
|
19627
|
-
return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !
|
|
20064
|
+
return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !fs24.existsSync(path18.join(retiredRoot, `${record.ref}.json`));
|
|
19628
20065
|
}
|
|
19629
20066
|
function sanitizeSession(session) {
|
|
19630
20067
|
try {
|
|
@@ -19663,17 +20100,17 @@ function createNodeChatAttachmentStore(options) {
|
|
|
19663
20100
|
return !opaque.test(ref);
|
|
19664
20101
|
}
|
|
19665
20102
|
)) unavailable();
|
|
19666
|
-
const directory =
|
|
20103
|
+
const directory = path18.join(dataRoot, item.sessionId, item.ref);
|
|
19667
20104
|
assertSafeNodePath(root, directory);
|
|
19668
|
-
|
|
20105
|
+
fs24.rmSync(directory, { recursive: true, force: true });
|
|
19669
20106
|
await removePresentationRefs(item.sessionId, item.refs);
|
|
19670
|
-
|
|
20107
|
+
fs24.rmSync(path18.join(retiredRoot, `${item.ref}.json`), { force: true });
|
|
19671
20108
|
}
|
|
19672
20109
|
async function retire(record) {
|
|
19673
20110
|
const item = { sessionId: record.sessionId, ref: record.ref, refs: [record.ref, ...record.pages.map(function pageRef(page) {
|
|
19674
20111
|
return page.ref;
|
|
19675
20112
|
})] };
|
|
19676
|
-
atomicReplace(
|
|
20113
|
+
atomicReplace(path18.join(retiredRoot, `${record.ref}.json`), JSON.stringify(item));
|
|
19677
20114
|
await finishRetirement(item);
|
|
19678
20115
|
}
|
|
19679
20116
|
async function put(input) {
|
|
@@ -19706,13 +20143,13 @@ function createNodeChatAttachmentStore(options) {
|
|
|
19706
20143
|
const createdAt = now();
|
|
19707
20144
|
if (!Number.isSafeInteger(createdAt) || createdAt < 0) unavailable();
|
|
19708
20145
|
const ref = randomUUID6();
|
|
19709
|
-
const parent =
|
|
20146
|
+
const parent = path18.join(dataRoot, sessionKey(input.sessionId));
|
|
19710
20147
|
ensureChatDirectory(root, parent);
|
|
19711
|
-
const staging =
|
|
20148
|
+
const staging = path18.join(root, `staging-${ref}`);
|
|
19712
20149
|
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: [] };
|
|
19713
20150
|
try {
|
|
19714
20151
|
ensureChatDirectory(root, staging);
|
|
19715
|
-
|
|
20152
|
+
fs24.writeFileSync(path18.join(staging, "content"), bytes, { flag: "wx", mode: 384 });
|
|
19716
20153
|
let pageBytes = 0;
|
|
19717
20154
|
for (const inputPage of parsed?.pages ?? []) {
|
|
19718
20155
|
const page = Buffer.from(inputPage);
|
|
@@ -19720,17 +20157,17 @@ function createNodeChatAttachmentStore(options) {
|
|
|
19720
20157
|
pageBytes += page.length;
|
|
19721
20158
|
if (!type2.startsWith("image/") || !page.length || page.length > IMAGE_BYTES || pageBytes > MAX_BYTES) unavailable();
|
|
19722
20159
|
const pageRef = randomUUID6();
|
|
19723
|
-
|
|
20160
|
+
fs24.writeFileSync(path18.join(staging, pageRef), page, { flag: "wx", mode: 384 });
|
|
19724
20161
|
record.pages.push({ ref: pageRef, mimeType: type2, byteLength: page.length, sha256: digest(page) });
|
|
19725
20162
|
}
|
|
19726
|
-
if (parsed)
|
|
19727
|
-
|
|
20163
|
+
if (parsed) fs24.writeFileSync(path18.join(staging, "parsed.json"), JSON.stringify({ text: parsed.text.slice(0, 16e3) }), { flag: "wx", mode: 384 });
|
|
20164
|
+
fs24.writeFileSync(path18.join(staging, "metadata.json"), JSON.stringify(record), { flag: "wx", mode: 384 });
|
|
19728
20165
|
checkSignal(input.signal);
|
|
19729
|
-
|
|
20166
|
+
fs24.renameSync(staging, path18.join(parent, ref));
|
|
19730
20167
|
const { pages: _pages, ...view } = record;
|
|
19731
20168
|
return view;
|
|
19732
20169
|
} finally {
|
|
19733
|
-
|
|
20170
|
+
fs24.rmSync(staging, { recursive: true, force: true });
|
|
19734
20171
|
}
|
|
19735
20172
|
}, input.signal);
|
|
19736
20173
|
} catch (error) {
|
|
@@ -19772,10 +20209,10 @@ function createNodeChatAttachmentStore(options) {
|
|
|
19772
20209
|
return locked(async function readParsed() {
|
|
19773
20210
|
const { record, page } = await find3(sessionId, ref);
|
|
19774
20211
|
if (page || record.kind !== "document") unavailable();
|
|
19775
|
-
const target =
|
|
20212
|
+
const target = path18.join(dataRoot, sessionId, ref, "parsed.json");
|
|
19776
20213
|
assertSafeNodePath(root, target);
|
|
19777
|
-
if (
|
|
19778
|
-
const parsed = JSON.parse(
|
|
20214
|
+
if (fs24.statSync(target).size > 1e5) unavailable();
|
|
20215
|
+
const parsed = JSON.parse(fs24.readFileSync(target, "utf8"));
|
|
19779
20216
|
if (typeof parsed.text !== "string") unavailable();
|
|
19780
20217
|
return { text: parsed.text.slice(0, 16e3), pageImages: record.pages.map(function pageGrant(item) {
|
|
19781
20218
|
return grant({ ...record, ref: item.ref, kind: "image" });
|
|
@@ -19785,44 +20222,44 @@ function createNodeChatAttachmentStore(options) {
|
|
|
19785
20222
|
async function readBytes(sessionId, ref, signal) {
|
|
19786
20223
|
return locked(async function readContent() {
|
|
19787
20224
|
const { record, page } = await find3(sessionId, ref);
|
|
19788
|
-
const target =
|
|
20225
|
+
const target = path18.join(dataRoot, sessionId, record.ref, page?.ref ?? "content");
|
|
19789
20226
|
assertSafeNodePath(root, target);
|
|
19790
20227
|
const metadata = page ?? record;
|
|
19791
|
-
if (
|
|
19792
|
-
const bytes =
|
|
20228
|
+
if (fs24.statSync(target).size !== metadata.byteLength || metadata.byteLength > MAX_BYTES) unavailable();
|
|
20229
|
+
const bytes = fs24.readFileSync(target);
|
|
19793
20230
|
if (digest(bytes) !== metadata.sha256) unavailable();
|
|
19794
20231
|
return { bytes: new Uint8Array(bytes), mimeType: metadata.mimeType };
|
|
19795
20232
|
}, signal);
|
|
19796
20233
|
}
|
|
19797
20234
|
async function deleteBySession(sessionId) {
|
|
19798
20235
|
await locked(async function deleteSessionAttachments() {
|
|
19799
|
-
atomicReplace(
|
|
20236
|
+
atomicReplace(path18.join(deletingRoot, `${sessionKey(sessionId)}.json`), JSON.stringify({ sessionId }));
|
|
19800
20237
|
for (const record of records(sessionId)) await retire(record);
|
|
19801
20238
|
await removePresentationRefs(sessionId);
|
|
19802
|
-
|
|
20239
|
+
fs24.rmSync(path18.join(dataRoot, sessionId), { recursive: true, force: true });
|
|
19803
20240
|
}, void 0, "CHAT_ATTACHMENT_CLEANUP_FAILED");
|
|
19804
20241
|
}
|
|
19805
20242
|
async function cleanupExpired(input = {}) {
|
|
19806
20243
|
const limit = input.limit ?? 32;
|
|
19807
20244
|
if (!Number.isInteger(limit) || limit < 1 || limit > 128) throw new NodeChatError("CHAT_ATTACHMENT_CLEANUP_FAILED");
|
|
19808
20245
|
return locked(async function cleanupBatch() {
|
|
19809
|
-
for (const file of
|
|
20246
|
+
for (const file of fs24.readdirSync(root)) {
|
|
19810
20247
|
if (!/^staging-[0-9a-f-]{36}$/.test(file)) continue;
|
|
19811
|
-
const target =
|
|
20248
|
+
const target = path18.join(root, file);
|
|
19812
20249
|
assertSafeNodePath(root, target);
|
|
19813
|
-
|
|
20250
|
+
fs24.rmSync(target, { recursive: true, force: true });
|
|
19814
20251
|
}
|
|
19815
|
-
for (const file of
|
|
20252
|
+
for (const file of fs24.readdirSync(retiredRoot)) {
|
|
19816
20253
|
if (!file.endsWith(".json")) continue;
|
|
19817
|
-
const target =
|
|
20254
|
+
const target = path18.join(retiredRoot, file);
|
|
19818
20255
|
assertSafeNodePath(root, target);
|
|
19819
20256
|
checkSignal(input.signal);
|
|
19820
|
-
const item = JSON.parse(
|
|
20257
|
+
const item = JSON.parse(fs24.readFileSync(target, "utf8"));
|
|
19821
20258
|
if (file !== `${item.ref}.json`) unavailable();
|
|
19822
20259
|
await finishRetirement(item);
|
|
19823
20260
|
}
|
|
19824
20261
|
const expired = [];
|
|
19825
|
-
for (const sessionId of
|
|
20262
|
+
for (const sessionId of fs24.readdirSync(dataRoot)) {
|
|
19826
20263
|
for (const record of records(sessionId)) if (record.expiresAt <= now() || isSessionDeleting(sessionId)) expired.push(record);
|
|
19827
20264
|
}
|
|
19828
20265
|
expired.sort(function oldestFirst(left, right) {
|
|
@@ -20055,199 +20492,9 @@ function createNodeRagRuntime(options) {
|
|
|
20055
20492
|
};
|
|
20056
20493
|
}
|
|
20057
20494
|
|
|
20058
|
-
// src/node/settings/user-config-directory.ts
|
|
20059
|
-
import fs23 from "node:fs";
|
|
20060
|
-
import os4 from "node:os";
|
|
20061
|
-
import path15 from "node:path";
|
|
20062
|
-
var UserConfigDirectoryError = class extends Error {
|
|
20063
|
-
constructor(code) {
|
|
20064
|
-
super(code);
|
|
20065
|
-
this.code = code;
|
|
20066
|
-
this.name = "UserConfigDirectoryError";
|
|
20067
|
-
}
|
|
20068
|
-
};
|
|
20069
|
-
function resolveUserHome(homeDirectory) {
|
|
20070
|
-
let candidate = homeDirectory;
|
|
20071
|
-
if (candidate === void 0) {
|
|
20072
|
-
try {
|
|
20073
|
-
candidate = os4.homedir();
|
|
20074
|
-
} catch {
|
|
20075
|
-
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
20076
|
-
}
|
|
20077
|
-
}
|
|
20078
|
-
if (!candidate || !path15.isAbsolute(candidate)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
20079
|
-
return path15.resolve(candidate);
|
|
20080
|
-
}
|
|
20081
|
-
function readEntry(entryPath) {
|
|
20082
|
-
try {
|
|
20083
|
-
return fs23.lstatSync(entryPath);
|
|
20084
|
-
} catch (error) {
|
|
20085
|
-
if (error.code === "ENOENT") return void 0;
|
|
20086
|
-
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
20087
|
-
}
|
|
20088
|
-
}
|
|
20089
|
-
function isWithinHome(homeDirectory, configDirectory) {
|
|
20090
|
-
const relative = path15.relative(homeDirectory, configDirectory);
|
|
20091
|
-
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path15.sep}`) && !path15.isAbsolute(relative);
|
|
20092
|
-
}
|
|
20093
|
-
function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
20094
|
-
const entry = readEntry(configDirectory);
|
|
20095
|
-
if (!entry) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
20096
|
-
if (entry.isSymbolicLink()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
20097
|
-
if (!entry.isDirectory()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_NOT_DIRECTORY");
|
|
20098
|
-
try {
|
|
20099
|
-
const canonicalHome = fs23.realpathSync.native(homeDirectory);
|
|
20100
|
-
const canonicalConfigDirectory = fs23.realpathSync.native(configDirectory);
|
|
20101
|
-
if (!isWithinHome(canonicalHome, canonicalConfigDirectory)) {
|
|
20102
|
-
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
20103
|
-
}
|
|
20104
|
-
} catch (error) {
|
|
20105
|
-
if (error instanceof UserConfigDirectoryError) throw error;
|
|
20106
|
-
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
20107
|
-
}
|
|
20108
|
-
}
|
|
20109
|
-
function ensureUserConfigDirectory(options = {}) {
|
|
20110
|
-
const homeDirectory = resolveUserHome(options.homeDirectory);
|
|
20111
|
-
const configDirectory = path15.join(homeDirectory, ".autopilot");
|
|
20112
|
-
const existing = readEntry(configDirectory);
|
|
20113
|
-
if (existing) assertSafeConfigDirectory(homeDirectory, configDirectory);
|
|
20114
|
-
else {
|
|
20115
|
-
try {
|
|
20116
|
-
fs23.mkdirSync(configDirectory, { recursive: true, mode: 448 });
|
|
20117
|
-
} catch {
|
|
20118
|
-
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
20119
|
-
}
|
|
20120
|
-
assertSafeConfigDirectory(homeDirectory, configDirectory);
|
|
20121
|
-
}
|
|
20122
|
-
return configDirectory;
|
|
20123
|
-
}
|
|
20124
|
-
|
|
20125
|
-
// src/node/settings/node-settings-loader.ts
|
|
20126
|
-
import fs24 from "node:fs";
|
|
20127
|
-
import os5 from "node:os";
|
|
20128
|
-
import path16 from "node:path";
|
|
20129
|
-
import {
|
|
20130
|
-
resolveAutopilotSettings
|
|
20131
|
-
} from "@autopilot-agent/core";
|
|
20132
|
-
function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = path16) {
|
|
20133
|
-
try {
|
|
20134
|
-
const home = homeDirectory ?? os5.homedir();
|
|
20135
|
-
if (!pathApi.isAbsolute(home)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
20136
|
-
return pathApi.join(home, ".autopilot", "settings.json");
|
|
20137
|
-
} catch {
|
|
20138
|
-
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
20139
|
-
}
|
|
20140
|
-
}
|
|
20141
|
-
function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = os5.homedir(), pathApi = path16) {
|
|
20142
|
-
const root = pathApi.resolve(workspaceRoot);
|
|
20143
|
-
return {
|
|
20144
|
-
user: pathApi.join(homeDirectory, ".autopilot", "settings.json"),
|
|
20145
|
-
project: pathApi.join(root, ".autopilot", "settings.json"),
|
|
20146
|
-
local: pathApi.join(root, ".autopilot", "settings.local.json")
|
|
20147
|
-
};
|
|
20148
|
-
}
|
|
20149
|
-
function createNodeSettingsLoader(options = {}) {
|
|
20150
|
-
const debounceMs = options.debounceMs ?? 100;
|
|
20151
|
-
function isSafeSettingsFile(filePath) {
|
|
20152
|
-
try {
|
|
20153
|
-
const file = fs24.lstatSync(filePath);
|
|
20154
|
-
const configDirectory = path16.dirname(filePath);
|
|
20155
|
-
const directory = fs24.lstatSync(configDirectory);
|
|
20156
|
-
if (!file.isFile() || file.isSymbolicLink() || !directory.isDirectory() || directory.isSymbolicLink()) return false;
|
|
20157
|
-
const canonicalDirectory = fs24.realpathSync.native(configDirectory);
|
|
20158
|
-
const canonicalFile = fs24.realpathSync.native(filePath);
|
|
20159
|
-
const relative = path16.relative(canonicalDirectory, canonicalFile);
|
|
20160
|
-
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path16.sep}`) && !path16.isAbsolute(relative);
|
|
20161
|
-
} catch (error) {
|
|
20162
|
-
return error.code === "ENOENT";
|
|
20163
|
-
}
|
|
20164
|
-
}
|
|
20165
|
-
function readSource(scope, filePath) {
|
|
20166
|
-
if (!fs24.existsSync(filePath)) {
|
|
20167
|
-
try {
|
|
20168
|
-
if (fs24.lstatSync(filePath).isSymbolicLink()) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
20169
|
-
} catch {
|
|
20170
|
-
return void 0;
|
|
20171
|
-
}
|
|
20172
|
-
return void 0;
|
|
20173
|
-
}
|
|
20174
|
-
if (!isSafeSettingsFile(filePath)) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
20175
|
-
try {
|
|
20176
|
-
return { scope, value: JSON.parse(fs24.readFileSync(filePath, "utf8")), diagnostics: [] };
|
|
20177
|
-
} catch {
|
|
20178
|
-
return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_JSON_INVALID" }] };
|
|
20179
|
-
}
|
|
20180
|
-
}
|
|
20181
|
-
function load2(workspaceRoot) {
|
|
20182
|
-
return loadPaths(resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory));
|
|
20183
|
-
}
|
|
20184
|
-
function loadUser() {
|
|
20185
|
-
return loadPaths({ user: resolveNodeUserSettingsPath(options.homeDirectory) });
|
|
20186
|
-
}
|
|
20187
|
-
function loadPaths(paths) {
|
|
20188
|
-
const sources = Object.entries(paths).map(function readEntry2([scope, filePath]) {
|
|
20189
|
-
return readSource(scope, filePath);
|
|
20190
|
-
}).filter((source) => Boolean(source));
|
|
20191
|
-
const settings = resolveAutopilotSettings(sources.map(({ scope, value }) => ({ scope, value })));
|
|
20192
|
-
const diagnostics = [...settings.diagnostics, ...sources.flatMap((source) => source.diagnostics)];
|
|
20193
|
-
return { paths, settings: { ...settings, diagnostics } };
|
|
20194
|
-
}
|
|
20195
|
-
function watch(workspaceRoot, onReload) {
|
|
20196
|
-
const paths = resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory);
|
|
20197
|
-
return watchPaths(Object.values(paths), function reloadWorkspace() {
|
|
20198
|
-
onReload(load2(workspaceRoot));
|
|
20199
|
-
});
|
|
20200
|
-
}
|
|
20201
|
-
function watchUser(onReload) {
|
|
20202
|
-
return watchPaths([resolveNodeUserSettingsPath(options.homeDirectory)], function reloadUser() {
|
|
20203
|
-
onReload(loadUser());
|
|
20204
|
-
});
|
|
20205
|
-
}
|
|
20206
|
-
function watchPaths(watched, reload) {
|
|
20207
|
-
let timer;
|
|
20208
|
-
let watchers = [];
|
|
20209
|
-
function installWatchers() {
|
|
20210
|
-
for (const watcher of watchers) watcher.close();
|
|
20211
|
-
const uniqueDirectories = [...new Set(watched.flatMap(function collectWatchDirectories(filePath) {
|
|
20212
|
-
const directory = path16.dirname(filePath);
|
|
20213
|
-
return [directory, path16.dirname(directory)];
|
|
20214
|
-
}))].filter(
|
|
20215
|
-
/** 不把用户配置目录的链接目标注册为监听面;父目录仍能观察链接被替换。 */
|
|
20216
|
-
function safeWatchDirectory(directory) {
|
|
20217
|
-
return fs24.existsSync(directory) && fs24.lstatSync(directory).isDirectory() && !fs24.lstatSync(directory).isSymbolicLink();
|
|
20218
|
-
}
|
|
20219
|
-
);
|
|
20220
|
-
watchers = uniqueDirectories.flatMap(function watchParent(directory) {
|
|
20221
|
-
try {
|
|
20222
|
-
const watcher = fs24.watch(directory, function reloadOnTargetFile(_eventType, fileName) {
|
|
20223
|
-
if (!fileName || !watched.some((target) => path16.basename(target) === fileName.toString() || path16.basename(path16.dirname(target)) === fileName.toString())) return;
|
|
20224
|
-
if (timer) clearTimeout(timer);
|
|
20225
|
-
timer = setTimeout(function reloadAfterDebounce() {
|
|
20226
|
-
reload();
|
|
20227
|
-
installWatchers();
|
|
20228
|
-
}, debounceMs);
|
|
20229
|
-
});
|
|
20230
|
-
watcher.unref();
|
|
20231
|
-
watcher.on("error", function ignoreWatcherError() {
|
|
20232
|
-
});
|
|
20233
|
-
return [watcher];
|
|
20234
|
-
} catch {
|
|
20235
|
-
return [];
|
|
20236
|
-
}
|
|
20237
|
-
});
|
|
20238
|
-
}
|
|
20239
|
-
installWatchers();
|
|
20240
|
-
return function stopWatchingSettings() {
|
|
20241
|
-
if (timer) clearTimeout(timer);
|
|
20242
|
-
for (const watcher of watchers) watcher.close();
|
|
20243
|
-
};
|
|
20244
|
-
}
|
|
20245
|
-
return { load: load2, watch, loadUser, watchUser };
|
|
20246
|
-
}
|
|
20247
|
-
|
|
20248
20495
|
// src/node/settings/node-settings-writer.ts
|
|
20249
20496
|
import fs25 from "node:fs";
|
|
20250
|
-
import { resolveAutopilotSettings as
|
|
20497
|
+
import { resolveAutopilotSettings as resolveAutopilotSettings3 } from "@autopilot-agent/core";
|
|
20251
20498
|
var CONFIG_KEY_ALLOWLIST = /* @__PURE__ */ new Set([
|
|
20252
20499
|
"model",
|
|
20253
20500
|
"effortLevel",
|
|
@@ -20292,7 +20539,7 @@ function createNodeSettingsWriter(options = {}) {
|
|
|
20292
20539
|
cursor = cursor[part];
|
|
20293
20540
|
}
|
|
20294
20541
|
cursor[parts[parts.length - 1]] = parsedValue;
|
|
20295
|
-
|
|
20542
|
+
resolveAutopilotSettings3([{ scope, value: target }]);
|
|
20296
20543
|
atomicReplace(getPaths(workspaceRoot)[scope], JSON.stringify(target, null, 2));
|
|
20297
20544
|
return toSafeView(target);
|
|
20298
20545
|
}
|
|
@@ -20359,7 +20606,7 @@ function parseConfigValue(key2, rawValue) {
|
|
|
20359
20606
|
// src/node/settings/node-user-settings-service.ts
|
|
20360
20607
|
import { createHash as createHash5 } from "node:crypto";
|
|
20361
20608
|
import fs26 from "node:fs";
|
|
20362
|
-
import { normalizeProviderBaseUrl, resolveAutopilotSettings as
|
|
20609
|
+
import { isExternalPermissionDiagnostic, normalizeProviderBaseUrl, resolveAutopilotSettings as resolveAutopilotSettings4 } from "@autopilot-agent/core";
|
|
20363
20610
|
var RAG_ROLE_CONTRACT = Object.freeze({
|
|
20364
20611
|
textRerank: { provider: "bailian", key: "RAG_TEXT_RERANK_API_KEY", dimension: false },
|
|
20365
20612
|
visionRerank: { provider: "bailian", key: "RAG_VISION_RERANK_API_KEY", dimension: false },
|
|
@@ -20367,11 +20614,24 @@ var RAG_ROLE_CONTRACT = Object.freeze({
|
|
|
20367
20614
|
multimodalEmbedding: { provider: "dashscope", key: "RAG_MULTIMODAL_EMBEDDING_API_KEY", dimension: true }
|
|
20368
20615
|
});
|
|
20369
20616
|
var NodeUserSettingsError = class extends Error {
|
|
20370
|
-
constructor(code) {
|
|
20617
|
+
constructor(code, diagnostic) {
|
|
20371
20618
|
super(code);
|
|
20372
20619
|
this.code = code;
|
|
20620
|
+
this.diagnostic = diagnostic;
|
|
20373
20621
|
}
|
|
20374
20622
|
};
|
|
20623
|
+
function safeDiagnostic(diagnostic) {
|
|
20624
|
+
return { code: diagnostic.code, scope: diagnostic.scope, ...diagnostic.field ? { field: diagnostic.field } : {} };
|
|
20625
|
+
}
|
|
20626
|
+
function splitDiagnostics(diagnostics) {
|
|
20627
|
+
const blocking = [];
|
|
20628
|
+
const permissions = [];
|
|
20629
|
+
for (const diagnostic of diagnostics) {
|
|
20630
|
+
if (isExternalPermissionDiagnostic(diagnostic)) permissions.push(safeDiagnostic(diagnostic));
|
|
20631
|
+
else blocking.push(diagnostic);
|
|
20632
|
+
}
|
|
20633
|
+
return { blocking, permissions };
|
|
20634
|
+
}
|
|
20375
20635
|
function isRecord4(value) {
|
|
20376
20636
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
20377
20637
|
}
|
|
@@ -20473,7 +20733,7 @@ function applyMainCategory(raw, input) {
|
|
|
20473
20733
|
return candidate.value;
|
|
20474
20734
|
}))];
|
|
20475
20735
|
if (!normalized.apiKey && distinct.length > 1) throw new NodeUserSettingsError("SETTINGS_MIGRATION_CONFLICT");
|
|
20476
|
-
const previous =
|
|
20736
|
+
const previous = resolveAutopilotSettings4([{ scope: "user", value: raw }]);
|
|
20477
20737
|
const previousRoute = previous.modelRef && previous.providerRoutes[previous.modelRef.provider];
|
|
20478
20738
|
const previousBaseUrl = normalizeProviderBaseUrl(previousRoute?.baseUrl ?? previous.firstParty.baseUrl);
|
|
20479
20739
|
const officialDeepSeekMigration = previousBaseUrl === "https://api.deepseek.com" && normalized.baseUrl === "https://api.deepseek.com/anthropic";
|
|
@@ -20578,9 +20838,8 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20578
20838
|
const current = readUserSettings(settingsPath);
|
|
20579
20839
|
assertRevision(current.original, revision);
|
|
20580
20840
|
update2(current.raw);
|
|
20581
|
-
const
|
|
20582
|
-
|
|
20583
|
-
if (blockingDiagnostics.length > 0) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
20841
|
+
const { blocking } = splitDiagnostics(resolveAutopilotSettings4([{ scope: "user", value: current.raw }]).diagnostics);
|
|
20842
|
+
if (blocking.length > 0) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID", safeDiagnostic(blocking[0]));
|
|
20584
20843
|
const content = `${JSON.stringify(current.raw, null, 2)}
|
|
20585
20844
|
`;
|
|
20586
20845
|
atomicReplace(settingsPath, content);
|
|
@@ -20616,9 +20875,9 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20616
20875
|
const current = readUserSettings(settingsPath);
|
|
20617
20876
|
const raw = current.raw;
|
|
20618
20877
|
const environment = isRecord4(raw.env) ? raw.env : {};
|
|
20619
|
-
const resolved =
|
|
20620
|
-
const
|
|
20621
|
-
if (
|
|
20878
|
+
const resolved = resolveAutopilotSettings4([{ scope: "user", value: raw }]);
|
|
20879
|
+
const { blocking, permissions } = splitDiagnostics(resolved.diagnostics);
|
|
20880
|
+
if (blocking.length > 0) throw new NodeUserSettingsError("SETTINGS_INVALID", safeDiagnostic(blocking[0]));
|
|
20622
20881
|
const mainBaseUrl = resolved.firstParty.baseUrl ?? "https://api.deepseek.com/anthropic";
|
|
20623
20882
|
const mainModel = resolved.modelRef?.modelId ?? "deepseek-v4-flash";
|
|
20624
20883
|
const mainKey = readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY");
|
|
@@ -20663,6 +20922,7 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20663
20922
|
model: search?.model ?? "deepseek-v4-flash",
|
|
20664
20923
|
configured: Boolean(search && searchKey)
|
|
20665
20924
|
},
|
|
20925
|
+
diagnostics: permissions,
|
|
20666
20926
|
rag
|
|
20667
20927
|
};
|
|
20668
20928
|
},
|
|
@@ -20702,15 +20962,15 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20702
20962
|
// src/node/capabilities/memory-retriever.ts
|
|
20703
20963
|
import crypto3 from "node:crypto";
|
|
20704
20964
|
import fs27 from "node:fs";
|
|
20705
|
-
import
|
|
20965
|
+
import path19 from "node:path";
|
|
20706
20966
|
function getNodeMemoryWorkspaceId(workspaceRoot) {
|
|
20707
20967
|
return crypto3.createHash("sha256").update(fs27.realpathSync.native(workspaceRoot).toLowerCase()).digest("hex").slice(0, 24);
|
|
20708
20968
|
}
|
|
20709
20969
|
function getNodeMemoryDirectory(stateRoot, workspaceRoot) {
|
|
20710
|
-
return
|
|
20970
|
+
return path19.join(path19.resolve(stateRoot), "memory", getNodeMemoryWorkspaceId(workspaceRoot));
|
|
20711
20971
|
}
|
|
20712
20972
|
function getLegacyWebMemoryDirectory(workspaceRoot, cwd = process.cwd()) {
|
|
20713
|
-
return
|
|
20973
|
+
return path19.join(path19.resolve(cwd), ".local", "agent", "workspaces", getNodeMemoryWorkspaceId(workspaceRoot), "memory");
|
|
20714
20974
|
}
|
|
20715
20975
|
function retrieveNodeMemories(_stateRoot, _workspaceRoot, _query, _maxItems = 5) {
|
|
20716
20976
|
return [];
|
|
@@ -20718,10 +20978,10 @@ function retrieveNodeMemories(_stateRoot, _workspaceRoot, _query, _maxItems = 5)
|
|
|
20718
20978
|
|
|
20719
20979
|
// src/node/trust-policy.ts
|
|
20720
20980
|
import fs28 from "node:fs";
|
|
20721
|
-
import
|
|
20981
|
+
import path20 from "node:path";
|
|
20722
20982
|
function createNodeTrustStore(options) {
|
|
20723
20983
|
const trustRoot = resolveNodeTrustRoot({ stateRoot: options.stateRoot, trustRoot: options.trustRoot });
|
|
20724
|
-
const trustFile =
|
|
20984
|
+
const trustFile = path20.join(trustRoot, "trust.json");
|
|
20725
20985
|
const now = options.now ?? (() => Date.now());
|
|
20726
20986
|
function ensureDir() {
|
|
20727
20987
|
fs28.mkdirSync(trustRoot, { recursive: true });
|
|
@@ -20832,10 +21092,10 @@ function createNodeTrustPolicy(options) {
|
|
|
20832
21092
|
|
|
20833
21093
|
// src/node/workspace-registry.ts
|
|
20834
21094
|
import fs29 from "node:fs";
|
|
20835
|
-
import
|
|
21095
|
+
import path21 from "node:path";
|
|
20836
21096
|
function createNodeWorkspaceRegistry(options = {}) {
|
|
20837
21097
|
const globalStateRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: options.cwd });
|
|
20838
|
-
const registryPath =
|
|
21098
|
+
const registryPath = path21.join(globalStateRoot, "workspace-registry.json");
|
|
20839
21099
|
const now = options.now ?? (() => Date.now());
|
|
20840
21100
|
function load2() {
|
|
20841
21101
|
if (!fs29.existsSync(registryPath)) return [];
|
|
@@ -20863,7 +21123,7 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
20863
21123
|
const next = {
|
|
20864
21124
|
workspaceId,
|
|
20865
21125
|
workspaceRoot: canonicalRoot,
|
|
20866
|
-
displayName:
|
|
21126
|
+
displayName: path21.basename(canonicalRoot) || canonicalRoot,
|
|
20867
21127
|
lastOpenedAt: now()
|
|
20868
21128
|
};
|
|
20869
21129
|
const entries2 = load2().filter(function removeExisting(entry) {
|
|
@@ -20909,7 +21169,9 @@ export {
|
|
|
20909
21169
|
createNodeClock,
|
|
20910
21170
|
createNodeCredentialStore,
|
|
20911
21171
|
createNodeEventSink,
|
|
21172
|
+
createNodeExternalPermissionProjector,
|
|
20912
21173
|
createNodeFileMutationStore,
|
|
21174
|
+
createNodeHostExecutionSandboxPort,
|
|
20913
21175
|
createNodeInputInbox,
|
|
20914
21176
|
createNodeJobOwnerProbe,
|
|
20915
21177
|
createNodeJobStore,
|
|
@@ -20944,8 +21206,8 @@ export {
|
|
|
20944
21206
|
getNodeStatePaths,
|
|
20945
21207
|
getNodeStateSchemaDiagnostic,
|
|
20946
21208
|
initializeNodeStateRoot,
|
|
21209
|
+
isSafeSettingsFile,
|
|
20947
21210
|
loadMcpConfigFromWorkspace,
|
|
20948
|
-
readWindowsSandboxCapability,
|
|
20949
21211
|
resolveNodeChatStatePaths,
|
|
20950
21212
|
resolveNodeGlobalStateRoot,
|
|
20951
21213
|
resolveNodeSettingsPaths,
|
|
@@ -20953,6 +21215,5 @@ export {
|
|
|
20953
21215
|
resolveNodeTrustRoot,
|
|
20954
21216
|
resolveNodeUserSettingsPath,
|
|
20955
21217
|
retrieveNodeMemories,
|
|
20956
|
-
runWindowsSandboxSetup,
|
|
20957
21218
|
serializePosixCommand
|
|
20958
21219
|
};
|