@autopilot-agent/adapters 0.2.0 → 0.3.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 +6 -4
- package/dist/index.d.ts +6 -0
- package/dist/index.js +1619 -332
- package/dist/index.mjs +1590 -308
- package/dist/node/create-node-chat-capability-loader.d.ts +1 -0
- package/dist/node/file-utils.d.ts +7 -0
- package/dist/node/host-identity.d.ts +2 -0
- package/dist/node/node-errors.d.ts +11 -2
- package/dist/node/state-root.d.ts +1 -1
- package/dist/node/state-upgrade.d.ts +2 -0
- package/dist/node/stores/node-session-image-store.d.ts +2 -0
- package/dist/node/stores/node-thread-store.d.ts +2 -0
- package/dist/node/stores/session-directory.d.ts +1 -0
- package/dist/node/thread-handoff.d.ts +5 -0
- package/dist/node/thread-runner.d.ts +53 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -2139,6 +2139,7 @@ __export(index_exports, {
|
|
|
2139
2139
|
DEFAULT_COMPACT_TARGET_RATIO: () => DEFAULT_COMPACT_TARGET_RATIO,
|
|
2140
2140
|
DEFAULT_COMPACT_TRIGGER_RATIO: () => DEFAULT_COMPACT_TRIGGER_RATIO,
|
|
2141
2141
|
DEFAULT_CONTEXT_WINDOW_TOKENS: () => DEFAULT_CONTEXT_WINDOW_TOKENS,
|
|
2142
|
+
LOCAL_HUMAN_PRINCIPAL_ID: () => LOCAL_HUMAN_PRINCIPAL_ID,
|
|
2142
2143
|
NODE_CHAT_KNOWLEDGE_SPACE_ID: () => NODE_CHAT_KNOWLEDGE_SPACE_ID,
|
|
2143
2144
|
NODE_STATE_SCHEMA_VERSION: () => NODE_STATE_SCHEMA_VERSION,
|
|
2144
2145
|
NODE_WORKSPACE_ID_VERSION: () => NODE_WORKSPACE_ID_VERSION,
|
|
@@ -2170,11 +2171,15 @@ __export(index_exports, {
|
|
|
2170
2171
|
createNodeRagRuntime: () => createNodeRagRuntime,
|
|
2171
2172
|
createNodeRuntimePorts: () => createNodeRuntimePorts,
|
|
2172
2173
|
createNodeSandboxPort: () => createNodeSandboxPort,
|
|
2174
|
+
createNodeSessionImageStore: () => createNodeSessionImageStore,
|
|
2173
2175
|
createNodeSessionResourceStore: () => createNodeSessionResourceStore,
|
|
2174
2176
|
createNodeSessionStore: () => createNodeSessionStore,
|
|
2175
2177
|
createNodeSettingsLoader: () => createNodeSettingsLoader,
|
|
2176
2178
|
createNodeSettingsWriter: () => createNodeSettingsWriter,
|
|
2179
|
+
createNodeStateRootId: () => createNodeStateRootId,
|
|
2177
2180
|
createNodeStateSchemaManager: () => createNodeStateSchemaManager,
|
|
2181
|
+
createNodeThreadHandoffWriter: () => createNodeThreadHandoffWriter,
|
|
2182
|
+
createNodeThreadRunner: () => createNodeThreadRunner,
|
|
2178
2183
|
createNodeTranscriptStore: () => createNodeTranscriptStore,
|
|
2179
2184
|
createNodeTrustPolicy: () => createNodeTrustPolicy,
|
|
2180
2185
|
createNodeTrustStore: () => createNodeTrustStore,
|
|
@@ -2242,14 +2247,20 @@ var runtimeMessages = {
|
|
|
2242
2247
|
};
|
|
2243
2248
|
var NodeStateError = class extends Error {
|
|
2244
2249
|
/** 只使用固定错误码作为消息,恢复信息保存为不可枚举的私有字段。 */
|
|
2245
|
-
constructor(code, recovery) {
|
|
2250
|
+
constructor(code, recovery, storage) {
|
|
2246
2251
|
super(code);
|
|
2247
2252
|
this.code = code;
|
|
2248
2253
|
this.name = "NodeStateError";
|
|
2249
2254
|
this.#recovery = recovery ? { ...recovery } : void 0;
|
|
2255
|
+
this.#storage = storage ? { ...storage } : void 0;
|
|
2250
2256
|
}
|
|
2251
2257
|
#recovery;
|
|
2258
|
+
#storage;
|
|
2252
2259
|
/** 受信宿主显式取得恢复信息副本,不得将它投影到 HTTP 或模型事件。 */
|
|
2260
|
+
/** 受信CLI诊断显式读取,序列化错误不会暴露内部阶段。 */
|
|
2261
|
+
getStorageDiagnostic() {
|
|
2262
|
+
return this.#storage ? { ...this.#storage } : void 0;
|
|
2263
|
+
}
|
|
2253
2264
|
getRecoveryDiagnostic() {
|
|
2254
2265
|
return this.#recovery ? { ...this.#recovery } : void 0;
|
|
2255
2266
|
}
|
|
@@ -2265,19 +2276,19 @@ var NodeChatError = class extends Error {
|
|
|
2265
2276
|
function createNodeIdentityError(code) {
|
|
2266
2277
|
return new import_core.AgentRuntimeError(code, runtimeMessages[code]);
|
|
2267
2278
|
}
|
|
2268
|
-
function toNodeBoundaryError(error, fallback) {
|
|
2279
|
+
function toNodeBoundaryError(error, fallback, storage) {
|
|
2269
2280
|
if (error instanceof Error && "code" in error && typeof error.code === "string") {
|
|
2270
2281
|
if (error.name === "AgentRuntimeError" && Object.prototype.hasOwnProperty.call(runtimeMessages, error.code)) return createNodeIdentityError(error.code);
|
|
2271
2282
|
if (error.name === "NodeStateError" && stateCodes.includes(error.code)) {
|
|
2272
|
-
return new NodeStateError(error.code, error instanceof NodeStateError ? error.getRecoveryDiagnostic() : void 0);
|
|
2283
|
+
return new NodeStateError(error.code, error instanceof NodeStateError ? error.getRecoveryDiagnostic() : void 0, storage ?? (error instanceof NodeStateError ? error.getStorageDiagnostic() : void 0));
|
|
2273
2284
|
}
|
|
2274
2285
|
if (error.name === "NodeChatError" && chatCodes.includes(error.code)) return new NodeChatError(error.code);
|
|
2275
2286
|
}
|
|
2276
|
-
return stateCodes.includes(fallback) ? new NodeStateError(fallback) : new NodeChatError(fallback);
|
|
2287
|
+
return stateCodes.includes(fallback) ? new NodeStateError(fallback, void 0, storage) : new NodeChatError(fallback);
|
|
2277
2288
|
}
|
|
2278
2289
|
|
|
2279
2290
|
// src/node/create-node-runtime-ports.ts
|
|
2280
|
-
var
|
|
2291
|
+
var import_core17 = require("@autopilot-agent/core");
|
|
2281
2292
|
|
|
2282
2293
|
// src/node/capabilities/context-budget.ts
|
|
2283
2294
|
var DEFAULT_CONTEXT_WINDOW_TOKENS = 128e3;
|
|
@@ -17453,7 +17464,7 @@ function loadSrtRuntimeSurface() {
|
|
|
17453
17464
|
}
|
|
17454
17465
|
|
|
17455
17466
|
// src/node/sandbox/node-sandbox-port.ts
|
|
17456
|
-
var
|
|
17467
|
+
var import_node_path9 = __toESM(require("node:path"));
|
|
17457
17468
|
|
|
17458
17469
|
// src/node/file-mutation-locks.ts
|
|
17459
17470
|
var import_node_os2 = __toESM(require("node:os"));
|
|
@@ -17465,6 +17476,16 @@ var import_node_fs5 = __toESM(require("node:fs"));
|
|
|
17465
17476
|
var import_promises2 = __toESM(require("node:fs/promises"));
|
|
17466
17477
|
var import_node_crypto3 = require("node:crypto");
|
|
17467
17478
|
var import_node_path4 = __toESM(require("node:path"));
|
|
17479
|
+
var fileDiagnostics = /* @__PURE__ */ new WeakMap();
|
|
17480
|
+
function getFileOperationDiagnostic(error) {
|
|
17481
|
+
return error && typeof error === "object" ? fileDiagnostics.get(error) : void 0;
|
|
17482
|
+
}
|
|
17483
|
+
function rememberFileFailure(error, diagnostic) {
|
|
17484
|
+
if (!error || typeof error !== "object") return;
|
|
17485
|
+
const code = error.code;
|
|
17486
|
+
const osCode = ["EACCES", "EPERM", "ENOENT", "EEXIST", "ENOSPC", "EIO", "EMFILE", "ENFILE", "EBUSY", "EROFS", "ENOTDIR", "ETIMEDOUT"].includes(code ?? "") ? code : void 0;
|
|
17487
|
+
fileDiagnostics.set(error, { ...diagnostic, ...osCode ? { osCode } : {} });
|
|
17488
|
+
}
|
|
17468
17489
|
var fileLocks = /* @__PURE__ */ new Map();
|
|
17469
17490
|
var PROCESS_LOCK_RETRY_MS = 10;
|
|
17470
17491
|
var PROCESS_LOCK_TIMEOUT_MS = 3e4;
|
|
@@ -17579,7 +17600,14 @@ async function withFileLock(filePath, operation, options) {
|
|
|
17579
17600
|
fileLocks.set(key2, queued);
|
|
17580
17601
|
try {
|
|
17581
17602
|
await previous;
|
|
17582
|
-
const
|
|
17603
|
+
const startedAt = Date.now();
|
|
17604
|
+
let handle;
|
|
17605
|
+
try {
|
|
17606
|
+
handle = await acquireProcessLock(key2, options?.requireExitedOwner);
|
|
17607
|
+
} catch (error) {
|
|
17608
|
+
rememberFileFailure(error, { phase: "lock", lockWaitMs: Date.now() - startedAt });
|
|
17609
|
+
throw error;
|
|
17610
|
+
}
|
|
17583
17611
|
try {
|
|
17584
17612
|
return await operation();
|
|
17585
17613
|
} finally {
|
|
@@ -17658,11 +17686,26 @@ function ensureParentDirectory(filePath) {
|
|
|
17658
17686
|
function atomicReplace(filePath, content) {
|
|
17659
17687
|
ensureParentDirectory(filePath);
|
|
17660
17688
|
const temporaryPath = `${filePath}.${process.pid}.${(0, import_node_crypto3.randomUUID)()}.tmp`;
|
|
17689
|
+
let phase = "temporary_write";
|
|
17690
|
+
let failure;
|
|
17661
17691
|
try {
|
|
17662
17692
|
import_node_fs5.default.writeFileSync(temporaryPath, content, { encoding: "utf8", flag: "wx" });
|
|
17693
|
+
phase = "rename";
|
|
17663
17694
|
import_node_fs5.default.renameSync(temporaryPath, filePath);
|
|
17695
|
+
} catch (error) {
|
|
17696
|
+
failure = error;
|
|
17697
|
+
rememberFileFailure(error, { phase });
|
|
17698
|
+
throw error;
|
|
17664
17699
|
} finally {
|
|
17665
|
-
|
|
17700
|
+
try {
|
|
17701
|
+
if (import_node_fs5.default.existsSync(temporaryPath)) import_node_fs5.default.unlinkSync(temporaryPath);
|
|
17702
|
+
} catch (error) {
|
|
17703
|
+
if (failure) rememberFileFailure(failure, { ...getFileOperationDiagnostic(failure), cleanupFailed: true });
|
|
17704
|
+
else {
|
|
17705
|
+
rememberFileFailure(error, { phase: "cleanup" });
|
|
17706
|
+
throw error;
|
|
17707
|
+
}
|
|
17708
|
+
}
|
|
17666
17709
|
}
|
|
17667
17710
|
}
|
|
17668
17711
|
function safeFilePath(directory, key2, extension) {
|
|
@@ -17738,22 +17781,37 @@ async function withNodeFileMutationLocks(canonicalTargets, operation) {
|
|
|
17738
17781
|
}
|
|
17739
17782
|
|
|
17740
17783
|
// src/node/state-root.ts
|
|
17741
|
-
var
|
|
17742
|
-
var
|
|
17784
|
+
var import_node_fs8 = __toESM(require("node:fs"));
|
|
17785
|
+
var import_node_crypto7 = require("node:crypto");
|
|
17743
17786
|
var import_node_os3 = __toESM(require("node:os"));
|
|
17744
|
-
var
|
|
17787
|
+
var import_node_path8 = __toESM(require("node:path"));
|
|
17745
17788
|
|
|
17746
17789
|
// src/node/state-schema-manager.ts
|
|
17747
17790
|
var import_node_fs6 = __toESM(require("node:fs"));
|
|
17748
17791
|
var import_node_path6 = __toESM(require("node:path"));
|
|
17749
17792
|
var import_node_crypto5 = require("node:crypto");
|
|
17793
|
+
function hasExitedLockOwner(file) {
|
|
17794
|
+
try {
|
|
17795
|
+
const metadata = JSON.parse(import_node_fs6.default.readFileSync(file, "utf8"));
|
|
17796
|
+
if (!Number.isSafeInteger(metadata?.pid) || metadata.pid <= 0) return false;
|
|
17797
|
+
try {
|
|
17798
|
+
process.kill(metadata.pid, 0);
|
|
17799
|
+
} catch (error) {
|
|
17800
|
+
return error.code === "ESRCH";
|
|
17801
|
+
}
|
|
17802
|
+
return false;
|
|
17803
|
+
} catch {
|
|
17804
|
+
return false;
|
|
17805
|
+
}
|
|
17806
|
+
}
|
|
17750
17807
|
function assertPlainStateTree(root) {
|
|
17751
17808
|
const entry = import_node_fs6.default.lstatSync(root);
|
|
17752
17809
|
if (entry.isSymbolicLink() || !entry.isDirectory() && !entry.isFile()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17753
17810
|
if (!entry.isDirectory()) return;
|
|
17754
17811
|
for (const name of import_node_fs6.default.readdirSync(root)) {
|
|
17755
|
-
|
|
17756
|
-
assertPlainStateTree(
|
|
17812
|
+
const child = import_node_path6.default.join(root, name);
|
|
17813
|
+
assertPlainStateTree(child);
|
|
17814
|
+
if (name.endsWith(".lock") && !hasExitedLockOwner(child)) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17757
17815
|
}
|
|
17758
17816
|
}
|
|
17759
17817
|
function acquireSchemaLock(root) {
|
|
@@ -17816,6 +17874,14 @@ function createBackupPath(root, fromVersion, toVersion) {
|
|
|
17816
17874
|
function backupStateRoot(root, fromVersion, toVersion) {
|
|
17817
17875
|
if (!hasDurableState(root)) return void 0;
|
|
17818
17876
|
assertPlainStateTree(root);
|
|
17877
|
+
const leases = import_node_path6.default.join(root, "leases");
|
|
17878
|
+
if (import_node_fs6.default.existsSync(leases)) {
|
|
17879
|
+
for (const file of import_node_fs6.default.readdirSync(leases)) {
|
|
17880
|
+
if (!file.endsWith(".json")) continue;
|
|
17881
|
+
const record = JSON.parse(import_node_fs6.default.readFileSync(import_node_path6.default.join(leases, file), "utf8"));
|
|
17882
|
+
if (Number.isFinite(record?.lease?.heartbeatAt) && Date.now() - record.lease.heartbeatAt <= 45e3) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17883
|
+
}
|
|
17884
|
+
}
|
|
17819
17885
|
const backupPath = createBackupPath(root, fromVersion, toVersion);
|
|
17820
17886
|
const backupRoot = import_node_path6.default.dirname(backupPath);
|
|
17821
17887
|
if (import_node_fs6.default.existsSync(backupRoot) && import_node_fs6.default.lstatSync(backupRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
@@ -17901,6 +17967,11 @@ function createNodeStateSchemaManager(options) {
|
|
|
17901
17967
|
if (!Number.isInteger(fromVersion) || !Number.isInteger(toVersion)) {
|
|
17902
17968
|
throw new NodeStateError("STATE_SCHEMA_VERSION_INVALID");
|
|
17903
17969
|
}
|
|
17970
|
+
for (let version = fromVersion; version < toVersion; version++) {
|
|
17971
|
+
if (!options.migrations.some(function adjacent(step) {
|
|
17972
|
+
return step.fromVersion === version && step.toVersion === version + 1;
|
|
17973
|
+
})) throw new NodeStateError("STATE_SCHEMA_MIGRATION_MISSING");
|
|
17974
|
+
}
|
|
17904
17975
|
const backupPath = backup(fromVersion, toVersion);
|
|
17905
17976
|
try {
|
|
17906
17977
|
if (import_node_fs6.default.existsSync(root)) import_node_fs6.default.cpSync(root, stagingRoot, { recursive: true, errorOnExist: true });
|
|
@@ -17951,7 +18022,12 @@ function normalizeNodeSession(value, id) {
|
|
|
17951
18022
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
17952
18023
|
const session = value;
|
|
17953
18024
|
if (session.id !== id || !Number.isFinite(session.createdAt) || !Number.isFinite(session.updatedAt)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
17954
|
-
const
|
|
18025
|
+
const source = session.creationSource;
|
|
18026
|
+
if (source !== void 0) {
|
|
18027
|
+
const actor = source?.actor;
|
|
18028
|
+
if (!session.collaborationCreationId || !source || typeof source.requestId !== "string" || !source.requestId || !actor || actor.kind !== "human" && actor.kind !== "thread" || actor.kind === "human" && (typeof actor.principalId !== "string" || !actor.principalId) || actor.kind === "thread" && (typeof actor.threadId !== "string" || !actor.threadId || typeof actor.turnId !== "string" || !actor.turnId)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18029
|
+
}
|
|
18030
|
+
const mode = session.productMode;
|
|
17955
18031
|
if (mode === "chat") {
|
|
17956
18032
|
if (session.projectId !== void 0 || !["none", "web", "rag"].includes(session.chatRetrievalMode ?? "")) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17957
18033
|
} else if (mode !== "work" || session.chatRetrievalMode !== void 0 || typeof session.projectId !== "string" || !session.projectId.trim()) {
|
|
@@ -17960,13 +18036,62 @@ function normalizeNodeSession(value, id) {
|
|
|
17960
18036
|
return { ...session, productMode: mode };
|
|
17961
18037
|
}
|
|
17962
18038
|
function assertNodeSessionIdentity(previous, next) {
|
|
18039
|
+
if (JSON.stringify(previous.collaborationAllowedTools) !== JSON.stringify(next.collaborationAllowedTools)) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
18040
|
+
if (JSON.stringify(previous.creationSource) !== JSON.stringify(next.creationSource)) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
18041
|
+
if (previous.collaborationCreationId !== next.collaborationCreationId) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17963
18042
|
if (previous.workContextVersion !== next.workContextVersion) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17964
18043
|
if (previous.productMode !== next.productMode || previous.projectId !== next.projectId) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17965
18044
|
if (previous.chatRetrievalMode !== next.chatRetrievalMode) throw createNodeIdentityError("CHAT_RETRIEVAL_MODE_LOCKED");
|
|
17966
18045
|
}
|
|
17967
18046
|
|
|
18047
|
+
// src/node/state-upgrade.ts
|
|
18048
|
+
var import_node_fs7 = __toESM(require("node:fs"));
|
|
18049
|
+
var import_node_path7 = __toESM(require("node:path"));
|
|
18050
|
+
var import_node_crypto6 = require("node:crypto");
|
|
18051
|
+
function upgradeSessionIdentity(root, allowLegacyWork) {
|
|
18052
|
+
const directory = import_node_path7.default.join(root, "sessions");
|
|
18053
|
+
if (!import_node_fs7.default.existsSync(directory)) return;
|
|
18054
|
+
for (const file of import_node_fs7.default.readdirSync(directory)) {
|
|
18055
|
+
if (!file.endsWith(".json")) continue;
|
|
18056
|
+
const target = import_node_path7.default.join(directory, file);
|
|
18057
|
+
let value;
|
|
18058
|
+
try {
|
|
18059
|
+
value = JSON.parse(import_node_fs7.default.readFileSync(target, "utf8"));
|
|
18060
|
+
} catch {
|
|
18061
|
+
throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18062
|
+
}
|
|
18063
|
+
const missingMode = value && typeof value === "object" && value.productMode === void 0;
|
|
18064
|
+
if (missingMode && allowLegacyWork) value.productMode = "work";
|
|
18065
|
+
const session = normalizeNodeSession(value, file.slice(0, -5));
|
|
18066
|
+
if (missingMode && allowLegacyWork) import_node_fs7.default.writeFileSync(target, JSON.stringify(session, null, 2), "utf8");
|
|
18067
|
+
}
|
|
18068
|
+
}
|
|
18069
|
+
function upgradeThreadCreationSources(root) {
|
|
18070
|
+
upgradeSessionIdentity(root, false);
|
|
18071
|
+
const groups = import_node_path7.default.join(root, "threads", "groups");
|
|
18072
|
+
if (!import_node_fs7.default.existsSync(groups)) return;
|
|
18073
|
+
for (const groupId of import_node_fs7.default.readdirSync(groups)) {
|
|
18074
|
+
const file = import_node_path7.default.join(groups, groupId, "control.json");
|
|
18075
|
+
if (!import_node_fs7.default.existsSync(file)) continue;
|
|
18076
|
+
const control = JSON.parse(import_node_fs7.default.readFileSync(file, "utf8"));
|
|
18077
|
+
if (control.group?.groupId !== groupId || !Array.isArray(control.creates)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18078
|
+
for (const intent of control.creates) {
|
|
18079
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(intent.threadId)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18080
|
+
const target = import_node_path7.default.join(root, "sessions", `${intent.threadId}.json`);
|
|
18081
|
+
if (!import_node_fs7.default.existsSync(target)) continue;
|
|
18082
|
+
const session = normalizeNodeSession(JSON.parse(import_node_fs7.default.readFileSync(target, "utf8")), intent.threadId);
|
|
18083
|
+
const creationId = (0, import_node_crypto6.createHash)("sha256").update(JSON.stringify([groupId, intent.actorKey, intent.requestId])).digest("hex");
|
|
18084
|
+
if (session.collaborationCreationId !== creationId || session.projectId !== control.group.projectId) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18085
|
+
const source = { actor: intent.from, requestId: intent.requestId };
|
|
18086
|
+
const next = normalizeNodeSession({ ...session, creationSource: source }, session.id);
|
|
18087
|
+
if (session.creationSource !== void 0 && JSON.stringify(session.creationSource) !== JSON.stringify(source)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18088
|
+
if (session.creationSource === void 0) import_node_fs7.default.writeFileSync(target, JSON.stringify(next, null, 2), "utf8");
|
|
18089
|
+
}
|
|
18090
|
+
}
|
|
18091
|
+
}
|
|
18092
|
+
|
|
17968
18093
|
// src/node/state-root.ts
|
|
17969
|
-
var NODE_STATE_SCHEMA_VERSION =
|
|
18094
|
+
var NODE_STATE_SCHEMA_VERSION = 8;
|
|
17970
18095
|
var NODE_WORKSPACE_ID_VERSION = 1;
|
|
17971
18096
|
var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
17972
18097
|
fromVersion: 0,
|
|
@@ -17977,47 +18102,47 @@ var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
|
17977
18102
|
fromVersion: 1,
|
|
17978
18103
|
toVersion: 2,
|
|
17979
18104
|
migrate(stagingRoot) {
|
|
17980
|
-
|
|
18105
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "jobs"), { recursive: true });
|
|
17981
18106
|
}
|
|
17982
18107
|
}, {
|
|
17983
18108
|
fromVersion: 2,
|
|
17984
18109
|
toVersion: 3,
|
|
17985
18110
|
migrate(stagingRoot) {
|
|
17986
|
-
|
|
17987
|
-
|
|
17988
|
-
|
|
17989
|
-
|
|
18111
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "mutations"), { recursive: true });
|
|
18112
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "mutation-blobs"), { recursive: true });
|
|
18113
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "mutation-locks"), { recursive: true });
|
|
18114
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "undo-transactions"), { recursive: true });
|
|
17990
18115
|
}
|
|
17991
18116
|
}, {
|
|
17992
18117
|
fromVersion: 3,
|
|
17993
18118
|
toVersion: 4,
|
|
17994
18119
|
migrate(stagingRoot) {
|
|
17995
|
-
|
|
18120
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "questions"), { recursive: true });
|
|
17996
18121
|
}
|
|
17997
18122
|
}, {
|
|
17998
18123
|
fromVersion: 4,
|
|
17999
18124
|
toVersion: 5,
|
|
18000
18125
|
/** 仅在迁移副本补写产品身份;缺失归属只能采用唯一已有 Project,不能猜工作区。 */
|
|
18001
18126
|
migrate(stagingRoot) {
|
|
18002
|
-
const sessions =
|
|
18003
|
-
if (!
|
|
18004
|
-
const projects =
|
|
18005
|
-
const candidates =
|
|
18127
|
+
const sessions = import_node_path8.default.join(stagingRoot, "sessions");
|
|
18128
|
+
if (!import_node_fs8.default.existsSync(sessions)) return;
|
|
18129
|
+
const projects = import_node_path8.default.join(stagingRoot, "projects");
|
|
18130
|
+
const candidates = import_node_fs8.default.existsSync(projects) ? import_node_fs8.default.readdirSync(projects).filter(
|
|
18006
18131
|
/** 只检查现有 Project 记录,不创建新的工作区身份。 */
|
|
18007
18132
|
function projectFile(file) {
|
|
18008
18133
|
return file.endsWith(".json");
|
|
18009
18134
|
}
|
|
18010
18135
|
) : [];
|
|
18011
|
-
for (const file of
|
|
18136
|
+
for (const file of import_node_fs8.default.readdirSync(sessions)) {
|
|
18012
18137
|
if (!file.endsWith(".json")) continue;
|
|
18013
|
-
const target =
|
|
18014
|
-
const value = JSON.parse(
|
|
18138
|
+
const target = import_node_path8.default.join(sessions, file);
|
|
18139
|
+
const value = JSON.parse(import_node_fs8.default.readFileSync(target, "utf8"));
|
|
18015
18140
|
if (value && value.productMode === void 0 && value.projectId === void 0 && candidates.length === 1) {
|
|
18016
|
-
const project = JSON.parse(
|
|
18141
|
+
const project = JSON.parse(import_node_fs8.default.readFileSync(import_node_path8.default.join(projects, candidates[0]), "utf8"));
|
|
18017
18142
|
if (project.id === candidates[0].slice(0, -5) && typeof project.workspaceRoot === "string" && project.workspaceRoot) value.projectId = project.id;
|
|
18018
18143
|
}
|
|
18019
18144
|
const session = normalizeNodeSession(value, file.slice(0, -5));
|
|
18020
|
-
|
|
18145
|
+
import_node_fs8.default.writeFileSync(target, JSON.stringify(session, null, 2), "utf8");
|
|
18021
18146
|
}
|
|
18022
18147
|
}
|
|
18023
18148
|
}, {
|
|
@@ -18025,70 +18150,87 @@ var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
|
18025
18150
|
toVersion: 6,
|
|
18026
18151
|
migrate() {
|
|
18027
18152
|
}
|
|
18153
|
+
}, {
|
|
18154
|
+
fromVersion: 6,
|
|
18155
|
+
toVersion: 7,
|
|
18156
|
+
/** v7 严格校验产品身份;旧 Work 缺省值在副本中显式落盘。 */
|
|
18157
|
+
migrate(stagingRoot) {
|
|
18158
|
+
upgradeSessionIdentity(stagingRoot, true);
|
|
18159
|
+
}
|
|
18160
|
+
}, {
|
|
18161
|
+
fromVersion: 7,
|
|
18162
|
+
toVersion: 8,
|
|
18163
|
+
/** 新来源只从已有持久意图恢复;旧进展仍保留为无任务归属的会话进展。 */
|
|
18164
|
+
migrate(stagingRoot) {
|
|
18165
|
+
upgradeThreadCreationSources(stagingRoot);
|
|
18166
|
+
}
|
|
18028
18167
|
}];
|
|
18029
18168
|
function canonicalizeNodePath(candidate, baseDirectory = process.cwd()) {
|
|
18030
|
-
const resolved =
|
|
18169
|
+
const resolved = import_node_path8.default.resolve(baseDirectory, candidate);
|
|
18031
18170
|
try {
|
|
18032
|
-
return
|
|
18171
|
+
return import_node_fs8.default.realpathSync.native(resolved);
|
|
18033
18172
|
} catch {
|
|
18034
18173
|
return resolved;
|
|
18035
18174
|
}
|
|
18036
18175
|
}
|
|
18037
18176
|
function createNodeWorkspaceId(workspaceRoot, baseDirectory) {
|
|
18038
18177
|
const canonicalRoot = canonicalizeNodePath(workspaceRoot, baseDirectory);
|
|
18039
|
-
const digest2 = (0,
|
|
18178
|
+
const digest2 = (0, import_node_crypto7.createHash)("sha256").update(canonicalRoot).digest("hex").slice(0, 24);
|
|
18040
18179
|
return `v${NODE_WORKSPACE_ID_VERSION}-${digest2}`;
|
|
18041
18180
|
}
|
|
18042
18181
|
function resolveNodeGlobalStateRoot(options = {}) {
|
|
18043
18182
|
const baseDirectory = options.cwd ?? process.cwd();
|
|
18044
|
-
const defaultRoot = process.env.LOCALAPPDATA ?
|
|
18183
|
+
const defaultRoot = process.env.LOCALAPPDATA ? import_node_path8.default.join(process.env.LOCALAPPDATA, "autopilot-agent") : import_node_path8.default.join(import_node_os3.default.homedir(), ".autopilot-agent");
|
|
18045
18184
|
return canonicalizeNodePath(options.globalStateRoot ?? defaultRoot, baseDirectory);
|
|
18046
18185
|
}
|
|
18047
18186
|
function resolveNodeStateRoot(options = {}) {
|
|
18048
18187
|
const baseDirectory = options.cwd ?? process.cwd();
|
|
18049
18188
|
if (options.stateRoot) return canonicalizeNodePath(options.stateRoot, baseDirectory);
|
|
18050
18189
|
const workspaceRoot = options.workspaceRoot ?? baseDirectory;
|
|
18051
|
-
return
|
|
18190
|
+
return import_node_path8.default.join(resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: baseDirectory }), "workspaces", createNodeWorkspaceId(workspaceRoot, baseDirectory));
|
|
18052
18191
|
}
|
|
18053
18192
|
function resolveNodeTrustRoot(options) {
|
|
18054
18193
|
const stateRoot = canonicalizeNodePath(options.stateRoot);
|
|
18055
|
-
return canonicalizeNodePath(options.trustRoot ??
|
|
18194
|
+
return canonicalizeNodePath(options.trustRoot ?? import_node_path8.default.resolve(stateRoot, "..", "agent"));
|
|
18056
18195
|
}
|
|
18057
18196
|
function getNodeStatePaths(stateRoot) {
|
|
18058
18197
|
const root = canonicalizeNodePath(stateRoot);
|
|
18059
18198
|
return {
|
|
18060
18199
|
root,
|
|
18061
|
-
schemaFile:
|
|
18062
|
-
sessionsDir:
|
|
18063
|
-
checkpointsDir:
|
|
18064
|
-
transcriptsDir:
|
|
18065
|
-
projectsDir:
|
|
18066
|
-
turnsDir:
|
|
18067
|
-
approvalsDir:
|
|
18068
|
-
inboxDir:
|
|
18069
|
-
leasesDir:
|
|
18070
|
-
jobsDir:
|
|
18071
|
-
mutationsDir:
|
|
18072
|
-
mutationBlobsDir:
|
|
18073
|
-
mutationLocksDir:
|
|
18074
|
-
undoTransactionsDir:
|
|
18075
|
-
questionsDir:
|
|
18200
|
+
schemaFile: import_node_path8.default.join(root, "schema.json"),
|
|
18201
|
+
sessionsDir: import_node_path8.default.join(root, "sessions"),
|
|
18202
|
+
checkpointsDir: import_node_path8.default.join(root, "checkpoints"),
|
|
18203
|
+
transcriptsDir: import_node_path8.default.join(root, "transcripts"),
|
|
18204
|
+
projectsDir: import_node_path8.default.join(root, "projects"),
|
|
18205
|
+
turnsDir: import_node_path8.default.join(root, "turns"),
|
|
18206
|
+
approvalsDir: import_node_path8.default.join(root, "approvals"),
|
|
18207
|
+
inboxDir: import_node_path8.default.join(root, "inbox"),
|
|
18208
|
+
leasesDir: import_node_path8.default.join(root, "leases"),
|
|
18209
|
+
jobsDir: import_node_path8.default.join(root, "jobs"),
|
|
18210
|
+
mutationsDir: import_node_path8.default.join(root, "mutations"),
|
|
18211
|
+
mutationBlobsDir: import_node_path8.default.join(root, "mutation-blobs"),
|
|
18212
|
+
mutationLocksDir: import_node_path8.default.join(root, "mutation-locks"),
|
|
18213
|
+
undoTransactionsDir: import_node_path8.default.join(root, "undo-transactions"),
|
|
18214
|
+
questionsDir: import_node_path8.default.join(root, "questions")
|
|
18076
18215
|
};
|
|
18077
18216
|
}
|
|
18078
18217
|
function assertNodeStateSchema(stateRoot) {
|
|
18079
18218
|
const paths = getNodeStatePaths(stateRoot);
|
|
18080
|
-
if (!
|
|
18081
|
-
createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations:
|
|
18219
|
+
if (!import_node_fs8.default.existsSync(paths.schemaFile)) throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
18220
|
+
createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: [] }).verify();
|
|
18082
18221
|
}
|
|
18083
18222
|
function ensureNodeStateRoot(stateRoot) {
|
|
18084
18223
|
return initializeNodeStateRoot(stateRoot);
|
|
18085
18224
|
}
|
|
18086
18225
|
function initializeNodeStateRoot(stateRoot) {
|
|
18087
18226
|
try {
|
|
18088
|
-
if (
|
|
18227
|
+
if (import_node_fs8.default.existsSync(stateRoot) && import_node_fs8.default.lstatSync(stateRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
18089
18228
|
const paths = getNodeStatePaths(stateRoot);
|
|
18229
|
+
const recovering = import_node_fs8.default.existsSync(`${paths.root}.schema-original`);
|
|
18230
|
+
if (!recovering && !import_node_fs8.default.existsSync(paths.schemaFile) && import_node_fs8.default.existsSync(paths.root) && import_node_fs8.default.readdirSync(paths.root).length !== 0) throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
18090
18231
|
const manager = createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS });
|
|
18091
18232
|
manager.migrate();
|
|
18233
|
+
assertNodeStateSchema(paths.root);
|
|
18092
18234
|
return paths;
|
|
18093
18235
|
} catch (error) {
|
|
18094
18236
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
@@ -18103,11 +18245,11 @@ function getNodeStateCorruptionDiagnostics(stateRoot) {
|
|
|
18103
18245
|
const directories = [paths.approvalsDir, paths.checkpointsDir, paths.inboxDir, paths.transcriptsDir, paths.questionsDir];
|
|
18104
18246
|
const diagnostics = [];
|
|
18105
18247
|
for (const directory of directories) {
|
|
18106
|
-
if (!
|
|
18107
|
-
for (const entry of
|
|
18108
|
-
const filePath =
|
|
18248
|
+
if (!import_node_fs8.default.existsSync(directory)) continue;
|
|
18249
|
+
for (const entry of import_node_fs8.default.readdirSync(directory).filter((file) => file.endsWith(".jsonl"))) {
|
|
18250
|
+
const filePath = import_node_path8.default.join(directory, entry);
|
|
18109
18251
|
const result = readJsonLines(filePath);
|
|
18110
|
-
for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file:
|
|
18252
|
+
for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file: import_node_path8.default.relative(paths.root, filePath) });
|
|
18111
18253
|
}
|
|
18112
18254
|
}
|
|
18113
18255
|
return diagnostics;
|
|
@@ -18160,9 +18302,9 @@ function createNodeSandboxPort(options) {
|
|
|
18160
18302
|
return result;
|
|
18161
18303
|
}
|
|
18162
18304
|
function protectAuthority(policy) {
|
|
18163
|
-
const settingsRoot =
|
|
18305
|
+
const settingsRoot = import_node_path9.default.join(options.workspaceRoot, ".autopilot");
|
|
18164
18306
|
const writes = [getNodeFileMutationLockRoot(), ...["settings.json", "settings.local.json", "mcp.json"].map(function settingsPath(file) {
|
|
18165
|
-
return
|
|
18307
|
+
return import_node_path9.default.join(settingsRoot, file);
|
|
18166
18308
|
})];
|
|
18167
18309
|
const state = options.stateRoot ? [options.stateRoot, canonicalizeNodePath(options.stateRoot)] : [];
|
|
18168
18310
|
return { ...policy, deniedRead: [.../* @__PURE__ */ new Set([...policy.deniedRead, ...state])], deniedWrite: [.../* @__PURE__ */ new Set([...policy.deniedWrite, ...state, ...writes, ...writes.map(function canonical(candidate) {
|
|
@@ -18357,20 +18499,20 @@ function describePlatform() {
|
|
|
18357
18499
|
}
|
|
18358
18500
|
|
|
18359
18501
|
// src/node/workspace-adapter.ts
|
|
18360
|
-
var
|
|
18361
|
-
var
|
|
18502
|
+
var import_node_fs9 = __toESM(require("node:fs"));
|
|
18503
|
+
var import_node_path10 = __toESM(require("node:path"));
|
|
18362
18504
|
function findWorkspaceRoot(startDirectory) {
|
|
18363
18505
|
let current = canonicalizeNodePath(startDirectory);
|
|
18364
18506
|
while (true) {
|
|
18365
|
-
const manifestPath =
|
|
18366
|
-
if (
|
|
18507
|
+
const manifestPath = import_node_path10.default.join(current, "package.json");
|
|
18508
|
+
if (import_node_fs9.default.existsSync(manifestPath)) {
|
|
18367
18509
|
try {
|
|
18368
|
-
const manifest = JSON.parse(
|
|
18510
|
+
const manifest = JSON.parse(import_node_fs9.default.readFileSync(manifestPath, "utf8"));
|
|
18369
18511
|
if (manifest.workspaces) return canonicalizeNodePath(current);
|
|
18370
18512
|
} catch {
|
|
18371
18513
|
}
|
|
18372
18514
|
}
|
|
18373
|
-
const parent =
|
|
18515
|
+
const parent = import_node_path10.default.dirname(current);
|
|
18374
18516
|
if (parent === current) throw new Error("\u65E0\u6CD5\u5B9A\u4F4D Agent \u5DE5\u4F5C\u533A\uFF1B\u8BF7\u8BBE\u7F6E AGENT_WORKSPACE_ROOT");
|
|
18375
18517
|
current = parent;
|
|
18376
18518
|
}
|
|
@@ -18389,20 +18531,20 @@ function createNodeWorkspaceAdapter(options = {}) {
|
|
|
18389
18531
|
const root = canonicalizeWorkspaceRoot(workspaceRoot);
|
|
18390
18532
|
const markers = [];
|
|
18391
18533
|
for (const marker of ["AGENTS.md", ".autopilot", ".claude"]) {
|
|
18392
|
-
if (
|
|
18534
|
+
if (import_node_fs9.default.existsSync(import_node_path10.default.join(root, marker))) markers.push(marker);
|
|
18393
18535
|
}
|
|
18394
18536
|
return {
|
|
18395
18537
|
root,
|
|
18396
18538
|
hasTrustMarker: markers.length > 0,
|
|
18397
18539
|
trustMarkers: markers,
|
|
18398
|
-
displayName:
|
|
18540
|
+
displayName: import_node_path10.default.basename(root)
|
|
18399
18541
|
};
|
|
18400
18542
|
}
|
|
18401
18543
|
return { resolveWorkspaceRoot, canonicalizeWorkspaceRoot, getWorkspaceInfo };
|
|
18402
18544
|
}
|
|
18403
18545
|
|
|
18404
18546
|
// src/node/stores/node-approval-store.ts
|
|
18405
|
-
var
|
|
18547
|
+
var import_node_fs10 = __toESM(require("node:fs"));
|
|
18406
18548
|
var import_core10 = require("@autopilot-agent/core");
|
|
18407
18549
|
function createNodeApprovalStore(options) {
|
|
18408
18550
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
@@ -18410,7 +18552,7 @@ function createNodeApprovalStore(options) {
|
|
|
18410
18552
|
const grantsFile = `${paths.approvalsDir}/grants.jsonl`;
|
|
18411
18553
|
function ensureDir() {
|
|
18412
18554
|
const state = ensureNodeStateRoot(paths.root);
|
|
18413
|
-
|
|
18555
|
+
import_node_fs10.default.mkdirSync(state.approvalsDir, { recursive: true });
|
|
18414
18556
|
}
|
|
18415
18557
|
return {
|
|
18416
18558
|
/** 待审批私有身份复用 decisions.jsonl;记录类型不与真实 decision 混淆。 */
|
|
@@ -18657,15 +18799,15 @@ function createNodeApprovalStore(options) {
|
|
|
18657
18799
|
}
|
|
18658
18800
|
|
|
18659
18801
|
// src/node/settings/node-external-permission-projector.ts
|
|
18660
|
-
var
|
|
18802
|
+
var import_node_fs13 = __toESM(require("node:fs"));
|
|
18661
18803
|
var import_node_os6 = __toESM(require("node:os"));
|
|
18662
18804
|
var import_core12 = require("@autopilot-agent/core");
|
|
18663
18805
|
var import_core13 = require("@autopilot-agent/core");
|
|
18664
18806
|
|
|
18665
18807
|
// src/node/settings/user-config-directory.ts
|
|
18666
|
-
var
|
|
18808
|
+
var import_node_fs11 = __toESM(require("node:fs"));
|
|
18667
18809
|
var import_node_os4 = __toESM(require("node:os"));
|
|
18668
|
-
var
|
|
18810
|
+
var import_node_path11 = __toESM(require("node:path"));
|
|
18669
18811
|
var UserConfigDirectoryError = class extends Error {
|
|
18670
18812
|
constructor(code) {
|
|
18671
18813
|
super(code);
|
|
@@ -18682,20 +18824,20 @@ function resolveUserHome(homeDirectory) {
|
|
|
18682
18824
|
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18683
18825
|
}
|
|
18684
18826
|
}
|
|
18685
|
-
if (!candidate || !
|
|
18686
|
-
return
|
|
18827
|
+
if (!candidate || !import_node_path11.default.isAbsolute(candidate)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18828
|
+
return import_node_path11.default.resolve(candidate);
|
|
18687
18829
|
}
|
|
18688
18830
|
function readEntry(entryPath) {
|
|
18689
18831
|
try {
|
|
18690
|
-
return
|
|
18832
|
+
return import_node_fs11.default.lstatSync(entryPath);
|
|
18691
18833
|
} catch (error) {
|
|
18692
18834
|
if (error.code === "ENOENT") return void 0;
|
|
18693
18835
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18694
18836
|
}
|
|
18695
18837
|
}
|
|
18696
18838
|
function isWithinHome(homeDirectory, configDirectory) {
|
|
18697
|
-
const relative =
|
|
18698
|
-
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${
|
|
18839
|
+
const relative = import_node_path11.default.relative(homeDirectory, configDirectory);
|
|
18840
|
+
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${import_node_path11.default.sep}`) && !import_node_path11.default.isAbsolute(relative);
|
|
18699
18841
|
}
|
|
18700
18842
|
function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
18701
18843
|
const entry = readEntry(configDirectory);
|
|
@@ -18703,8 +18845,8 @@ function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
|
18703
18845
|
if (entry.isSymbolicLink()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
18704
18846
|
if (!entry.isDirectory()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_NOT_DIRECTORY");
|
|
18705
18847
|
try {
|
|
18706
|
-
const canonicalHome =
|
|
18707
|
-
const canonicalConfigDirectory =
|
|
18848
|
+
const canonicalHome = import_node_fs11.default.realpathSync.native(homeDirectory);
|
|
18849
|
+
const canonicalConfigDirectory = import_node_fs11.default.realpathSync.native(configDirectory);
|
|
18708
18850
|
if (!isWithinHome(canonicalHome, canonicalConfigDirectory)) {
|
|
18709
18851
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
18710
18852
|
}
|
|
@@ -18715,12 +18857,12 @@ function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
|
18715
18857
|
}
|
|
18716
18858
|
function ensureUserConfigDirectory(options = {}) {
|
|
18717
18859
|
const homeDirectory = resolveUserHome(options.homeDirectory);
|
|
18718
|
-
const configDirectory =
|
|
18860
|
+
const configDirectory = import_node_path11.default.join(homeDirectory, ".autopilot");
|
|
18719
18861
|
const existing = readEntry(configDirectory);
|
|
18720
18862
|
if (existing) assertSafeConfigDirectory(homeDirectory, configDirectory);
|
|
18721
18863
|
else {
|
|
18722
18864
|
try {
|
|
18723
|
-
|
|
18865
|
+
import_node_fs11.default.mkdirSync(configDirectory, { recursive: true, mode: 448 });
|
|
18724
18866
|
} catch {
|
|
18725
18867
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18726
18868
|
}
|
|
@@ -18730,11 +18872,11 @@ function ensureUserConfigDirectory(options = {}) {
|
|
|
18730
18872
|
}
|
|
18731
18873
|
|
|
18732
18874
|
// src/node/settings/node-settings-loader.ts
|
|
18733
|
-
var
|
|
18875
|
+
var import_node_fs12 = __toESM(require("node:fs"));
|
|
18734
18876
|
var import_node_os5 = __toESM(require("node:os"));
|
|
18735
|
-
var
|
|
18877
|
+
var import_node_path12 = __toESM(require("node:path"));
|
|
18736
18878
|
var import_core11 = require("@autopilot-agent/core");
|
|
18737
|
-
function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi =
|
|
18879
|
+
function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = import_node_path12.default) {
|
|
18738
18880
|
try {
|
|
18739
18881
|
const home = homeDirectory ?? import_node_os5.default.homedir();
|
|
18740
18882
|
if (!pathApi.isAbsolute(home)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
@@ -18743,7 +18885,7 @@ function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = import_no
|
|
|
18743
18885
|
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18744
18886
|
}
|
|
18745
18887
|
}
|
|
18746
|
-
function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = import_node_os5.default.homedir(), pathApi =
|
|
18888
|
+
function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = import_node_os5.default.homedir(), pathApi = import_node_path12.default) {
|
|
18747
18889
|
const root = pathApi.resolve(workspaceRoot);
|
|
18748
18890
|
return {
|
|
18749
18891
|
user: pathApi.join(homeDirectory, ".autopilot", "settings.json"),
|
|
@@ -18753,14 +18895,14 @@ function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = import_node_os5
|
|
|
18753
18895
|
}
|
|
18754
18896
|
function isSafeSettingsFile(filePath) {
|
|
18755
18897
|
try {
|
|
18756
|
-
const file =
|
|
18757
|
-
const configDirectory =
|
|
18758
|
-
const directory =
|
|
18898
|
+
const file = import_node_fs12.default.lstatSync(filePath);
|
|
18899
|
+
const configDirectory = import_node_path12.default.dirname(filePath);
|
|
18900
|
+
const directory = import_node_fs12.default.lstatSync(configDirectory);
|
|
18759
18901
|
if (!file.isFile() || file.isSymbolicLink() || !directory.isDirectory() || directory.isSymbolicLink()) return false;
|
|
18760
|
-
const canonicalDirectory =
|
|
18761
|
-
const canonicalFile =
|
|
18762
|
-
const relative =
|
|
18763
|
-
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${
|
|
18902
|
+
const canonicalDirectory = import_node_fs12.default.realpathSync.native(configDirectory);
|
|
18903
|
+
const canonicalFile = import_node_fs12.default.realpathSync.native(filePath);
|
|
18904
|
+
const relative = import_node_path12.default.relative(canonicalDirectory, canonicalFile);
|
|
18905
|
+
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${import_node_path12.default.sep}`) && !import_node_path12.default.isAbsolute(relative);
|
|
18764
18906
|
} catch (error) {
|
|
18765
18907
|
return error.code === "ENOENT";
|
|
18766
18908
|
}
|
|
@@ -18768,9 +18910,9 @@ function isSafeSettingsFile(filePath) {
|
|
|
18768
18910
|
function createNodeSettingsLoader(options = {}) {
|
|
18769
18911
|
const debounceMs = options.debounceMs ?? 100;
|
|
18770
18912
|
function readSource(scope, filePath) {
|
|
18771
|
-
if (!
|
|
18913
|
+
if (!import_node_fs12.default.existsSync(filePath)) {
|
|
18772
18914
|
try {
|
|
18773
|
-
if (
|
|
18915
|
+
if (import_node_fs12.default.lstatSync(filePath).isSymbolicLink()) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
18774
18916
|
} catch {
|
|
18775
18917
|
return void 0;
|
|
18776
18918
|
}
|
|
@@ -18778,7 +18920,7 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18778
18920
|
}
|
|
18779
18921
|
if (!isSafeSettingsFile(filePath)) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
18780
18922
|
try {
|
|
18781
|
-
return { scope, value: JSON.parse(
|
|
18923
|
+
return { scope, value: JSON.parse(import_node_fs12.default.readFileSync(filePath, "utf8")), diagnostics: [] };
|
|
18782
18924
|
} catch {
|
|
18783
18925
|
return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_JSON_INVALID" }] };
|
|
18784
18926
|
}
|
|
@@ -18814,18 +18956,18 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18814
18956
|
function installWatchers() {
|
|
18815
18957
|
for (const watcher of watchers) watcher.close();
|
|
18816
18958
|
const uniqueDirectories = [...new Set(watched.flatMap(function collectWatchDirectories(filePath) {
|
|
18817
|
-
const directory =
|
|
18818
|
-
return [directory,
|
|
18959
|
+
const directory = import_node_path12.default.dirname(filePath);
|
|
18960
|
+
return [directory, import_node_path12.default.dirname(directory)];
|
|
18819
18961
|
}))].filter(
|
|
18820
18962
|
/** 不把用户配置目录的链接目标注册为监听面;父目录仍能观察链接被替换。 */
|
|
18821
18963
|
function safeWatchDirectory(directory) {
|
|
18822
|
-
return
|
|
18964
|
+
return import_node_fs12.default.existsSync(directory) && import_node_fs12.default.lstatSync(directory).isDirectory() && !import_node_fs12.default.lstatSync(directory).isSymbolicLink();
|
|
18823
18965
|
}
|
|
18824
18966
|
);
|
|
18825
18967
|
watchers = uniqueDirectories.flatMap(function watchParent(directory) {
|
|
18826
18968
|
try {
|
|
18827
|
-
const watcher =
|
|
18828
|
-
if (!fileName || !watched.some((target) =>
|
|
18969
|
+
const watcher = import_node_fs12.default.watch(directory, function reloadOnTargetFile(_eventType, fileName) {
|
|
18970
|
+
if (!fileName || !watched.some((target) => import_node_path12.default.basename(target) === fileName.toString() || import_node_path12.default.basename(import_node_path12.default.dirname(target)) === fileName.toString())) return;
|
|
18829
18971
|
if (timer) clearTimeout(timer);
|
|
18830
18972
|
timer = setTimeout(function reloadAfterDebounce() {
|
|
18831
18973
|
reload();
|
|
@@ -18854,16 +18996,16 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18854
18996
|
function readScopeValue(filePath, strict = false) {
|
|
18855
18997
|
if (strict) {
|
|
18856
18998
|
try {
|
|
18857
|
-
|
|
18999
|
+
import_node_fs13.default.lstatSync(filePath);
|
|
18858
19000
|
} catch (error) {
|
|
18859
19001
|
if (error.code === "ENOENT") return {};
|
|
18860
19002
|
throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
|
|
18861
19003
|
}
|
|
18862
19004
|
if (!isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
|
|
18863
|
-
} else if (!
|
|
19005
|
+
} else if (!import_node_fs13.default.existsSync(filePath) || !isSafeSettingsFile(filePath)) return {};
|
|
18864
19006
|
let content;
|
|
18865
19007
|
try {
|
|
18866
|
-
content =
|
|
19008
|
+
content = import_node_fs13.default.readFileSync(filePath, "utf8");
|
|
18867
19009
|
} catch {
|
|
18868
19010
|
if (strict) throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
|
|
18869
19011
|
return {};
|
|
@@ -18908,8 +19050,8 @@ function createNodeExternalPermissionProjector(options = {}) {
|
|
|
18908
19050
|
const resolved = (0, import_core12.resolveAutopilotSettings)([{ scope: "local", value: updated }]);
|
|
18909
19051
|
if (resolved.permissions.restricted === true) throw new Error("EXTERNAL_RULE_PERMISSIONS_UNSAFE");
|
|
18910
19052
|
if (next.length === 0 && Object.keys(permissions).length === 1) delete updated.permissions;
|
|
18911
|
-
if (
|
|
18912
|
-
|
|
19053
|
+
if (import_node_fs13.default.existsSync(filePath) && !isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
|
|
19054
|
+
import_node_fs13.default.mkdirSync(resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory ?? import_node_os6.default.homedir()).local.replace(/[/\\]settings\.local\.json$/u, ""), { recursive: true });
|
|
18913
19055
|
atomicReplace(filePath, `${JSON.stringify(updated, null, 2)}
|
|
18914
19056
|
`);
|
|
18915
19057
|
});
|
|
@@ -18928,16 +19070,16 @@ function createNodeExternalPermissionProjector(options = {}) {
|
|
|
18928
19070
|
}
|
|
18929
19071
|
|
|
18930
19072
|
// src/node/host-mutation-protection.ts
|
|
18931
|
-
var
|
|
19073
|
+
var import_node_path13 = __toESM(require("node:path"));
|
|
18932
19074
|
function createNodeHostMutationProtection(options) {
|
|
18933
|
-
const stateRoot =
|
|
18934
|
-
const trustFile =
|
|
19075
|
+
const stateRoot = import_node_path13.default.resolve(options.stateRoot);
|
|
19076
|
+
const trustFile = import_node_path13.default.join(resolveNodeTrustRoot(options), "trust.json");
|
|
18935
19077
|
const fixedTargets = [
|
|
18936
19078
|
{ path: getNodeFileMutationLockRoot(), scope: "directory" },
|
|
18937
19079
|
{ path: stateRoot, scope: "directory" },
|
|
18938
19080
|
{ path: canonicalizeNodePath(stateRoot), scope: "directory" },
|
|
18939
19081
|
{ path: trustFile, scope: "file" },
|
|
18940
|
-
...options.userSettingsPath ? [{ path:
|
|
19082
|
+
...options.userSettingsPath ? [{ path: import_node_path13.default.resolve(options.userSettingsPath), scope: "file" }] : []
|
|
18941
19083
|
];
|
|
18942
19084
|
return {
|
|
18943
19085
|
/** 权限配置路径复用真实User/Project/Local resolver,每次保留原路径与canonical判定。 */
|
|
@@ -18953,47 +19095,120 @@ function createNodeHostMutationProtection(options) {
|
|
|
18953
19095
|
}
|
|
18954
19096
|
|
|
18955
19097
|
// src/node/stores/node-checkpoint-store.ts
|
|
18956
|
-
var
|
|
19098
|
+
var import_node_fs14 = __toESM(require("node:fs"));
|
|
19099
|
+
var import_node_path14 = __toESM(require("node:path"));
|
|
19100
|
+
var import_node_readline = require("node:readline");
|
|
18957
19101
|
function createNodeCheckpointStore(options) {
|
|
18958
19102
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19103
|
+
const latestCache = /* @__PURE__ */ new Map();
|
|
19104
|
+
let cacheBytes = 0;
|
|
19105
|
+
function signature(target) {
|
|
19106
|
+
try {
|
|
19107
|
+
const stat = import_node_fs14.default.statSync(target, { bigint: true });
|
|
19108
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.birthtimeNs}`;
|
|
19109
|
+
} catch (error) {
|
|
19110
|
+
if (error.code === "ENOENT") return "missing";
|
|
19111
|
+
throw error;
|
|
19112
|
+
}
|
|
19113
|
+
}
|
|
19114
|
+
function invalidate(key2) {
|
|
19115
|
+
const previous = latestCache.get(key2);
|
|
19116
|
+
if (previous) cacheBytes -= previous.bytes;
|
|
19117
|
+
latestCache.delete(key2);
|
|
19118
|
+
}
|
|
19119
|
+
function invalidateSession(sessionId) {
|
|
19120
|
+
for (const key2 of latestCache.keys()) if (JSON.parse(key2)[0] === sessionId) invalidate(key2);
|
|
19121
|
+
}
|
|
18959
19122
|
function ensureDir() {
|
|
18960
19123
|
const state = ensureNodeStateRoot(paths.root);
|
|
18961
|
-
|
|
19124
|
+
import_node_fs14.default.mkdirSync(state.checkpointsDir, { recursive: true });
|
|
18962
19125
|
}
|
|
18963
19126
|
function filePath(sessionId) {
|
|
18964
19127
|
return safeFilePath(paths.checkpointsDir, sessionId, ".jsonl");
|
|
18965
19128
|
}
|
|
18966
|
-
function
|
|
18967
|
-
const
|
|
18968
|
-
|
|
18969
|
-
|
|
18970
|
-
|
|
18971
|
-
|
|
18972
|
-
|
|
18973
|
-
|
|
18974
|
-
|
|
19129
|
+
async function readCheckpoint(sessionId, turnId) {
|
|
19130
|
+
const target = filePath(sessionId);
|
|
19131
|
+
const key2 = JSON.stringify([sessionId, turnId ?? null]);
|
|
19132
|
+
try {
|
|
19133
|
+
const before2 = signature(target);
|
|
19134
|
+
const cached = latestCache.get(key2);
|
|
19135
|
+
if (cached?.signature === before2) {
|
|
19136
|
+
latestCache.delete(key2);
|
|
19137
|
+
latestCache.set(key2, cached);
|
|
19138
|
+
return structuredClone(cached.checkpoint);
|
|
19139
|
+
}
|
|
19140
|
+
invalidate(key2);
|
|
19141
|
+
let checkpoint = null;
|
|
19142
|
+
let bytes = 0;
|
|
19143
|
+
const corrupted = [];
|
|
19144
|
+
if (before2 !== "missing") {
|
|
19145
|
+
let failRead2 = function(error) {
|
|
19146
|
+
readError = error;
|
|
19147
|
+
lines.close();
|
|
19148
|
+
};
|
|
19149
|
+
var failRead = failRead2;
|
|
19150
|
+
const input = import_node_fs14.default.createReadStream(target, { encoding: "utf8", highWaterMark: 64 * 1024 });
|
|
19151
|
+
const lines = (0, import_node_readline.createInterface)({ input, crlfDelay: Infinity });
|
|
19152
|
+
let readError;
|
|
19153
|
+
input.on("error", failRead2);
|
|
19154
|
+
let lineNumber = 0;
|
|
19155
|
+
try {
|
|
19156
|
+
for await (const line of lines) {
|
|
19157
|
+
lineNumber++;
|
|
19158
|
+
if (!line) continue;
|
|
19159
|
+
try {
|
|
19160
|
+
const value = JSON.parse(line);
|
|
19161
|
+
if (!turnId || value?.turnId === turnId) {
|
|
19162
|
+
checkpoint = value;
|
|
19163
|
+
bytes = Buffer.byteLength(line, "utf8");
|
|
19164
|
+
}
|
|
19165
|
+
} catch {
|
|
19166
|
+
corrupted.push(lineNumber);
|
|
19167
|
+
}
|
|
19168
|
+
await new Promise(function yieldParsing(resolve) {
|
|
19169
|
+
setImmediate(resolve);
|
|
19170
|
+
});
|
|
19171
|
+
}
|
|
19172
|
+
if (readError) throw readError;
|
|
19173
|
+
} finally {
|
|
19174
|
+
lines.close();
|
|
19175
|
+
input.destroy();
|
|
19176
|
+
input.off("error", failRead2);
|
|
19177
|
+
}
|
|
19178
|
+
}
|
|
19179
|
+
if (corrupted.length) console.warn(`[DURABLE_JSONL_CORRUPTED] file=${import_node_path14.default.basename(target)} records=${corrupted.length} lines=${corrupted.join(",")}`);
|
|
19180
|
+
if (!corrupted.length && before2 === signature(target) && bytes <= 8 * 1024 * 1024) {
|
|
19181
|
+
while (latestCache.size >= 8 || cacheBytes + bytes > 8 * 1024 * 1024) invalidate(latestCache.keys().next().value);
|
|
19182
|
+
latestCache.set(key2, { signature: before2, checkpoint, bytes });
|
|
19183
|
+
cacheBytes += bytes;
|
|
19184
|
+
return structuredClone(checkpoint);
|
|
19185
|
+
}
|
|
19186
|
+
return checkpoint;
|
|
19187
|
+
} catch (error) {
|
|
19188
|
+
invalidate(key2);
|
|
19189
|
+
throw error;
|
|
18975
19190
|
}
|
|
18976
|
-
return null;
|
|
18977
19191
|
}
|
|
18978
19192
|
return {
|
|
18979
19193
|
async getLatest(sessionId) {
|
|
18980
19194
|
ensureDir();
|
|
18981
|
-
return withFileLock(filePath(sessionId), () =>
|
|
19195
|
+
return withFileLock(filePath(sessionId), () => readCheckpoint(sessionId));
|
|
18982
19196
|
},
|
|
18983
19197
|
async getByTurn(sessionId, turnId) {
|
|
18984
19198
|
ensureDir();
|
|
18985
|
-
return withFileLock(filePath(sessionId), () =>
|
|
19199
|
+
return withFileLock(filePath(sessionId), () => readCheckpoint(sessionId, turnId));
|
|
18986
19200
|
},
|
|
18987
19201
|
async save(sessionId, checkpoint) {
|
|
18988
19202
|
ensureDir();
|
|
18989
19203
|
await withFileLock(filePath(sessionId), () => {
|
|
19204
|
+
invalidateSession(sessionId);
|
|
18990
19205
|
appendJsonLine(filePath(sessionId), JSON.stringify(checkpoint));
|
|
18991
19206
|
});
|
|
18992
19207
|
},
|
|
18993
19208
|
async recoverStale(sessionId, now, staleAfterMs) {
|
|
18994
19209
|
ensureDir();
|
|
18995
|
-
return withFileLock(filePath(sessionId), ()
|
|
18996
|
-
const latest =
|
|
19210
|
+
return withFileLock(filePath(sessionId), async function recover() {
|
|
19211
|
+
const latest = await readCheckpoint(sessionId);
|
|
18997
19212
|
if (!latest) return null;
|
|
18998
19213
|
if (latest.status !== "running" || !latest.lease || now - latest.lease.heartbeatAt <= staleAfterMs) return latest;
|
|
18999
19214
|
const recovered = {
|
|
@@ -19001,6 +19216,7 @@ function createNodeCheckpointStore(options) {
|
|
|
19001
19216
|
status: "interrupted_recoverable",
|
|
19002
19217
|
interruptionReason: "stale_lease"
|
|
19003
19218
|
};
|
|
19219
|
+
invalidateSession(sessionId);
|
|
19004
19220
|
appendJsonLine(filePath(sessionId), JSON.stringify(recovered));
|
|
19005
19221
|
return recovered;
|
|
19006
19222
|
});
|
|
@@ -19009,7 +19225,8 @@ function createNodeCheckpointStore(options) {
|
|
|
19009
19225
|
ensureDir();
|
|
19010
19226
|
const target = filePath(sessionId);
|
|
19011
19227
|
await withFileLock(target, () => {
|
|
19012
|
-
|
|
19228
|
+
invalidateSession(sessionId);
|
|
19229
|
+
if (import_node_fs14.default.existsSync(target)) import_node_fs14.default.unlinkSync(target);
|
|
19013
19230
|
});
|
|
19014
19231
|
}
|
|
19015
19232
|
};
|
|
@@ -19025,13 +19242,14 @@ function createNodeEventSink(_options) {
|
|
|
19025
19242
|
}
|
|
19026
19243
|
|
|
19027
19244
|
// src/node/stores/node-input-inbox.ts
|
|
19028
|
-
var
|
|
19029
|
-
var
|
|
19245
|
+
var import_node_crypto8 = require("node:crypto");
|
|
19246
|
+
var import_node_fs15 = __toESM(require("node:fs"));
|
|
19247
|
+
var import_core14 = require("@autopilot-agent/core");
|
|
19030
19248
|
function createNodeInputInbox(options) {
|
|
19031
19249
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19032
19250
|
function ensureDir() {
|
|
19033
19251
|
const state = ensureNodeStateRoot(paths.root);
|
|
19034
|
-
|
|
19252
|
+
import_node_fs15.default.mkdirSync(state.inboxDir, { recursive: true });
|
|
19035
19253
|
}
|
|
19036
19254
|
function filePath(sessionId) {
|
|
19037
19255
|
return safeFilePath(paths.inboxDir, sessionId, ".jsonl");
|
|
@@ -19054,10 +19272,13 @@ function createNodeInputInbox(options) {
|
|
|
19054
19272
|
const inputs = readInbox(input.sessionId);
|
|
19055
19273
|
if (input.clientMessageId) {
|
|
19056
19274
|
const existing = inputs.find((candidate) => candidate.clientMessageId === input.clientMessageId);
|
|
19057
|
-
if (existing)
|
|
19275
|
+
if (existing) {
|
|
19276
|
+
if (existing.content !== input.content || (0, import_core14.inboxOriginKey)(existing.origin) !== (0, import_core14.inboxOriginKey)(input.origin)) throw new Error("INBOX_INPUT_CONFLICT");
|
|
19277
|
+
return existing;
|
|
19278
|
+
}
|
|
19058
19279
|
}
|
|
19059
19280
|
const inboxInput = {
|
|
19060
|
-
inputId: (0,
|
|
19281
|
+
inputId: (0, import_node_crypto8.randomUUID)(),
|
|
19061
19282
|
sessionId: input.sessionId,
|
|
19062
19283
|
turnId: input.turnId,
|
|
19063
19284
|
delivery: input.delivery,
|
|
@@ -19066,6 +19287,7 @@ function createNodeInputInbox(options) {
|
|
|
19066
19287
|
clientMessageId: input.clientMessageId,
|
|
19067
19288
|
attachments: input.attachments ?? [],
|
|
19068
19289
|
selectedSkills: input.selectedSkills ?? [],
|
|
19290
|
+
origin: input.origin,
|
|
19069
19291
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
19070
19292
|
};
|
|
19071
19293
|
inputs.push(inboxInput);
|
|
@@ -19118,7 +19340,7 @@ function createNodeInputInbox(options) {
|
|
|
19118
19340
|
},
|
|
19119
19341
|
async cancel(inputId) {
|
|
19120
19342
|
ensureDir();
|
|
19121
|
-
const files =
|
|
19343
|
+
const files = import_node_fs15.default.readdirSync(paths.inboxDir).filter((file) => file.endsWith(".jsonl"));
|
|
19122
19344
|
for (const file of files) {
|
|
19123
19345
|
const sessionId = file.slice(0, -6);
|
|
19124
19346
|
const cancelled = await withFileLock(filePath(sessionId), () => {
|
|
@@ -19137,7 +19359,7 @@ function createNodeInputInbox(options) {
|
|
|
19137
19359
|
ensureDir();
|
|
19138
19360
|
const target = filePath(sessionId);
|
|
19139
19361
|
await withFileLock(target, () => {
|
|
19140
|
-
if (
|
|
19362
|
+
if (import_node_fs15.default.existsSync(target)) import_node_fs15.default.unlinkSync(target);
|
|
19141
19363
|
});
|
|
19142
19364
|
},
|
|
19143
19365
|
async waitForInput(_query) {
|
|
@@ -19146,21 +19368,21 @@ function createNodeInputInbox(options) {
|
|
|
19146
19368
|
}
|
|
19147
19369
|
|
|
19148
19370
|
// src/node/stores/node-project-store.ts
|
|
19149
|
-
var
|
|
19150
|
-
var
|
|
19371
|
+
var import_node_crypto9 = require("node:crypto");
|
|
19372
|
+
var import_node_fs16 = __toESM(require("node:fs"));
|
|
19151
19373
|
function createNodeProjectStore(options) {
|
|
19152
19374
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19153
19375
|
function ensureDir() {
|
|
19154
19376
|
const state = ensureNodeStateRoot(paths.root);
|
|
19155
|
-
|
|
19377
|
+
import_node_fs16.default.mkdirSync(state.projectsDir, { recursive: true });
|
|
19156
19378
|
}
|
|
19157
19379
|
function filePath(projectId) {
|
|
19158
19380
|
return safeFilePath(paths.projectsDir, projectId, ".json");
|
|
19159
19381
|
}
|
|
19160
19382
|
return {
|
|
19161
19383
|
async get(id) {
|
|
19162
|
-
|
|
19163
|
-
return
|
|
19384
|
+
assertNodeStateSchema(paths.root);
|
|
19385
|
+
return readJsonFile(filePath(id));
|
|
19164
19386
|
},
|
|
19165
19387
|
async save(project) {
|
|
19166
19388
|
ensureDir();
|
|
@@ -19169,9 +19391,10 @@ function createNodeProjectStore(options) {
|
|
|
19169
19391
|
});
|
|
19170
19392
|
},
|
|
19171
19393
|
async list() {
|
|
19172
|
-
|
|
19394
|
+
assertNodeStateSchema(paths.root);
|
|
19173
19395
|
const projects = [];
|
|
19174
|
-
|
|
19396
|
+
if (!import_node_fs16.default.existsSync(paths.projectsDir)) return projects;
|
|
19397
|
+
for (const file of import_node_fs16.default.readdirSync(paths.projectsDir).filter((entry) => entry.endsWith(".json"))) {
|
|
19175
19398
|
const project = readJsonFile(filePath(file.slice(0, -5)));
|
|
19176
19399
|
if (project) projects.push(project);
|
|
19177
19400
|
}
|
|
@@ -19180,7 +19403,7 @@ function createNodeProjectStore(options) {
|
|
|
19180
19403
|
async create(input) {
|
|
19181
19404
|
const now = Date.now();
|
|
19182
19405
|
const project = {
|
|
19183
|
-
id: (0,
|
|
19406
|
+
id: (0, import_node_crypto9.randomUUID)(),
|
|
19184
19407
|
name: input.name,
|
|
19185
19408
|
workspaceRoot: input.workspaceRoot,
|
|
19186
19409
|
description: input.description,
|
|
@@ -19196,40 +19419,42 @@ function createNodeProjectStore(options) {
|
|
|
19196
19419
|
ensureDir();
|
|
19197
19420
|
const target = filePath(id);
|
|
19198
19421
|
return withFileLock(target, () => {
|
|
19199
|
-
if (!
|
|
19200
|
-
|
|
19422
|
+
if (!import_node_fs16.default.existsSync(target)) return false;
|
|
19423
|
+
import_node_fs16.default.unlinkSync(target);
|
|
19201
19424
|
return true;
|
|
19202
19425
|
});
|
|
19203
19426
|
}
|
|
19204
19427
|
};
|
|
19205
19428
|
}
|
|
19206
19429
|
|
|
19207
|
-
// src/node/stores/node-
|
|
19208
|
-
var
|
|
19430
|
+
// src/node/stores/node-thread-store.ts
|
|
19431
|
+
var import_core15 = require("@autopilot-agent/core");
|
|
19432
|
+
var import_node_fs18 = __toESM(require("node:fs"));
|
|
19433
|
+
var import_node_path16 = __toESM(require("node:path"));
|
|
19209
19434
|
|
|
19210
19435
|
// src/node/chat-state.ts
|
|
19211
|
-
var
|
|
19436
|
+
var import_node_fs17 = __toESM(require("node:fs"));
|
|
19212
19437
|
var import_node_os7 = __toESM(require("node:os"));
|
|
19213
|
-
var
|
|
19438
|
+
var import_node_path15 = __toESM(require("node:path"));
|
|
19214
19439
|
function resolveNodeChatStatePaths(options = {}) {
|
|
19215
19440
|
try {
|
|
19216
|
-
if (options.globalStateRoot !== void 0 && !
|
|
19441
|
+
if (options.globalStateRoot !== void 0 && !import_node_path15.default.isAbsolute(options.globalStateRoot)) throw new NodeChatError("CHAT_STATE_ROOT_INVALID");
|
|
19217
19442
|
const globalRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: import_node_os7.default.homedir() });
|
|
19218
|
-
const root =
|
|
19219
|
-
return { root, stateRoot:
|
|
19443
|
+
const root = import_node_path15.default.join(globalRoot, "chat");
|
|
19444
|
+
return { root, stateRoot: import_node_path15.default.join(root, "state"), attachmentsRoot: import_node_path15.default.join(root, "attachments"), knowledgeRoot: import_node_path15.default.join(root, "knowledge") };
|
|
19220
19445
|
} catch (error) {
|
|
19221
19446
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19222
19447
|
}
|
|
19223
19448
|
}
|
|
19224
19449
|
function assertSafeNodePath(root, target) {
|
|
19225
19450
|
try {
|
|
19226
|
-
const relative =
|
|
19227
|
-
if (relative === ".." || relative.startsWith(`..${
|
|
19451
|
+
const relative = import_node_path15.default.relative(root, target);
|
|
19452
|
+
if (relative === ".." || relative.startsWith(`..${import_node_path15.default.sep}`) || import_node_path15.default.isAbsolute(relative)) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19228
19453
|
let current = root;
|
|
19229
|
-
for (const segment of ["", ...relative.split(
|
|
19230
|
-
if (segment) current =
|
|
19454
|
+
for (const segment of ["", ...relative.split(import_node_path15.default.sep).filter(Boolean)]) {
|
|
19455
|
+
if (segment) current = import_node_path15.default.join(current, segment);
|
|
19231
19456
|
try {
|
|
19232
|
-
const entry =
|
|
19457
|
+
const entry = import_node_fs17.default.lstatSync(current);
|
|
19233
19458
|
if (entry.isSymbolicLink() || current !== target && !entry.isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19234
19459
|
} catch (error) {
|
|
19235
19460
|
if (error.code !== "ENOENT") throw error;
|
|
@@ -19243,19 +19468,396 @@ function assertSafeNodePath(root, target) {
|
|
|
19243
19468
|
function ensureChatDirectory(root, target) {
|
|
19244
19469
|
try {
|
|
19245
19470
|
assertSafeNodePath(root, target);
|
|
19246
|
-
|
|
19471
|
+
import_node_fs17.default.mkdirSync(target, { recursive: true, mode: 448 });
|
|
19247
19472
|
assertSafeNodePath(root, target);
|
|
19248
|
-
if (!
|
|
19473
|
+
if (!import_node_fs17.default.lstatSync(target).isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19249
19474
|
} catch (error) {
|
|
19250
19475
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19251
19476
|
}
|
|
19252
19477
|
}
|
|
19253
19478
|
function initializeNodeChatDirectories(paths) {
|
|
19254
|
-
ensureChatDirectory(
|
|
19479
|
+
ensureChatDirectory(import_node_path15.default.dirname(paths.root), paths.root);
|
|
19255
19480
|
ensureChatDirectory(paths.root, paths.stateRoot);
|
|
19256
19481
|
ensureChatDirectory(paths.root, paths.attachmentsRoot);
|
|
19257
19482
|
}
|
|
19258
19483
|
|
|
19484
|
+
// src/node/stores/node-thread-store.ts
|
|
19485
|
+
function createNodeThreadStore(stateRoot) {
|
|
19486
|
+
const groups = import_node_path16.default.join(stateRoot, "threads", "groups");
|
|
19487
|
+
const controlCache = /* @__PURE__ */ new Map();
|
|
19488
|
+
let controlCacheBytes = 0;
|
|
19489
|
+
function controlSignature(target) {
|
|
19490
|
+
const stat = import_node_fs18.default.statSync(target, { bigint: true });
|
|
19491
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.birthtimeNs}`;
|
|
19492
|
+
}
|
|
19493
|
+
function forgetControl(target) {
|
|
19494
|
+
controlCacheBytes -= controlCache.get(target)?.bytes ?? 0;
|
|
19495
|
+
controlCache.delete(target);
|
|
19496
|
+
}
|
|
19497
|
+
function assertTargetRoot() {
|
|
19498
|
+
const manifest = import_node_path16.default.join(stateRoot, "schema.json");
|
|
19499
|
+
let value;
|
|
19500
|
+
try {
|
|
19501
|
+
if (import_node_fs18.default.lstatSync(stateRoot).isSymbolicLink() || import_node_fs18.default.lstatSync(manifest).isSymbolicLink()) throw new Error("unsafe");
|
|
19502
|
+
value = JSON.parse(import_node_fs18.default.readFileSync(manifest, "utf8"));
|
|
19503
|
+
} catch {
|
|
19504
|
+
throw new Error("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
19505
|
+
}
|
|
19506
|
+
if (!value || typeof value !== "object" || value.schemaVersion !== 8) throw new Error("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
19507
|
+
}
|
|
19508
|
+
function controlPath(groupId) {
|
|
19509
|
+
const target = import_node_path16.default.join(safeFilePath(groups, groupId, ""), "control.json");
|
|
19510
|
+
assertSafeNodePath(stateRoot, target);
|
|
19511
|
+
return target;
|
|
19512
|
+
}
|
|
19513
|
+
function assertInteractionControls(control) {
|
|
19514
|
+
if (control.controls !== void 0 && !Array.isArray(control.controls)) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19515
|
+
for (const intent of control.controls ?? []) {
|
|
19516
|
+
if (intent?.kind !== "continue_interaction") continue;
|
|
19517
|
+
if (intent.failureDiagnostic !== void 0 && (!(0, import_core15.sanitizeContinuationFailure)(intent.failureDiagnostic) || Object.keys(intent.failureDiagnostic).some(function invalid(key2) {
|
|
19518
|
+
return !Object.prototype.hasOwnProperty.call((0, import_core15.sanitizeContinuationFailure)(intent.failureDiagnostic), key2) || intent.failureDiagnostic[key2] !== (0, import_core15.sanitizeContinuationFailure)(intent.failureDiagnostic)[key2];
|
|
19519
|
+
}))) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19520
|
+
const ids = [intent.controlId, intent.threadId, intent.expectedTurnId, intent.approvalId ?? intent.requestId];
|
|
19521
|
+
if (ids.some(function invalid(id) {
|
|
19522
|
+
return typeof id !== "string" || !id || id.length > 200 || /[\\/\x00-\x1f]/u.test(id);
|
|
19523
|
+
}) || intent.approvalId !== void 0 && typeof intent.approvalId !== "string" || intent.requestId !== void 0 && typeof intent.requestId !== "string" || Boolean(intent.approvalId) === Boolean(intent.requestId) || !["pending", "claimed", "executing", "completed", "failed"].includes(intent.status) || typeof intent.checkpointDigest !== "string" || !/^[a-f0-9]{64}$/u.test(intent.checkpointDigest) || intent.pauseSeq !== void 0 && (!Number.isSafeInteger(intent.pauseSeq) || intent.pauseSeq < 0) || !Number.isFinite(intent.createdAt) || !Number.isFinite(intent.updatedAt) || (intent.status === "claimed" || intent.status === "executing") && (typeof intent.ownerId !== "string" || !intent.ownerId || intent.ownerId.length > 500) || intent.failureCode !== void 0 && !["BOUNDARY_CHANGED", "CONTINUE_FAILED"].includes(intent.failureCode)) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19524
|
+
}
|
|
19525
|
+
}
|
|
19526
|
+
function read(groupId) {
|
|
19527
|
+
const target = controlPath(groupId);
|
|
19528
|
+
try {
|
|
19529
|
+
const before2 = controlSignature(target);
|
|
19530
|
+
const cached = controlCache.get(target);
|
|
19531
|
+
if (cached?.signature === before2) {
|
|
19532
|
+
controlCache.delete(target);
|
|
19533
|
+
controlCache.set(target, cached);
|
|
19534
|
+
return structuredClone(cached.value);
|
|
19535
|
+
}
|
|
19536
|
+
forgetControl(target);
|
|
19537
|
+
const text = import_node_fs18.default.readFileSync(target, "utf8");
|
|
19538
|
+
let value;
|
|
19539
|
+
try {
|
|
19540
|
+
value = JSON.parse(text);
|
|
19541
|
+
} catch {
|
|
19542
|
+
throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19543
|
+
}
|
|
19544
|
+
if (!value || value.group?.groupId !== groupId || !Number.isSafeInteger(value.revision) || value.revision < 0) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19545
|
+
assertInteractionControls(value);
|
|
19546
|
+
const bytes = Buffer.byteLength(text, "utf8");
|
|
19547
|
+
if (bytes <= 8 * 1024 * 1024 && before2 === controlSignature(target)) {
|
|
19548
|
+
while (controlCache.size >= 128 || controlCacheBytes + bytes > 8 * 1024 * 1024) forgetControl(controlCache.keys().next().value);
|
|
19549
|
+
controlCache.set(target, { signature: before2, value, bytes });
|
|
19550
|
+
controlCacheBytes += bytes;
|
|
19551
|
+
return structuredClone(value);
|
|
19552
|
+
}
|
|
19553
|
+
return value;
|
|
19554
|
+
} catch (error) {
|
|
19555
|
+
forgetControl(target);
|
|
19556
|
+
if (error.code === "ENOENT") return null;
|
|
19557
|
+
throw error;
|
|
19558
|
+
}
|
|
19559
|
+
}
|
|
19560
|
+
function messagePath(groupId, threadId, seq2) {
|
|
19561
|
+
if (!Number.isSafeInteger(seq2) || seq2 < 1) throw new Error("THREAD_CURSOR_INVALID");
|
|
19562
|
+
const dir = import_node_path16.default.join(safeFilePath(groups, groupId, ""), "messages");
|
|
19563
|
+
const threadDir = safeFilePath(dir, threadId, "");
|
|
19564
|
+
const target = safeFilePath(threadDir, String(seq2), ".json");
|
|
19565
|
+
assertSafeNodePath(stateRoot, target);
|
|
19566
|
+
return target;
|
|
19567
|
+
}
|
|
19568
|
+
function readMessage(groupId, threadId, seq2) {
|
|
19569
|
+
let value;
|
|
19570
|
+
try {
|
|
19571
|
+
value = JSON.parse(import_node_fs18.default.readFileSync(messagePath(groupId, threadId, seq2), "utf8"));
|
|
19572
|
+
} catch (error) {
|
|
19573
|
+
if (error.code === "ENOENT") return null;
|
|
19574
|
+
throw new Error("THREAD_MESSAGE_CORRUPTED");
|
|
19575
|
+
}
|
|
19576
|
+
if (!value || value.groupId !== groupId || value.toThreadId !== threadId || value.deliverySeq !== seq2) throw new Error("THREAD_MESSAGE_CORRUPTED");
|
|
19577
|
+
return value;
|
|
19578
|
+
}
|
|
19579
|
+
function eventPath(groupId, seq2) {
|
|
19580
|
+
if (!Number.isSafeInteger(seq2) || seq2 < 1) throw new Error("THREAD_CURSOR_INVALID");
|
|
19581
|
+
const dir = import_node_path16.default.join(safeFilePath(groups, groupId, ""), "events");
|
|
19582
|
+
const target = safeFilePath(dir, String(seq2), ".json");
|
|
19583
|
+
assertSafeNodePath(stateRoot, target);
|
|
19584
|
+
return target;
|
|
19585
|
+
}
|
|
19586
|
+
function readEvent(groupId, seq2) {
|
|
19587
|
+
let value;
|
|
19588
|
+
try {
|
|
19589
|
+
value = JSON.parse(import_node_fs18.default.readFileSync(eventPath(groupId, seq2), "utf8"));
|
|
19590
|
+
} catch (error) {
|
|
19591
|
+
if (error.code === "ENOENT") return null;
|
|
19592
|
+
throw new Error("THREAD_EVENT_CORRUPTED");
|
|
19593
|
+
}
|
|
19594
|
+
if (!value || value.groupId !== groupId || value.groupSeq !== seq2) throw new Error("THREAD_EVENT_CORRUPTED");
|
|
19595
|
+
return value;
|
|
19596
|
+
}
|
|
19597
|
+
function readRequest(id) {
|
|
19598
|
+
const target = safeFilePath(import_node_path16.default.join(stateRoot, "threads", "requests"), id, ".json");
|
|
19599
|
+
assertSafeNodePath(stateRoot, target);
|
|
19600
|
+
try {
|
|
19601
|
+
return JSON.parse(import_node_fs18.default.readFileSync(target, "utf8"));
|
|
19602
|
+
} catch (error) {
|
|
19603
|
+
if (error.code === "ENOENT") return null;
|
|
19604
|
+
throw new Error("THREAD_REQUEST_CORRUPTED");
|
|
19605
|
+
}
|
|
19606
|
+
}
|
|
19607
|
+
return {
|
|
19608
|
+
/** 只读检查,和预留中的最终检查共同处理并发。 */
|
|
19609
|
+
async verifyRequest(id, groupId, payloadDigest) {
|
|
19610
|
+
assertTargetRoot();
|
|
19611
|
+
const prior = readRequest(id);
|
|
19612
|
+
if (prior && (prior.groupId !== groupId || prior.payloadDigest !== payloadDigest)) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19613
|
+
},
|
|
19614
|
+
/** 请求身份独立于组,跨进程锁内持久预留,冲突不得重绑。 */
|
|
19615
|
+
async reserveRequest(id, groupId, payloadDigest) {
|
|
19616
|
+
assertTargetRoot();
|
|
19617
|
+
const target = safeFilePath(import_node_path16.default.join(stateRoot, "threads", "requests"), id, ".json");
|
|
19618
|
+
assertSafeNodePath(stateRoot, target);
|
|
19619
|
+
await withFileLock(target, function reserveLocked() {
|
|
19620
|
+
if (import_node_fs18.default.existsSync(target)) {
|
|
19621
|
+
let prior;
|
|
19622
|
+
try {
|
|
19623
|
+
prior = JSON.parse(import_node_fs18.default.readFileSync(target, "utf8"));
|
|
19624
|
+
} catch {
|
|
19625
|
+
throw new Error("THREAD_REQUEST_CORRUPTED");
|
|
19626
|
+
}
|
|
19627
|
+
if (prior.groupId !== groupId || prior.payloadDigest !== payloadDigest) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19628
|
+
return;
|
|
19629
|
+
}
|
|
19630
|
+
atomicReplace(target, JSON.stringify({ groupId, payloadDigest }));
|
|
19631
|
+
}, { requireExitedOwner: true });
|
|
19632
|
+
},
|
|
19633
|
+
/** 同序号重放幂等,不同事件冲突。 */
|
|
19634
|
+
async writeEvent(event) {
|
|
19635
|
+
assertTargetRoot();
|
|
19636
|
+
const target = eventPath(event.groupId, event.groupSeq);
|
|
19637
|
+
const serialized = JSON.stringify(event);
|
|
19638
|
+
if (Buffer.byteLength(serialized, "utf8") > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
19639
|
+
await withFileLock(target, function writeEventLocked() {
|
|
19640
|
+
const previous = readEvent(event.groupId, event.groupSeq);
|
|
19641
|
+
if (previous && JSON.stringify(previous) !== serialized) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19642
|
+
if (!previous) atomicReplace(target, serialized);
|
|
19643
|
+
}, { requireExitedOwner: true });
|
|
19644
|
+
},
|
|
19645
|
+
/** 查询不创建锁或目录。 */
|
|
19646
|
+
async readEvent(groupId, seq2) {
|
|
19647
|
+
assertTargetRoot();
|
|
19648
|
+
return readEvent(groupId, seq2);
|
|
19649
|
+
},
|
|
19650
|
+
/** 短期 Session 锁只覆盖元数据变更与删除,不覆盖 Turn 执行。 */
|
|
19651
|
+
async withSessionLock(threadId, operation) {
|
|
19652
|
+
assertTargetRoot();
|
|
19653
|
+
const target = safeFilePath(import_node_path16.default.join(stateRoot, "threads", "session-locks"), threadId, "");
|
|
19654
|
+
assertSafeNodePath(stateRoot, target);
|
|
19655
|
+
return withFileLock(target, operation, { requireExitedOwner: true });
|
|
19656
|
+
},
|
|
19657
|
+
/** 检查全部组控制记录;损坏记录明确报错,不遗漏受管引用。 */
|
|
19658
|
+
async hasMembership(threadId) {
|
|
19659
|
+
assertTargetRoot();
|
|
19660
|
+
if (!import_node_fs18.default.existsSync(groups)) return false;
|
|
19661
|
+
for (const groupId of import_node_fs18.default.readdirSync(groups)) {
|
|
19662
|
+
const control = read(groupId);
|
|
19663
|
+
if (!control) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19664
|
+
if (control.members.some(function member(item) {
|
|
19665
|
+
return item.threadId === threadId;
|
|
19666
|
+
}) || control.creates.some(function intent(item) {
|
|
19667
|
+
return item.threadId === threadId || item.parentThreadId === threadId;
|
|
19668
|
+
})) return true;
|
|
19669
|
+
}
|
|
19670
|
+
return false;
|
|
19671
|
+
},
|
|
19672
|
+
/** 目标格式与稳定身份校验后按消息锁幂等写入。 */
|
|
19673
|
+
async writeMessage(message) {
|
|
19674
|
+
assertTargetRoot();
|
|
19675
|
+
const target = messagePath(message.groupId, message.toThreadId, message.deliverySeq);
|
|
19676
|
+
const serialized = JSON.stringify(message);
|
|
19677
|
+
if (Buffer.byteLength(serialized, "utf8") > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
19678
|
+
await withFileLock(target, function writeLocked() {
|
|
19679
|
+
const prior = readMessage(message.groupId, message.toThreadId, message.deliverySeq);
|
|
19680
|
+
if (prior && JSON.stringify(prior) !== serialized) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19681
|
+
if (!prior) atomicReplace(target, serialized);
|
|
19682
|
+
}, { requireExitedOwner: true });
|
|
19683
|
+
},
|
|
19684
|
+
/** 按序号读取,不创建目录或锁文件。 */
|
|
19685
|
+
async readMessage(groupId, threadId, seq2) {
|
|
19686
|
+
assertTargetRoot();
|
|
19687
|
+
return readMessage(groupId, threadId, seq2);
|
|
19688
|
+
},
|
|
19689
|
+
/** 查询不触发状态根初始化或执行恢复。 */
|
|
19690
|
+
async readControl(groupId) {
|
|
19691
|
+
assertTargetRoot();
|
|
19692
|
+
return read(groupId);
|
|
19693
|
+
},
|
|
19694
|
+
/** 只列出已有 control.json 的组,半初始化目录不冒充可执行目标。 */
|
|
19695
|
+
async listGroups() {
|
|
19696
|
+
assertTargetRoot();
|
|
19697
|
+
if (!import_node_fs18.default.existsSync(groups)) return [];
|
|
19698
|
+
return import_node_fs18.default.readdirSync(groups).filter(function hasControl(name) {
|
|
19699
|
+
return import_node_fs18.default.existsSync(controlPath(name));
|
|
19700
|
+
}).sort();
|
|
19701
|
+
},
|
|
19702
|
+
/**
|
|
19703
|
+
* 本进程内的文件变化唤醒;watchFile 只做 stat 轮询,不创建锁或文件。
|
|
19704
|
+
* 跨进程写入同样会改变 mtime,因此订阅不依赖同一进程的 CAS 回调。
|
|
19705
|
+
*/
|
|
19706
|
+
subscribe(groupId, listener) {
|
|
19707
|
+
const target = controlPath(groupId);
|
|
19708
|
+
const onChange = function changed() {
|
|
19709
|
+
try {
|
|
19710
|
+
listener();
|
|
19711
|
+
} catch {
|
|
19712
|
+
}
|
|
19713
|
+
};
|
|
19714
|
+
import_node_fs18.default.watchFile(target, { interval: 200, persistent: false }, onChange);
|
|
19715
|
+
return () => {
|
|
19716
|
+
import_node_fs18.default.unwatchFile(target, onChange);
|
|
19717
|
+
};
|
|
19718
|
+
},
|
|
19719
|
+
/** 加锁后重新读取和校验版本,原子替换而不跨 Session 持锁执行。 */
|
|
19720
|
+
async compareAndSetControl(groupId, expectedRevision, value) {
|
|
19721
|
+
assertTargetRoot();
|
|
19722
|
+
if (value.group.groupId !== groupId || value.revision !== (expectedRevision === null ? 0 : expectedRevision + 1)) throw new Error("THREAD_CONTROL_INVALID");
|
|
19723
|
+
assertInteractionControls(value);
|
|
19724
|
+
const serialized = JSON.stringify(value);
|
|
19725
|
+
if (Buffer.byteLength(serialized, "utf8") > 4 * 1024 * 1024) throw new Error("THREAD_STORAGE_FULL");
|
|
19726
|
+
return withFileLock(controlPath(groupId), function updateUnderLock() {
|
|
19727
|
+
const current = read(groupId);
|
|
19728
|
+
if (expectedRevision === null ? current !== null : current?.revision !== expectedRevision) return false;
|
|
19729
|
+
atomicReplace(controlPath(groupId), serialized);
|
|
19730
|
+
return true;
|
|
19731
|
+
}, { requireExitedOwner: true });
|
|
19732
|
+
}
|
|
19733
|
+
};
|
|
19734
|
+
}
|
|
19735
|
+
|
|
19736
|
+
// src/node/stores/node-session-store.ts
|
|
19737
|
+
var import_node_fs20 = __toESM(require("node:fs"));
|
|
19738
|
+
|
|
19739
|
+
// src/node/stores/session-directory.ts
|
|
19740
|
+
var import_node_fs19 = __toESM(require("node:fs"));
|
|
19741
|
+
var DIRECTORY_FIELDS = /* @__PURE__ */ new Set(["id", "title", "productMode", "projectId", "chatRetrievalMode", "createdAt", "updatedAt", "status", "activeTurnId"]);
|
|
19742
|
+
async function readSessionDirectoryRecord(filePath, id) {
|
|
19743
|
+
const fields = {};
|
|
19744
|
+
const stack = [];
|
|
19745
|
+
let root = false;
|
|
19746
|
+
let finished = false;
|
|
19747
|
+
let token;
|
|
19748
|
+
let text = "";
|
|
19749
|
+
let capture = false;
|
|
19750
|
+
let keyToken = false;
|
|
19751
|
+
let target;
|
|
19752
|
+
let escaped = false;
|
|
19753
|
+
let unicode = 0;
|
|
19754
|
+
function invalid() {
|
|
19755
|
+
throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
19756
|
+
}
|
|
19757
|
+
function beginValue() {
|
|
19758
|
+
if (!stack.length) {
|
|
19759
|
+
if (root) invalid();
|
|
19760
|
+
root = true;
|
|
19761
|
+
return void 0;
|
|
19762
|
+
}
|
|
19763
|
+
const frame = stack[stack.length - 1];
|
|
19764
|
+
if (frame.expect !== "value" && frame.expect !== "valueOrEnd") invalid();
|
|
19765
|
+
frame.expect = "commaOrEnd";
|
|
19766
|
+
return stack.length === 1 && frame.kind === "object" && frame.key && DIRECTORY_FIELDS.has(frame.key) ? frame.key : void 0;
|
|
19767
|
+
}
|
|
19768
|
+
function finishToken() {
|
|
19769
|
+
if (keyToken) {
|
|
19770
|
+
const frame = stack[stack.length - 1];
|
|
19771
|
+
frame.key = stack.length === 1 ? JSON.parse(text) : void 0;
|
|
19772
|
+
frame.expect = "colon";
|
|
19773
|
+
} else if (target) fields[target] = JSON.parse(text);
|
|
19774
|
+
token = void 0;
|
|
19775
|
+
text = "";
|
|
19776
|
+
target = void 0;
|
|
19777
|
+
}
|
|
19778
|
+
const stream = import_node_fs19.default.createReadStream(filePath, { encoding: "utf8", highWaterMark: 16 * 1024 });
|
|
19779
|
+
for await (const chunk of stream) {
|
|
19780
|
+
for (const character of chunk) {
|
|
19781
|
+
if (token === "string") {
|
|
19782
|
+
if (capture) text += character;
|
|
19783
|
+
if (unicode) {
|
|
19784
|
+
if (!/[0-9a-f]/iu.test(character)) invalid();
|
|
19785
|
+
unicode--;
|
|
19786
|
+
continue;
|
|
19787
|
+
}
|
|
19788
|
+
if (escaped) {
|
|
19789
|
+
if (character === "u") unicode = 4;
|
|
19790
|
+
else if (!/["\\/bfnrt]/u.test(character)) invalid();
|
|
19791
|
+
escaped = false;
|
|
19792
|
+
continue;
|
|
19793
|
+
}
|
|
19794
|
+
if (character === "\\") {
|
|
19795
|
+
escaped = true;
|
|
19796
|
+
continue;
|
|
19797
|
+
}
|
|
19798
|
+
if (character === '"') {
|
|
19799
|
+
finishToken();
|
|
19800
|
+
continue;
|
|
19801
|
+
}
|
|
19802
|
+
if (character.charCodeAt(0) < 32) invalid();
|
|
19803
|
+
continue;
|
|
19804
|
+
}
|
|
19805
|
+
if (token === "primitive") {
|
|
19806
|
+
if (!/[ \t\r\n,}\]]/u.test(character)) {
|
|
19807
|
+
text += character;
|
|
19808
|
+
if (text.length > 128) invalid();
|
|
19809
|
+
continue;
|
|
19810
|
+
}
|
|
19811
|
+
if (!/^(?:null|true|false|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)$/u.test(text)) invalid();
|
|
19812
|
+
finishToken();
|
|
19813
|
+
}
|
|
19814
|
+
if (/[ \t\r\n]/u.test(character)) continue;
|
|
19815
|
+
if (finished) invalid();
|
|
19816
|
+
const frame = stack[stack.length - 1];
|
|
19817
|
+
if (character === '"') {
|
|
19818
|
+
keyToken = frame?.kind === "object" && (frame.expect === "key" || frame.expect === "keyOrEnd");
|
|
19819
|
+
target = keyToken ? void 0 : beginValue();
|
|
19820
|
+
capture = keyToken ? stack.length === 1 : target !== void 0;
|
|
19821
|
+
text = capture ? '"' : "";
|
|
19822
|
+
token = "string";
|
|
19823
|
+
continue;
|
|
19824
|
+
}
|
|
19825
|
+
if (character === "{" || character === "[") {
|
|
19826
|
+
const topLevel = !root;
|
|
19827
|
+
if (topLevel && character !== "{") invalid();
|
|
19828
|
+
beginValue();
|
|
19829
|
+
if (stack.length >= 128) invalid();
|
|
19830
|
+
stack.push({ kind: character === "{" ? "object" : "array", expect: character === "{" ? "keyOrEnd" : "valueOrEnd" });
|
|
19831
|
+
continue;
|
|
19832
|
+
}
|
|
19833
|
+
if (character === "}" || character === "]") {
|
|
19834
|
+
if (!frame || frame.kind !== (character === "}" ? "object" : "array") || !["commaOrEnd", character === "}" ? "keyOrEnd" : "valueOrEnd"].includes(frame.expect)) invalid();
|
|
19835
|
+
stack.pop();
|
|
19836
|
+
if (!stack.length) finished = true;
|
|
19837
|
+
continue;
|
|
19838
|
+
}
|
|
19839
|
+
if (character === ":") {
|
|
19840
|
+
if (frame?.expect !== "colon") invalid();
|
|
19841
|
+
frame.expect = "value";
|
|
19842
|
+
continue;
|
|
19843
|
+
}
|
|
19844
|
+
if (character === ",") {
|
|
19845
|
+
if (frame?.expect !== "commaOrEnd") invalid();
|
|
19846
|
+
frame.expect = frame.kind === "object" ? "key" : "value";
|
|
19847
|
+
continue;
|
|
19848
|
+
}
|
|
19849
|
+
target = beginValue();
|
|
19850
|
+
keyToken = false;
|
|
19851
|
+
capture = true;
|
|
19852
|
+
text = character;
|
|
19853
|
+
token = "primitive";
|
|
19854
|
+
}
|
|
19855
|
+
}
|
|
19856
|
+
if (!finished || token || stack.length) invalid();
|
|
19857
|
+
if (fields.title !== void 0 && typeof fields.title !== "string") invalid();
|
|
19858
|
+
return normalizeNodeSession(fields, id);
|
|
19859
|
+
}
|
|
19860
|
+
|
|
19259
19861
|
// src/node/stores/node-session-store.ts
|
|
19260
19862
|
function createNodeSessionStore(options) {
|
|
19261
19863
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
@@ -19263,7 +19865,7 @@ function createNodeSessionStore(options) {
|
|
|
19263
19865
|
function ensureDir() {
|
|
19264
19866
|
const state = ensureNodeStateRoot(options.stateRoot);
|
|
19265
19867
|
assertSafeNodePath(state.root, state.sessionsDir);
|
|
19266
|
-
|
|
19868
|
+
import_node_fs20.default.mkdirSync(state.sessionsDir, { recursive: true });
|
|
19267
19869
|
}
|
|
19268
19870
|
function filePath(sessionId) {
|
|
19269
19871
|
const target = safeFilePath(paths.sessionsDir, sessionId, ".json");
|
|
@@ -19272,9 +19874,9 @@ function createNodeSessionStore(options) {
|
|
|
19272
19874
|
}
|
|
19273
19875
|
function read(id) {
|
|
19274
19876
|
const target = filePath(id);
|
|
19275
|
-
if (!
|
|
19877
|
+
if (!import_node_fs20.default.existsSync(target)) return null;
|
|
19276
19878
|
let value;
|
|
19277
|
-
const content =
|
|
19879
|
+
const content = import_node_fs20.default.readFileSync(target, "utf8");
|
|
19278
19880
|
try {
|
|
19279
19881
|
value = JSON.parse(content);
|
|
19280
19882
|
} catch {
|
|
@@ -19282,17 +19884,27 @@ function createNodeSessionStore(options) {
|
|
|
19282
19884
|
}
|
|
19283
19885
|
const session = normalizeNodeSession(value, id);
|
|
19284
19886
|
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19285
|
-
if (value.productMode === void 0) atomicReplace(target, JSON.stringify(session, null, 2));
|
|
19286
19887
|
return session;
|
|
19287
19888
|
}
|
|
19288
19889
|
return {
|
|
19289
19890
|
/** 在文件锁内校验并读取当前产品域的 Session。 */
|
|
19290
19891
|
async get(id) {
|
|
19291
19892
|
try {
|
|
19292
|
-
|
|
19293
|
-
return
|
|
19294
|
-
|
|
19295
|
-
|
|
19893
|
+
assertNodeStateSchema(paths.root);
|
|
19894
|
+
return read(id);
|
|
19895
|
+
} catch (error) {
|
|
19896
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19897
|
+
}
|
|
19898
|
+
},
|
|
19899
|
+
/** 单个关联目标也复用流式元数据边界,不读取完整Session正文。 */
|
|
19900
|
+
async getDirectoryEntry(id) {
|
|
19901
|
+
try {
|
|
19902
|
+
assertNodeStateSchema(paths.root);
|
|
19903
|
+
const target = filePath(id);
|
|
19904
|
+
if (!import_node_fs20.default.existsSync(target)) return null;
|
|
19905
|
+
const session = await readSessionDirectoryRecord(target, id);
|
|
19906
|
+
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19907
|
+
return session;
|
|
19296
19908
|
} catch (error) {
|
|
19297
19909
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19298
19910
|
}
|
|
@@ -19300,9 +19912,10 @@ function createNodeSessionStore(options) {
|
|
|
19300
19912
|
/** 逐项加锁读取,损坏记录不能从列表中无声消失。 */
|
|
19301
19913
|
async list() {
|
|
19302
19914
|
try {
|
|
19303
|
-
|
|
19915
|
+
assertNodeStateSchema(paths.root);
|
|
19304
19916
|
const sessions = [];
|
|
19305
|
-
|
|
19917
|
+
if (!import_node_fs20.default.existsSync(paths.sessionsDir)) return sessions;
|
|
19918
|
+
for (const file of import_node_fs20.default.readdirSync(paths.sessionsDir)) {
|
|
19306
19919
|
if (!file.endsWith(".json")) continue;
|
|
19307
19920
|
const session = await this.get(file.slice(0, -5));
|
|
19308
19921
|
if (session) sessions.push(session);
|
|
@@ -19312,19 +19925,69 @@ function createNodeSessionStore(options) {
|
|
|
19312
19925
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19313
19926
|
}
|
|
19314
19927
|
},
|
|
19928
|
+
/** 每页只扫描limit个稳定UUID记录;流式跳过正文,不回退完整get/list。 */
|
|
19929
|
+
async listDirectoryPage(query2) {
|
|
19930
|
+
try {
|
|
19931
|
+
assertNodeStateSchema(paths.root);
|
|
19932
|
+
if (!Number.isInteger(query2.limit) || query2.limit < 1 || query2.limit > 100 || !query2.projectId.trim()) throw new Error("SESSION_CURSOR_INVALID");
|
|
19933
|
+
let after2 = "";
|
|
19934
|
+
if (query2.cursor) {
|
|
19935
|
+
try {
|
|
19936
|
+
const value = JSON.parse(Buffer.from(query2.cursor, "base64url").toString("utf8"));
|
|
19937
|
+
if (value.view !== "session-directory" || value.root !== paths.root || value.mode !== productMode || value.projectId !== query2.projectId || typeof value.after !== "string") throw new Error();
|
|
19938
|
+
after2 = value.after;
|
|
19939
|
+
} catch {
|
|
19940
|
+
throw new Error("SESSION_CURSOR_INVALID");
|
|
19941
|
+
}
|
|
19942
|
+
}
|
|
19943
|
+
const names = import_node_fs20.default.existsSync(paths.sessionsDir) ? import_node_fs20.default.readdirSync(paths.sessionsDir).filter(function session(file) {
|
|
19944
|
+
return file.endsWith(".json") && file.slice(0, -5) > after2;
|
|
19945
|
+
}).sort() : [];
|
|
19946
|
+
const items = [];
|
|
19947
|
+
for (const name of names.slice(0, query2.limit)) {
|
|
19948
|
+
after2 = name.slice(0, -5);
|
|
19949
|
+
const session = await readSessionDirectoryRecord(filePath(after2), after2);
|
|
19950
|
+
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19951
|
+
if (session.projectId === query2.projectId) items.push({ id: session.id, ...session.title !== void 0 ? { title: session.title } : {} });
|
|
19952
|
+
}
|
|
19953
|
+
const nextCursor = names.length > query2.limit ? Buffer.from(JSON.stringify({ view: "session-directory", root: paths.root, mode: productMode, projectId: query2.projectId, after: after2 })).toString("base64url") : void 0;
|
|
19954
|
+
return { items, ...nextCursor ? { nextCursor } : {} };
|
|
19955
|
+
} catch (error) {
|
|
19956
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19957
|
+
}
|
|
19958
|
+
},
|
|
19959
|
+
/** 跨进程锁内确认不存在再创建,防止并发覆盖已有 Session。 */
|
|
19960
|
+
async createIfAbsent(session) {
|
|
19961
|
+
try {
|
|
19962
|
+
ensureDir();
|
|
19963
|
+
const next = normalizeNodeSession(session, session.id);
|
|
19964
|
+
if (next.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19965
|
+
return await withFileLock(filePath(session.id), function createLocked() {
|
|
19966
|
+
if (read(session.id)) return false;
|
|
19967
|
+
atomicReplace(filePath(session.id), JSON.stringify(next, null, 2));
|
|
19968
|
+
return true;
|
|
19969
|
+
}, { requireExitedOwner: true });
|
|
19970
|
+
} catch (error) {
|
|
19971
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19972
|
+
}
|
|
19973
|
+
},
|
|
19315
19974
|
/** 在同一临界区比较持久化身份并原子替换,拒绝底层直接越权写入。 */
|
|
19316
19975
|
async save(session) {
|
|
19976
|
+
let phase = "prepare";
|
|
19317
19977
|
try {
|
|
19318
19978
|
ensureDir();
|
|
19979
|
+
phase = "identity";
|
|
19319
19980
|
const next = normalizeNodeSession(session, session.id);
|
|
19320
19981
|
if (next.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19982
|
+
phase = "lock";
|
|
19321
19983
|
await withFileLock(filePath(session.id), function saveLocked() {
|
|
19984
|
+
phase = "identity";
|
|
19322
19985
|
const previous = read(session.id);
|
|
19323
19986
|
if (previous) assertNodeSessionIdentity(previous, next);
|
|
19324
19987
|
atomicReplace(filePath(session.id), JSON.stringify(next, null, 2));
|
|
19325
19988
|
});
|
|
19326
19989
|
} catch (error) {
|
|
19327
|
-
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19990
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE", { operation: "session_save", target: "session", phase, ...getFileOperationDiagnostic(error) });
|
|
19328
19991
|
}
|
|
19329
19992
|
},
|
|
19330
19993
|
/** 只删除当前产品域记录;外围资源仍由 SessionResourceStore 先行清理。 */
|
|
@@ -19334,7 +19997,7 @@ function createNodeSessionStore(options) {
|
|
|
19334
19997
|
const target = filePath(id);
|
|
19335
19998
|
return await withFileLock(target, function deleteLocked() {
|
|
19336
19999
|
if (!read(id)) return false;
|
|
19337
|
-
|
|
20000
|
+
import_node_fs20.default.unlinkSync(target);
|
|
19338
20001
|
return true;
|
|
19339
20002
|
});
|
|
19340
20003
|
} catch (error) {
|
|
@@ -19346,11 +20009,16 @@ function createNodeSessionStore(options) {
|
|
|
19346
20009
|
|
|
19347
20010
|
// src/node/stores/node-transcript-store.ts
|
|
19348
20011
|
var import_promises3 = __toESM(require("node:fs/promises"));
|
|
19349
|
-
var
|
|
20012
|
+
var import_node_path17 = __toESM(require("node:path"));
|
|
19350
20013
|
var transcriptIndexes = /* @__PURE__ */ new Map();
|
|
19351
20014
|
var transcriptRootInitializations = /* @__PURE__ */ new Map();
|
|
20015
|
+
function parseTranscriptFileIdentity(value) {
|
|
20016
|
+
if (typeof value === "string" && /^\d{1,20}$/.test(value)) return BigInt(value).toString();
|
|
20017
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return String(value);
|
|
20018
|
+
throw new Error("THREAD_CURSOR_INVALID");
|
|
20019
|
+
}
|
|
19352
20020
|
function getTranscriptIndex(filePath) {
|
|
19353
|
-
const key2 =
|
|
20021
|
+
const key2 = import_node_path17.default.resolve(filePath);
|
|
19354
20022
|
const existing = transcriptIndexes.get(key2);
|
|
19355
20023
|
if (existing) return existing;
|
|
19356
20024
|
const created = { initialized: false, offset: 0, pendingBytes: Buffer.alloc(0), endsWithNewline: true, keys: /* @__PURE__ */ new Set() };
|
|
@@ -19361,7 +20029,7 @@ function getEnvelopeKey(envelope) {
|
|
|
19361
20029
|
return `${envelope.sessionId}\0${envelope.turnId}\0${envelope.seq}`;
|
|
19362
20030
|
}
|
|
19363
20031
|
function ensureTranscriptDirectory(stateRoot) {
|
|
19364
|
-
const key2 =
|
|
20032
|
+
const key2 = import_node_path17.default.resolve(stateRoot);
|
|
19365
20033
|
const existing = transcriptRootInitializations.get(key2);
|
|
19366
20034
|
if (existing) return existing;
|
|
19367
20035
|
const initialization = Promise.resolve().then(async function initializeTranscriptDirectory() {
|
|
@@ -19383,7 +20051,7 @@ async function readTranscriptBuffer(filePath) {
|
|
|
19383
20051
|
}
|
|
19384
20052
|
}
|
|
19385
20053
|
function reportCorruptedLine(filePath) {
|
|
19386
|
-
console.warn(`[DURABLE_JSONL_CORRUPTED] file=${
|
|
20054
|
+
console.warn(`[DURABLE_JSONL_CORRUPTED] file=${import_node_path17.default.basename(filePath)} records=1 lines=unknown`);
|
|
19387
20055
|
}
|
|
19388
20056
|
function parseTranscriptLine(filePath, line, index, parsed) {
|
|
19389
20057
|
if (line.length === 0) return;
|
|
@@ -19447,26 +20115,28 @@ async function readTranscriptTail(filePath, offset) {
|
|
|
19447
20115
|
}
|
|
19448
20116
|
}
|
|
19449
20117
|
async function refreshTranscriptIndex(filePath, index) {
|
|
19450
|
-
if (!index.initialized) {
|
|
19451
|
-
rebuildTranscriptIndex(filePath, await readTranscriptBuffer(filePath), index);
|
|
19452
|
-
return;
|
|
19453
|
-
}
|
|
19454
20118
|
let stats;
|
|
19455
20119
|
try {
|
|
19456
|
-
stats = await import_promises3.default.stat(filePath);
|
|
20120
|
+
stats = await import_promises3.default.stat(filePath, { bigint: true });
|
|
19457
20121
|
} catch (error) {
|
|
19458
20122
|
if (error.code !== "ENOENT") throw error;
|
|
19459
20123
|
rebuildTranscriptIndex(filePath, Buffer.alloc(0), index);
|
|
20124
|
+
index.identity = void 0;
|
|
20125
|
+
index.signature = void 0;
|
|
19460
20126
|
return;
|
|
19461
20127
|
}
|
|
19462
|
-
|
|
20128
|
+
const identity = `${stats.dev}:${stats.ino}:${stats.birthtimeNs}`;
|
|
20129
|
+
const signature = `${identity}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
|
|
20130
|
+
const size = Number(stats.size);
|
|
20131
|
+
if (!index.initialized || index.identity !== identity || size < index.offset || size === index.offset && index.signature !== signature) {
|
|
19463
20132
|
rebuildTranscriptIndex(filePath, await readTranscriptBuffer(filePath), index);
|
|
19464
|
-
|
|
20133
|
+
} else if (size > index.offset) {
|
|
20134
|
+
const tail = await readTranscriptTail(filePath, index.offset);
|
|
20135
|
+
consumeTranscriptBytes(filePath, tail.bytes, index);
|
|
20136
|
+
index.offset = tail.size;
|
|
19465
20137
|
}
|
|
19466
|
-
|
|
19467
|
-
|
|
19468
|
-
consumeTranscriptBytes(filePath, tail.bytes, index);
|
|
19469
|
-
index.offset = tail.size;
|
|
20138
|
+
index.identity = identity;
|
|
20139
|
+
index.signature = signature;
|
|
19470
20140
|
}
|
|
19471
20141
|
async function appendTranscriptEnvelope(filePath, envelope) {
|
|
19472
20142
|
const index = getTranscriptIndex(filePath);
|
|
@@ -19483,6 +20153,9 @@ async function appendTranscriptEnvelope(filePath, envelope) {
|
|
|
19483
20153
|
index.endsWithNewline = true;
|
|
19484
20154
|
index.offset += bytes.length;
|
|
19485
20155
|
index.keys.add(key2);
|
|
20156
|
+
const stats = await import_promises3.default.stat(filePath, { bigint: true });
|
|
20157
|
+
index.identity = `${stats.dev}:${stats.ino}:${stats.birthtimeNs}`;
|
|
20158
|
+
index.signature = `${index.identity}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
|
|
19486
20159
|
});
|
|
19487
20160
|
}
|
|
19488
20161
|
function removeAdjacentDuplicateEnvelopes(parsed) {
|
|
@@ -19499,7 +20172,9 @@ function removeAdjacentDuplicateEnvelopes(parsed) {
|
|
|
19499
20172
|
function createNodeTranscriptStore(options) {
|
|
19500
20173
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19501
20174
|
function filePath(sessionId) {
|
|
19502
|
-
|
|
20175
|
+
const target = safeFilePath(paths.transcriptsDir, sessionId, ".jsonl");
|
|
20176
|
+
assertSafeNodePath(paths.root, target);
|
|
20177
|
+
return target;
|
|
19503
20178
|
}
|
|
19504
20179
|
return {
|
|
19505
20180
|
async append(sessionId, envelope) {
|
|
@@ -19514,6 +20189,88 @@ function createNodeTranscriptStore(options) {
|
|
|
19514
20189
|
return removeAdjacentDuplicateEnvelopes(rebuildTranscriptIndex(target, await readTranscriptBuffer(target), index));
|
|
19515
20190
|
});
|
|
19516
20191
|
},
|
|
20192
|
+
/** 从字节游标增量读取 JSONL,不初始化目录、不持有写锁。 */
|
|
20193
|
+
async readPage(sessionId, options2) {
|
|
20194
|
+
if (!Number.isInteger(options2.limit) || options2.limit < 1 || options2.limit > 100) throw new Error("THREAD_CURSOR_INVALID");
|
|
20195
|
+
assertNodeStateSchema(paths.root);
|
|
20196
|
+
let offset = 0;
|
|
20197
|
+
let identity;
|
|
20198
|
+
if (options2.cursor) {
|
|
20199
|
+
try {
|
|
20200
|
+
const data = JSON.parse(Buffer.from(options2.cursor, "base64url").toString("utf8"));
|
|
20201
|
+
if (data.sessionId !== sessionId || !Number.isSafeInteger(data.offset) || data.offset < 0) throw new Error();
|
|
20202
|
+
offset = data.offset;
|
|
20203
|
+
identity = { dev: parseTranscriptFileIdentity(data.dev), ino: parseTranscriptFileIdentity(data.ino), size: data.size, stamp: data.stamp };
|
|
20204
|
+
if (data.size !== void 0 && (!Number.isSafeInteger(data.size) || data.size < offset) || data.stamp !== void 0 && typeof data.stamp !== "string") throw new Error();
|
|
20205
|
+
} catch {
|
|
20206
|
+
throw new Error("THREAD_CURSOR_INVALID");
|
|
20207
|
+
}
|
|
20208
|
+
}
|
|
20209
|
+
let handle;
|
|
20210
|
+
try {
|
|
20211
|
+
handle = await import_promises3.default.open(filePath(sessionId), "r");
|
|
20212
|
+
} catch (error) {
|
|
20213
|
+
if (error.code === "ENOENT") {
|
|
20214
|
+
if (offset === 0) return { items: [] };
|
|
20215
|
+
throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20216
|
+
}
|
|
20217
|
+
throw error;
|
|
20218
|
+
}
|
|
20219
|
+
try {
|
|
20220
|
+
const stats = await handle.stat({ bigint: true });
|
|
20221
|
+
const size = Number(stats.size);
|
|
20222
|
+
const dev = stats.dev.toString();
|
|
20223
|
+
const ino = stats.ino.toString();
|
|
20224
|
+
if (!Number.isSafeInteger(size)) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20225
|
+
const stamp = `${stats.mtimeNs}:${stats.ctimeNs}:${stats.birthtimeNs}`;
|
|
20226
|
+
if (identity && (identity.dev !== dev || identity.ino !== ino || identity.size === size && identity.stamp !== void 0 && identity.stamp !== stamp)) throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20227
|
+
if (offset > size) throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20228
|
+
if (offset > 0) {
|
|
20229
|
+
const previous = Buffer.alloc(1);
|
|
20230
|
+
await handle.read(previous, 0, 1, offset - 1);
|
|
20231
|
+
if (previous[0] !== 10) throw new Error("THREAD_CURSOR_INVALID");
|
|
20232
|
+
}
|
|
20233
|
+
const items = [];
|
|
20234
|
+
let position = offset;
|
|
20235
|
+
let lineStart = offset;
|
|
20236
|
+
let pending = Buffer.alloc(0);
|
|
20237
|
+
const chunk = Buffer.alloc(16 * 1024);
|
|
20238
|
+
while (position < size && items.length < options2.limit) {
|
|
20239
|
+
const result = await handle.read(chunk, 0, Math.min(chunk.length, size - position), position);
|
|
20240
|
+
if (!result.bytesRead) break;
|
|
20241
|
+
let start = 0;
|
|
20242
|
+
for (let i = 0; i < result.bytesRead; i++) {
|
|
20243
|
+
if (chunk[i] !== 10) continue;
|
|
20244
|
+
const line = pending.length ? Buffer.concat([pending, chunk.subarray(start, i)]) : chunk.subarray(start, i);
|
|
20245
|
+
if (line.length > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20246
|
+
let item;
|
|
20247
|
+
try {
|
|
20248
|
+
item = JSON.parse(line.toString("utf8"));
|
|
20249
|
+
} catch {
|
|
20250
|
+
throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20251
|
+
}
|
|
20252
|
+
if (item.sessionId !== sessionId) throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20253
|
+
items.push(item);
|
|
20254
|
+
lineStart = position + i + 1;
|
|
20255
|
+
pending = Buffer.alloc(0);
|
|
20256
|
+
start = i + 1;
|
|
20257
|
+
if (items.length === options2.limit) break;
|
|
20258
|
+
}
|
|
20259
|
+
if (items.length === options2.limit) {
|
|
20260
|
+
position = lineStart;
|
|
20261
|
+
break;
|
|
20262
|
+
}
|
|
20263
|
+
pending = Buffer.concat([pending, chunk.subarray(start, result.bytesRead)]);
|
|
20264
|
+
if (pending.length > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20265
|
+
position += result.bytesRead;
|
|
20266
|
+
}
|
|
20267
|
+
if (position >= size && pending.length > 0) throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20268
|
+
const cursor = Buffer.from(JSON.stringify({ sessionId, offset: lineStart, dev, ino, size, stamp })).toString("base64url");
|
|
20269
|
+
return { items, cursor, ...lineStart < size ? { nextCursor: cursor } : {} };
|
|
20270
|
+
} finally {
|
|
20271
|
+
await handle.close();
|
|
20272
|
+
}
|
|
20273
|
+
},
|
|
19517
20274
|
async deleteBySession(sessionId) {
|
|
19518
20275
|
await ensureTranscriptDirectory(paths.root);
|
|
19519
20276
|
const target = filePath(sessionId);
|
|
@@ -19535,20 +20292,20 @@ function createNodeTranscriptStore(options) {
|
|
|
19535
20292
|
}
|
|
19536
20293
|
|
|
19537
20294
|
// src/node/stores/node-turn-store.ts
|
|
19538
|
-
var
|
|
20295
|
+
var import_node_fs21 = __toESM(require("node:fs"));
|
|
19539
20296
|
function createNodeTurnStore(options) {
|
|
19540
20297
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19541
20298
|
function ensureDir() {
|
|
19542
20299
|
const state = ensureNodeStateRoot(paths.root);
|
|
19543
|
-
|
|
20300
|
+
import_node_fs21.default.mkdirSync(state.turnsDir, { recursive: true });
|
|
19544
20301
|
}
|
|
19545
20302
|
function filePath(turnId) {
|
|
19546
20303
|
return safeFilePath(paths.turnsDir, turnId, ".json");
|
|
19547
20304
|
}
|
|
19548
20305
|
return {
|
|
19549
20306
|
async get(id) {
|
|
19550
|
-
|
|
19551
|
-
return
|
|
20307
|
+
assertNodeStateSchema(paths.root);
|
|
20308
|
+
return readJsonFile(filePath(id));
|
|
19552
20309
|
},
|
|
19553
20310
|
async save(turn) {
|
|
19554
20311
|
ensureDir();
|
|
@@ -19557,9 +20314,10 @@ function createNodeTurnStore(options) {
|
|
|
19557
20314
|
});
|
|
19558
20315
|
},
|
|
19559
20316
|
async list(sessionId) {
|
|
19560
|
-
|
|
20317
|
+
assertNodeStateSchema(paths.root);
|
|
19561
20318
|
const turns = [];
|
|
19562
|
-
|
|
20319
|
+
if (!import_node_fs21.default.existsSync(paths.turnsDir)) return turns;
|
|
20320
|
+
for (const file of import_node_fs21.default.readdirSync(paths.turnsDir).filter((entry) => entry.endsWith(".json"))) {
|
|
19563
20321
|
const turn = readJsonFile(filePath(file.slice(0, -5)));
|
|
19564
20322
|
if (turn?.sessionId === sessionId) turns.push(turn);
|
|
19565
20323
|
}
|
|
@@ -19576,7 +20334,7 @@ function createNodeTurnStore(options) {
|
|
|
19576
20334
|
for (const turn of turns) {
|
|
19577
20335
|
const target = filePath(turn.id);
|
|
19578
20336
|
await withFileLock(target, () => {
|
|
19579
|
-
if (
|
|
20337
|
+
if (import_node_fs21.default.existsSync(target)) import_node_fs21.default.unlinkSync(target);
|
|
19580
20338
|
});
|
|
19581
20339
|
}
|
|
19582
20340
|
}
|
|
@@ -19584,12 +20342,12 @@ function createNodeTurnStore(options) {
|
|
|
19584
20342
|
}
|
|
19585
20343
|
|
|
19586
20344
|
// src/node/stores/node-lease-store.ts
|
|
19587
|
-
var
|
|
20345
|
+
var import_node_fs22 = __toESM(require("node:fs"));
|
|
19588
20346
|
function createNodeLeaseStore(options) {
|
|
19589
20347
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19590
20348
|
function ensureDir() {
|
|
19591
20349
|
const state = ensureNodeStateRoot(paths.root);
|
|
19592
|
-
|
|
20350
|
+
import_node_fs22.default.mkdirSync(state.leasesDir, { recursive: true });
|
|
19593
20351
|
}
|
|
19594
20352
|
function filePath(sessionId) {
|
|
19595
20353
|
return safeFilePath(paths.leasesDir, sessionId, ".json");
|
|
@@ -19598,6 +20356,11 @@ function createNodeLeaseStore(options) {
|
|
|
19598
20356
|
return now - record.lease.heartbeatAt <= staleAfterMs;
|
|
19599
20357
|
}
|
|
19600
20358
|
return {
|
|
20359
|
+
/** 原子替换文件允许无锁只读;禁止在状态查询中初始化或迁移存储。 */
|
|
20360
|
+
async readCurrent(sessionId) {
|
|
20361
|
+
const current = readJsonFile(filePath(sessionId));
|
|
20362
|
+
return current ? { turnId: current.turnId, lease: { ...current.lease } } : null;
|
|
20363
|
+
},
|
|
19601
20364
|
async acquire(input) {
|
|
19602
20365
|
ensureDir();
|
|
19603
20366
|
const target = filePath(input.sessionId);
|
|
@@ -19626,7 +20389,7 @@ function createNodeLeaseStore(options) {
|
|
|
19626
20389
|
return withFileLock(target, () => {
|
|
19627
20390
|
const current = readJsonFile(target);
|
|
19628
20391
|
if (!current || current.lease.leaseId !== input.lease.leaseId || current.lease.ownerId !== input.lease.ownerId) return false;
|
|
19629
|
-
if (
|
|
20392
|
+
if (import_node_fs22.default.existsSync(target)) import_node_fs22.default.unlinkSync(target);
|
|
19630
20393
|
return true;
|
|
19631
20394
|
});
|
|
19632
20395
|
},
|
|
@@ -19634,7 +20397,7 @@ function createNodeLeaseStore(options) {
|
|
|
19634
20397
|
ensureDir();
|
|
19635
20398
|
const target = filePath(sessionId);
|
|
19636
20399
|
await withFileLock(target, () => {
|
|
19637
|
-
if (
|
|
20400
|
+
if (import_node_fs22.default.existsSync(target)) import_node_fs22.default.unlinkSync(target);
|
|
19638
20401
|
});
|
|
19639
20402
|
}
|
|
19640
20403
|
};
|
|
@@ -19649,26 +20412,26 @@ function createNodeClock() {
|
|
|
19649
20412
|
}
|
|
19650
20413
|
|
|
19651
20414
|
// src/node/stores/node-job-store.ts
|
|
19652
|
-
var
|
|
19653
|
-
var
|
|
20415
|
+
var import_node_fs23 = __toESM(require("node:fs"));
|
|
20416
|
+
var import_node_path18 = __toESM(require("node:path"));
|
|
19654
20417
|
function createNodeJobStore(options) {
|
|
19655
20418
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19656
20419
|
function ensureDir() {
|
|
19657
20420
|
const state = ensureNodeStateRoot(paths.root);
|
|
19658
|
-
|
|
20421
|
+
import_node_fs23.default.mkdirSync(state.jobsDir, { recursive: true });
|
|
19659
20422
|
}
|
|
19660
20423
|
function filePath(id) {
|
|
19661
20424
|
return safeFilePath(paths.jobsDir, id, ".json");
|
|
19662
20425
|
}
|
|
19663
20426
|
function sessionLockPath(sessionId) {
|
|
19664
|
-
return safeFilePath(
|
|
20427
|
+
return safeFilePath(import_node_path18.default.join(paths.jobsDir, ".session-locks"), sessionId, ".guard");
|
|
19665
20428
|
}
|
|
19666
20429
|
function sameOwner(first, second) {
|
|
19667
20430
|
return first?.runtimeInstanceId === second.runtimeInstanceId && first.hostProcessId === second.hostProcessId;
|
|
19668
20431
|
}
|
|
19669
20432
|
function readAll() {
|
|
19670
20433
|
ensureDir();
|
|
19671
|
-
return
|
|
20434
|
+
return import_node_fs23.default.readdirSync(paths.jobsDir).filter((file) => file.endsWith(".json")).flatMap((file) => {
|
|
19672
20435
|
const job = readJsonFile(filePath(file.slice(0, -5)));
|
|
19673
20436
|
return job ? [job] : [];
|
|
19674
20437
|
});
|
|
@@ -19681,7 +20444,7 @@ function createNodeJobStore(options) {
|
|
|
19681
20444
|
async create(job) {
|
|
19682
20445
|
ensureDir();
|
|
19683
20446
|
return withFileLock(filePath(job.id), function createIfMissing() {
|
|
19684
|
-
if (
|
|
20447
|
+
if (import_node_fs23.default.existsSync(filePath(job.id))) return false;
|
|
19685
20448
|
atomicReplace(filePath(job.id), JSON.stringify(job, null, 2));
|
|
19686
20449
|
return true;
|
|
19687
20450
|
});
|
|
@@ -19710,7 +20473,7 @@ function createNodeJobStore(options) {
|
|
|
19710
20473
|
for (const job of await this.listBySession(sessionId)) {
|
|
19711
20474
|
const target = filePath(job.id);
|
|
19712
20475
|
await withFileLock(target, () => {
|
|
19713
|
-
if (
|
|
20476
|
+
if (import_node_fs23.default.existsSync(target)) import_node_fs23.default.unlinkSync(target);
|
|
19714
20477
|
});
|
|
19715
20478
|
}
|
|
19716
20479
|
},
|
|
@@ -19738,43 +20501,43 @@ function createNodeJobOwnerProbe() {
|
|
|
19738
20501
|
}
|
|
19739
20502
|
|
|
19740
20503
|
// src/node/stores/node-file-mutation-store.ts
|
|
19741
|
-
var
|
|
19742
|
-
var
|
|
19743
|
-
var
|
|
20504
|
+
var import_node_crypto10 = require("node:crypto");
|
|
20505
|
+
var import_node_fs24 = __toESM(require("node:fs"));
|
|
20506
|
+
var import_node_path19 = __toESM(require("node:path"));
|
|
19744
20507
|
var MAX_FILE_SNAPSHOT_BYTES = 512 * 1024;
|
|
19745
20508
|
var MAX_SESSION_SNAPSHOT_BYTES = 5 * 1024 * 1024;
|
|
19746
20509
|
function sha256(content) {
|
|
19747
|
-
return (0,
|
|
20510
|
+
return (0, import_node_crypto10.createHash)("sha256").update(content).digest("hex");
|
|
19748
20511
|
}
|
|
19749
20512
|
function writeBlob(blobPath, content) {
|
|
19750
|
-
if (
|
|
19751
|
-
|
|
19752
|
-
const temporary = `${blobPath}.${process.pid}.${(0,
|
|
20513
|
+
if (import_node_fs24.default.existsSync(blobPath)) return;
|
|
20514
|
+
import_node_fs24.default.mkdirSync(import_node_path19.default.dirname(blobPath), { recursive: true });
|
|
20515
|
+
const temporary = `${blobPath}.${process.pid}.${(0, import_node_crypto10.randomUUID)()}.tmp`;
|
|
19753
20516
|
try {
|
|
19754
|
-
const descriptor =
|
|
20517
|
+
const descriptor = import_node_fs24.default.openSync(temporary, "wx");
|
|
19755
20518
|
try {
|
|
19756
|
-
|
|
19757
|
-
|
|
20519
|
+
import_node_fs24.default.writeFileSync(descriptor, content);
|
|
20520
|
+
import_node_fs24.default.fsyncSync(descriptor);
|
|
19758
20521
|
} finally {
|
|
19759
|
-
|
|
20522
|
+
import_node_fs24.default.closeSync(descriptor);
|
|
19760
20523
|
}
|
|
19761
20524
|
try {
|
|
19762
|
-
|
|
20525
|
+
import_node_fs24.default.renameSync(temporary, blobPath);
|
|
19763
20526
|
} catch (error) {
|
|
19764
|
-
if (!
|
|
20527
|
+
if (!import_node_fs24.default.existsSync(blobPath)) throw error;
|
|
19765
20528
|
}
|
|
19766
20529
|
} finally {
|
|
19767
|
-
if (
|
|
20530
|
+
if (import_node_fs24.default.existsSync(temporary)) import_node_fs24.default.unlinkSync(temporary);
|
|
19768
20531
|
}
|
|
19769
20532
|
}
|
|
19770
20533
|
function createNodeFileMutationStore(options) {
|
|
19771
20534
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19772
20535
|
function ensureDir() {
|
|
19773
20536
|
const state = ensureNodeStateRoot(paths.root);
|
|
19774
|
-
|
|
19775
|
-
|
|
19776
|
-
|
|
19777
|
-
|
|
20537
|
+
import_node_fs24.default.mkdirSync(state.mutationsDir, { recursive: true });
|
|
20538
|
+
import_node_fs24.default.mkdirSync(state.mutationBlobsDir, { recursive: true });
|
|
20539
|
+
import_node_fs24.default.mkdirSync(state.mutationLocksDir, { recursive: true });
|
|
20540
|
+
import_node_fs24.default.mkdirSync(state.undoTransactionsDir, { recursive: true });
|
|
19778
20541
|
}
|
|
19779
20542
|
function mutationPath(id) {
|
|
19780
20543
|
return safeFilePath(paths.mutationsDir, id, ".json");
|
|
@@ -19788,9 +20551,9 @@ function createNodeFileMutationStore(options) {
|
|
|
19788
20551
|
}
|
|
19789
20552
|
function readAll() {
|
|
19790
20553
|
ensureDir();
|
|
19791
|
-
return
|
|
20554
|
+
return import_node_fs24.default.readdirSync(paths.mutationsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
|
|
19792
20555
|
try {
|
|
19793
|
-
return [JSON.parse(
|
|
20556
|
+
return [JSON.parse(import_node_fs24.default.readFileSync(mutationPath(entry.slice(0, -5)), "utf8"))];
|
|
19794
20557
|
} catch {
|
|
19795
20558
|
return [];
|
|
19796
20559
|
}
|
|
@@ -19798,9 +20561,9 @@ function createNodeFileMutationStore(options) {
|
|
|
19798
20561
|
}
|
|
19799
20562
|
function readTransactions() {
|
|
19800
20563
|
ensureDir();
|
|
19801
|
-
return
|
|
20564
|
+
return import_node_fs24.default.readdirSync(paths.undoTransactionsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
|
|
19802
20565
|
try {
|
|
19803
|
-
return [JSON.parse(
|
|
20566
|
+
return [JSON.parse(import_node_fs24.default.readFileSync(transactionPath(entry.slice(0, -5)), "utf8"))];
|
|
19804
20567
|
} catch {
|
|
19805
20568
|
return [];
|
|
19806
20569
|
}
|
|
@@ -19808,7 +20571,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19808
20571
|
}
|
|
19809
20572
|
function sessionBlobBytes(sessionId) {
|
|
19810
20573
|
const refs3 = new Set(readAll().filter((item) => item.sessionId === sessionId).flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
|
|
19811
|
-
return [...refs3].reduce((total, ref) => total + (
|
|
20574
|
+
return [...refs3].reduce((total, ref) => total + (import_node_fs24.default.statSync(blobPath(ref), { throwIfNoEntry: false })?.size ?? 0), 0);
|
|
19812
20575
|
}
|
|
19813
20576
|
return {
|
|
19814
20577
|
async prepare(input) {
|
|
@@ -19818,13 +20581,13 @@ function createNodeFileMutationStore(options) {
|
|
|
19818
20581
|
const refs3 = /* @__PURE__ */ new Map();
|
|
19819
20582
|
if (input.before) refs3.set(beforeRef, input.before);
|
|
19820
20583
|
if (input.after) refs3.set(afterRef, input.after);
|
|
19821
|
-
const additionalBytes = [...refs3.entries()].filter(([ref]) => !
|
|
20584
|
+
const additionalBytes = [...refs3.entries()].filter(([ref]) => !import_node_fs24.default.existsSync(blobPath(ref))).reduce((total, [, content]) => total + content.byteLength, 0);
|
|
19822
20585
|
const byteCount = (input.before?.byteLength ?? 0) + (input.after?.byteLength ?? 0);
|
|
19823
20586
|
const binary2 = Boolean(input.before?.includes(0) || input.after?.includes(0));
|
|
19824
20587
|
const reversible = !binary2 && byteCount <= MAX_FILE_SNAPSHOT_BYTES && sessionBlobBytes(input.sessionId) + additionalBytes <= MAX_SESSION_SNAPSHOT_BYTES;
|
|
19825
20588
|
if (reversible) for (const [ref, content] of refs3) writeBlob(blobPath(ref), content);
|
|
19826
20589
|
const mutation = {
|
|
19827
|
-
id: (0,
|
|
20590
|
+
id: (0, import_node_crypto10.randomUUID)(),
|
|
19828
20591
|
sessionId: input.sessionId,
|
|
19829
20592
|
turnId: input.turnId,
|
|
19830
20593
|
toolCallId: input.toolCallId,
|
|
@@ -19849,7 +20612,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19849
20612
|
async getBlob(ref) {
|
|
19850
20613
|
ensureDir();
|
|
19851
20614
|
try {
|
|
19852
|
-
const content =
|
|
20615
|
+
const content = import_node_fs24.default.readFileSync(blobPath(ref));
|
|
19853
20616
|
return sha256(content) === ref ? content : null;
|
|
19854
20617
|
} catch {
|
|
19855
20618
|
return null;
|
|
@@ -19867,14 +20630,14 @@ function createNodeFileMutationStore(options) {
|
|
|
19867
20630
|
},
|
|
19868
20631
|
async deleteBySession(sessionId) {
|
|
19869
20632
|
ensureDir();
|
|
19870
|
-
for (const mutation of readAll().filter((item) => item.sessionId === sessionId))
|
|
19871
|
-
for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId))
|
|
20633
|
+
for (const mutation of readAll().filter((item) => item.sessionId === sessionId)) import_node_fs24.default.rmSync(mutationPath(mutation.id), { force: true });
|
|
20634
|
+
for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId)) import_node_fs24.default.rmSync(transactionPath(transaction.id), { force: true });
|
|
19872
20635
|
const referenced = new Set(readAll().flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
|
|
19873
|
-
for (const entry of
|
|
20636
|
+
for (const entry of import_node_fs24.default.readdirSync(paths.mutationBlobsDir).filter((item) => item.endsWith(".blob"))) if (!referenced.has(entry.slice(0, -5))) import_node_fs24.default.rmSync(import_node_path19.default.join(paths.mutationBlobsDir, entry), { force: true });
|
|
19874
20637
|
},
|
|
19875
20638
|
async withWorkspaceLock(workspaceRoot, operation, canonicalTargets = []) {
|
|
19876
20639
|
ensureDir();
|
|
19877
|
-
const lockId = (0,
|
|
20640
|
+
const lockId = (0, import_node_crypto10.createHash)("sha256").update(import_node_path19.default.resolve(workspaceRoot)).digest("hex");
|
|
19878
20641
|
return withFileLock(safeFilePath(paths.mutationLocksDir, lockId, ".lock-target"), function lockTargets() {
|
|
19879
20642
|
return withNodeFileMutationLocks(canonicalTargets, operation);
|
|
19880
20643
|
}, { requireExitedOwner: true });
|
|
@@ -19883,32 +20646,94 @@ function createNodeFileMutationStore(options) {
|
|
|
19883
20646
|
}
|
|
19884
20647
|
|
|
19885
20648
|
// src/node/stores/node-session-resource-store.ts
|
|
19886
|
-
var
|
|
19887
|
-
var
|
|
20649
|
+
var import_node_fs25 = __toESM(require("node:fs"));
|
|
20650
|
+
var import_node_path20 = __toESM(require("node:path"));
|
|
19888
20651
|
function isAttachmentSessionId(sessionId) {
|
|
19889
20652
|
return /^[0-9a-f-]{36}$/iu.test(sessionId);
|
|
19890
20653
|
}
|
|
19891
20654
|
function createNodeSessionResourceStore(workspaceRoot) {
|
|
19892
20655
|
const root = canonicalizeNodePath(workspaceRoot);
|
|
19893
|
-
const uploadsRoot =
|
|
20656
|
+
const uploadsRoot = import_node_path20.default.join(root, ".local", "session-uploads");
|
|
19894
20657
|
return {
|
|
19895
20658
|
async deleteBySession(sessionId) {
|
|
19896
20659
|
if (!isAttachmentSessionId(sessionId)) return;
|
|
19897
|
-
const target =
|
|
19898
|
-
if (!target.startsWith(`${uploadsRoot}${
|
|
19899
|
-
|
|
20660
|
+
const target = import_node_path20.default.join(uploadsRoot, sessionId);
|
|
20661
|
+
if (!target.startsWith(`${uploadsRoot}${import_node_path20.default.sep}`)) throw new Error("SESSION_RESOURCE_PATH_INVALID");
|
|
20662
|
+
import_node_fs25.default.rmSync(target, { recursive: true, force: true, maxRetries: 2 });
|
|
20663
|
+
}
|
|
20664
|
+
};
|
|
20665
|
+
}
|
|
20666
|
+
|
|
20667
|
+
// src/node/stores/node-session-image-store.ts
|
|
20668
|
+
var import_node_crypto11 = __toESM(require("node:crypto"));
|
|
20669
|
+
var import_node_fs26 = __toESM(require("node:fs"));
|
|
20670
|
+
var import_node_path21 = __toESM(require("node:path"));
|
|
20671
|
+
var import_core16 = require("@autopilot-agent/core");
|
|
20672
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
20673
|
+
function sessionDirectory(root, sessionId, create3) {
|
|
20674
|
+
if (!UUID.test(sessionId)) throw new Error("SESSION_IMAGE_INVALID");
|
|
20675
|
+
let current = import_node_fs26.default.realpathSync(root);
|
|
20676
|
+
for (const part of [".local", "session-uploads", sessionId]) {
|
|
20677
|
+
current = import_node_path21.default.join(current, part);
|
|
20678
|
+
if (create3) {
|
|
20679
|
+
try {
|
|
20680
|
+
import_node_fs26.default.mkdirSync(current);
|
|
20681
|
+
} catch (error) {
|
|
20682
|
+
if (error.code !== "EEXIST") throw error;
|
|
20683
|
+
}
|
|
20684
|
+
}
|
|
20685
|
+
const stat = import_node_fs26.default.lstatSync(current);
|
|
20686
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("SESSION_IMAGE_INVALID");
|
|
20687
|
+
}
|
|
20688
|
+
return current;
|
|
20689
|
+
}
|
|
20690
|
+
function createNodeSessionImageStore(workspaceRoot) {
|
|
20691
|
+
return {
|
|
20692
|
+
/** 校验并保存规范化副本与不可变元数据。 */
|
|
20693
|
+
async put(input) {
|
|
20694
|
+
let normalized;
|
|
20695
|
+
try {
|
|
20696
|
+
normalized = await (0, import_core16.normalizeWorkImage)({ bytes: input.bytes, mimeType: input.mimeType });
|
|
20697
|
+
} catch {
|
|
20698
|
+
throw new Error("SESSION_IMAGE_INVALID");
|
|
20699
|
+
}
|
|
20700
|
+
const directory = sessionDirectory(workspaceRoot, input.sessionId, true);
|
|
20701
|
+
const id = import_node_crypto11.default.randomUUID();
|
|
20702
|
+
const extension = normalized.mimeType === "image/jpeg" ? ".jpg" : normalized.mimeType === "image/png" ? ".png" : normalized.mimeType === "image/webp" ? ".webp" : ".gif";
|
|
20703
|
+
const bytes = Buffer.from(normalized.bytes);
|
|
20704
|
+
const image = { id, name: import_node_path21.default.basename(input.name), mimeType: normalized.mimeType, relativePath: `.local/session-uploads/${input.sessionId}/${id}${extension}`, sha256: import_node_crypto11.default.createHash("sha256").update(bytes).digest("hex"), width: normalized.width, height: normalized.height, bytes: bytes.length, gifFirstFrame: normalized.gifFirstFrame };
|
|
20705
|
+
import_node_fs26.default.writeFileSync(import_node_path21.default.join(directory, `${id}${extension}`), bytes, { flag: "wx" });
|
|
20706
|
+
import_node_fs26.default.writeFileSync(import_node_path21.default.join(directory, `${id}.json`), JSON.stringify(image), { flag: "wx" });
|
|
20707
|
+
return image;
|
|
20708
|
+
},
|
|
20709
|
+
/** 按会话和图片标识读取并复核文件哈希。 */
|
|
20710
|
+
async read(input) {
|
|
20711
|
+
if (!UUID.test(input.id)) throw new Error("SESSION_IMAGE_INVALID");
|
|
20712
|
+
const directory = sessionDirectory(workspaceRoot, input.sessionId, false);
|
|
20713
|
+
const metadataPath = import_node_path21.default.join(directory, `${input.id}.json`);
|
|
20714
|
+
const metadataStat = import_node_fs26.default.lstatSync(metadataPath);
|
|
20715
|
+
if (!metadataStat.isFile() || metadataStat.isSymbolicLink() || metadataStat.size > 4096) throw new Error("SESSION_IMAGE_INVALID");
|
|
20716
|
+
const image = JSON.parse(import_node_fs26.default.readFileSync(metadataPath, "utf8"));
|
|
20717
|
+
const extension = image.mimeType === "image/jpeg" ? ".jpg" : image.mimeType === "image/png" ? ".png" : image.mimeType === "image/webp" ? ".webp" : image.mimeType === "image/gif" ? ".gif" : "";
|
|
20718
|
+
if (!extension || image.id !== input.id || image.relativePath !== `.local/session-uploads/${input.sessionId}/${input.id}${extension}` || !/^[0-9a-f]{64}$/.test(image.sha256) || !Number.isSafeInteger(image.bytes) || image.bytes < 1 || image.bytes > 3932160) throw new Error("SESSION_IMAGE_INVALID");
|
|
20719
|
+
const filePath = import_node_path21.default.join(directory, `${input.id}${extension}`);
|
|
20720
|
+
const stat = import_node_fs26.default.lstatSync(filePath);
|
|
20721
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== image.bytes) throw new Error("SESSION_IMAGE_INVALID");
|
|
20722
|
+
const bytes = import_node_fs26.default.readFileSync(filePath);
|
|
20723
|
+
if (bytes.length !== image.bytes || import_node_crypto11.default.createHash("sha256").update(bytes).digest("hex") !== image.sha256) throw new Error("SESSION_IMAGE_INVALID");
|
|
20724
|
+
return { image, bytes };
|
|
19900
20725
|
}
|
|
19901
20726
|
};
|
|
19902
20727
|
}
|
|
19903
20728
|
|
|
19904
20729
|
// src/node/stores/node-user-question-store.ts
|
|
19905
|
-
var
|
|
20730
|
+
var import_node_fs27 = __toESM(require("node:fs"));
|
|
19906
20731
|
function createNodeUserQuestionStore(options) {
|
|
19907
20732
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19908
20733
|
const recordsFile = `${paths.questionsDir}/requests.jsonl`;
|
|
19909
20734
|
function ensureDir() {
|
|
19910
20735
|
const state = ensureNodeStateRoot(paths.root);
|
|
19911
|
-
|
|
20736
|
+
import_node_fs27.default.mkdirSync(state.questionsDir, { recursive: true });
|
|
19912
20737
|
}
|
|
19913
20738
|
function answersEqual(left, right) {
|
|
19914
20739
|
return JSON.stringify(left) === JSON.stringify(right);
|
|
@@ -19973,6 +20798,7 @@ function createNodeRuntimePorts(options) {
|
|
|
19973
20798
|
}
|
|
19974
20799
|
return {
|
|
19975
20800
|
hostMutationProtection: options.productMode === "chat" ? void 0 : createNodeHostMutationProtection(options),
|
|
20801
|
+
threadStore: createNodeThreadStore(options.stateRoot),
|
|
19976
20802
|
sessionStore: createNodeSessionStore({ ...storeOptions, productMode: options.productMode }),
|
|
19977
20803
|
checkpointStore: createNodeCheckpointStore(storeOptions),
|
|
19978
20804
|
transcriptStore: createNodeTranscriptStore(storeOptions),
|
|
@@ -19996,6 +20822,7 @@ function createNodeRuntimePorts(options) {
|
|
|
19996
20822
|
throw new NodeChatError("CHAT_ATTACHMENT_STORE_REQUIRED");
|
|
19997
20823
|
}
|
|
19998
20824
|
} : createNodeSessionResourceStore(options.workspaceRoot ?? options.cwd ?? process.cwd()),
|
|
20825
|
+
sessionImageStore: options.productMode === "chat" || !options.workspaceRoot ? void 0 : createNodeSessionImageStore(options.workspaceRoot),
|
|
19999
20826
|
userQuestionStore: createNodeUserQuestionStore(storeOptions),
|
|
20000
20827
|
/**
|
|
20001
20828
|
* Stage 2:Work 模式装配真实 SRT adapter(绑定 canonical workspaceRoot;tempRoot
|
|
@@ -20004,7 +20831,7 @@ function createNodeRuntimePorts(options) {
|
|
|
20004
20831
|
* Talk-Plan1022 S1:Windows 宿主执行模式装配宿主执行 port——不加载 SRT、不要求
|
|
20005
20832
|
* provision,进程调用经用户逐次审批后在宿主直接执行;macOS 装配保持不变。
|
|
20006
20833
|
*/
|
|
20007
|
-
sandboxPort: options.productMode === "chat" || options.workspaceRoot === void 0 ? (0,
|
|
20834
|
+
sandboxPort: options.productMode === "chat" || options.workspaceRoot === void 0 ? (0, import_core17.createUnavailableSandboxPort)() : process.platform === "win32" ? createNodeHostExecutionSandboxPort() : createNodeSandboxPort({
|
|
20008
20835
|
workspaceRoot: options.workspaceRoot,
|
|
20009
20836
|
stateRoot: options.stateRoot,
|
|
20010
20837
|
...options.sandboxTempRoot !== void 0 ? { tempRoot: options.sandboxTempRoot } : {}
|
|
@@ -20013,9 +20840,9 @@ function createNodeRuntimePorts(options) {
|
|
|
20013
20840
|
}
|
|
20014
20841
|
|
|
20015
20842
|
// src/node/stores/node-chat-attachment-store.ts
|
|
20016
|
-
var
|
|
20017
|
-
var
|
|
20018
|
-
var
|
|
20843
|
+
var import_node_fs28 = __toESM(require("node:fs"));
|
|
20844
|
+
var import_node_path22 = __toESM(require("node:path"));
|
|
20845
|
+
var import_node_crypto12 = require("node:crypto");
|
|
20019
20846
|
var CHAT_ATTACHMENT_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
20020
20847
|
var MAX_BYTES = 20 * 1024 * 1024;
|
|
20021
20848
|
var IMAGE_BYTES = 5 * 1024 * 1024;
|
|
@@ -20028,7 +20855,7 @@ function sessionKey(id) {
|
|
|
20028
20855
|
return id;
|
|
20029
20856
|
}
|
|
20030
20857
|
function digest(bytes) {
|
|
20031
|
-
return (0,
|
|
20858
|
+
return (0, import_node_crypto12.createHash)("sha256").update(bytes).digest("hex");
|
|
20032
20859
|
}
|
|
20033
20860
|
function detectMime(bytes) {
|
|
20034
20861
|
if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png";
|
|
@@ -20054,12 +20881,12 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20054
20881
|
const { paths, sessionStore } = options;
|
|
20055
20882
|
const now = options.now ?? Date.now;
|
|
20056
20883
|
const root = paths.attachmentsRoot;
|
|
20057
|
-
const dataRoot =
|
|
20058
|
-
const retiredRoot =
|
|
20059
|
-
const deletingRoot =
|
|
20060
|
-
const lock =
|
|
20884
|
+
const dataRoot = import_node_path22.default.join(root, "sessions");
|
|
20885
|
+
const retiredRoot = import_node_path22.default.join(root, "retired");
|
|
20886
|
+
const deletingRoot = import_node_path22.default.join(root, "deleting");
|
|
20887
|
+
const lock = import_node_path22.default.join(root, "lifecycle");
|
|
20061
20888
|
function ensure() {
|
|
20062
|
-
assertSafeNodePath(
|
|
20889
|
+
assertSafeNodePath(import_node_path22.default.dirname(paths.root), paths.root);
|
|
20063
20890
|
for (const directory of [root, dataRoot, retiredRoot, deletingRoot]) ensureChatDirectory(paths.root, directory);
|
|
20064
20891
|
assertSafeNodePath(root, `${lock}.lock`);
|
|
20065
20892
|
}
|
|
@@ -20081,9 +20908,9 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20081
20908
|
}
|
|
20082
20909
|
function isSessionDeleting(sessionId) {
|
|
20083
20910
|
try {
|
|
20084
|
-
const target =
|
|
20911
|
+
const target = import_node_path22.default.join(deletingRoot, `${sessionKey(sessionId)}.json`);
|
|
20085
20912
|
assertSafeNodePath(root, target);
|
|
20086
|
-
return
|
|
20913
|
+
return import_node_fs28.default.existsSync(target);
|
|
20087
20914
|
} catch (error) {
|
|
20088
20915
|
throw toNodeBoundaryError(error, "CHAT_ATTACHMENT_UNAVAILABLE");
|
|
20089
20916
|
}
|
|
@@ -20100,16 +20927,16 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20100
20927
|
if (session?.productMode !== "chat" || !["none", "web"].includes(session.chatRetrievalMode ?? "")) throw new NodeChatError("CHAT_UPLOAD_MODE_MISMATCH");
|
|
20101
20928
|
}
|
|
20102
20929
|
function records(sessionId) {
|
|
20103
|
-
const directory =
|
|
20930
|
+
const directory = import_node_path22.default.join(dataRoot, sessionKey(sessionId));
|
|
20104
20931
|
assertSafeNodePath(root, directory);
|
|
20105
|
-
if (!
|
|
20932
|
+
if (!import_node_fs28.default.existsSync(directory)) return [];
|
|
20106
20933
|
const result = [];
|
|
20107
|
-
for (const ref of
|
|
20934
|
+
for (const ref of import_node_fs28.default.readdirSync(directory)) {
|
|
20108
20935
|
if (!opaque.test(ref)) unavailable();
|
|
20109
|
-
const target =
|
|
20936
|
+
const target = import_node_path22.default.join(directory, ref, "metadata.json");
|
|
20110
20937
|
assertSafeNodePath(root, target);
|
|
20111
|
-
if (!
|
|
20112
|
-
const record = JSON.parse(
|
|
20938
|
+
if (!import_node_fs28.default.statSync(target).isFile() || import_node_fs28.default.statSync(target).size > 16384) unavailable();
|
|
20939
|
+
const record = JSON.parse(import_node_fs28.default.readFileSync(target, "utf8"));
|
|
20113
20940
|
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();
|
|
20114
20941
|
for (const page of record.pages) if (!opaque.test(page.ref)) unavailable();
|
|
20115
20942
|
result.push(record);
|
|
@@ -20120,7 +20947,7 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20120
20947
|
return { ref: record.ref, sessionId: record.sessionId, kind: record.kind, expiresAt: record.expiresAt };
|
|
20121
20948
|
}
|
|
20122
20949
|
function active(record) {
|
|
20123
|
-
return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !
|
|
20950
|
+
return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !import_node_fs28.default.existsSync(import_node_path22.default.join(retiredRoot, `${record.ref}.json`));
|
|
20124
20951
|
}
|
|
20125
20952
|
function sanitizeSession(session) {
|
|
20126
20953
|
try {
|
|
@@ -20159,17 +20986,17 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20159
20986
|
return !opaque.test(ref);
|
|
20160
20987
|
}
|
|
20161
20988
|
)) unavailable();
|
|
20162
|
-
const directory =
|
|
20989
|
+
const directory = import_node_path22.default.join(dataRoot, item.sessionId, item.ref);
|
|
20163
20990
|
assertSafeNodePath(root, directory);
|
|
20164
|
-
|
|
20991
|
+
import_node_fs28.default.rmSync(directory, { recursive: true, force: true });
|
|
20165
20992
|
await removePresentationRefs(item.sessionId, item.refs);
|
|
20166
|
-
|
|
20993
|
+
import_node_fs28.default.rmSync(import_node_path22.default.join(retiredRoot, `${item.ref}.json`), { force: true });
|
|
20167
20994
|
}
|
|
20168
20995
|
async function retire(record) {
|
|
20169
20996
|
const item = { sessionId: record.sessionId, ref: record.ref, refs: [record.ref, ...record.pages.map(function pageRef(page) {
|
|
20170
20997
|
return page.ref;
|
|
20171
20998
|
})] };
|
|
20172
|
-
atomicReplace(
|
|
20999
|
+
atomicReplace(import_node_path22.default.join(retiredRoot, `${record.ref}.json`), JSON.stringify(item));
|
|
20173
21000
|
await finishRetirement(item);
|
|
20174
21001
|
}
|
|
20175
21002
|
async function put(input) {
|
|
@@ -20201,32 +21028,32 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20201
21028
|
await requireSession(input.sessionId);
|
|
20202
21029
|
const createdAt = now();
|
|
20203
21030
|
if (!Number.isSafeInteger(createdAt) || createdAt < 0) unavailable();
|
|
20204
|
-
const ref = (0,
|
|
20205
|
-
const parent =
|
|
21031
|
+
const ref = (0, import_node_crypto12.randomUUID)();
|
|
21032
|
+
const parent = import_node_path22.default.join(dataRoot, sessionKey(input.sessionId));
|
|
20206
21033
|
ensureChatDirectory(root, parent);
|
|
20207
|
-
const staging =
|
|
21034
|
+
const staging = import_node_path22.default.join(root, `staging-${ref}`);
|
|
20208
21035
|
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: [] };
|
|
20209
21036
|
try {
|
|
20210
21037
|
ensureChatDirectory(root, staging);
|
|
20211
|
-
|
|
21038
|
+
import_node_fs28.default.writeFileSync(import_node_path22.default.join(staging, "content"), bytes, { flag: "wx", mode: 384 });
|
|
20212
21039
|
let pageBytes = 0;
|
|
20213
21040
|
for (const inputPage of parsed?.pages ?? []) {
|
|
20214
21041
|
const page = Buffer.from(inputPage);
|
|
20215
21042
|
const type2 = detectMime(page);
|
|
20216
21043
|
pageBytes += page.length;
|
|
20217
21044
|
if (!type2.startsWith("image/") || !page.length || page.length > IMAGE_BYTES || pageBytes > MAX_BYTES) unavailable();
|
|
20218
|
-
const pageRef = (0,
|
|
20219
|
-
|
|
21045
|
+
const pageRef = (0, import_node_crypto12.randomUUID)();
|
|
21046
|
+
import_node_fs28.default.writeFileSync(import_node_path22.default.join(staging, pageRef), page, { flag: "wx", mode: 384 });
|
|
20220
21047
|
record.pages.push({ ref: pageRef, mimeType: type2, byteLength: page.length, sha256: digest(page) });
|
|
20221
21048
|
}
|
|
20222
|
-
if (parsed)
|
|
20223
|
-
|
|
21049
|
+
if (parsed) import_node_fs28.default.writeFileSync(import_node_path22.default.join(staging, "parsed.json"), JSON.stringify({ text: parsed.text.slice(0, 16e3) }), { flag: "wx", mode: 384 });
|
|
21050
|
+
import_node_fs28.default.writeFileSync(import_node_path22.default.join(staging, "metadata.json"), JSON.stringify(record), { flag: "wx", mode: 384 });
|
|
20224
21051
|
checkSignal(input.signal);
|
|
20225
|
-
|
|
21052
|
+
import_node_fs28.default.renameSync(staging, import_node_path22.default.join(parent, ref));
|
|
20226
21053
|
const { pages: _pages, ...view } = record;
|
|
20227
21054
|
return view;
|
|
20228
21055
|
} finally {
|
|
20229
|
-
|
|
21056
|
+
import_node_fs28.default.rmSync(staging, { recursive: true, force: true });
|
|
20230
21057
|
}
|
|
20231
21058
|
}, input.signal);
|
|
20232
21059
|
} catch (error) {
|
|
@@ -20268,10 +21095,10 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20268
21095
|
return locked(async function readParsed() {
|
|
20269
21096
|
const { record, page } = await find3(sessionId, ref);
|
|
20270
21097
|
if (page || record.kind !== "document") unavailable();
|
|
20271
|
-
const target =
|
|
21098
|
+
const target = import_node_path22.default.join(dataRoot, sessionId, ref, "parsed.json");
|
|
20272
21099
|
assertSafeNodePath(root, target);
|
|
20273
|
-
if (
|
|
20274
|
-
const parsed = JSON.parse(
|
|
21100
|
+
if (import_node_fs28.default.statSync(target).size > 1e5) unavailable();
|
|
21101
|
+
const parsed = JSON.parse(import_node_fs28.default.readFileSync(target, "utf8"));
|
|
20275
21102
|
if (typeof parsed.text !== "string") unavailable();
|
|
20276
21103
|
return { text: parsed.text.slice(0, 16e3), pageImages: record.pages.map(function pageGrant(item) {
|
|
20277
21104
|
return grant({ ...record, ref: item.ref, kind: "image" });
|
|
@@ -20281,44 +21108,44 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20281
21108
|
async function readBytes(sessionId, ref, signal) {
|
|
20282
21109
|
return locked(async function readContent() {
|
|
20283
21110
|
const { record, page } = await find3(sessionId, ref);
|
|
20284
|
-
const target =
|
|
21111
|
+
const target = import_node_path22.default.join(dataRoot, sessionId, record.ref, page?.ref ?? "content");
|
|
20285
21112
|
assertSafeNodePath(root, target);
|
|
20286
21113
|
const metadata = page ?? record;
|
|
20287
|
-
if (
|
|
20288
|
-
const bytes =
|
|
21114
|
+
if (import_node_fs28.default.statSync(target).size !== metadata.byteLength || metadata.byteLength > MAX_BYTES) unavailable();
|
|
21115
|
+
const bytes = import_node_fs28.default.readFileSync(target);
|
|
20289
21116
|
if (digest(bytes) !== metadata.sha256) unavailable();
|
|
20290
21117
|
return { bytes: new Uint8Array(bytes), mimeType: metadata.mimeType };
|
|
20291
21118
|
}, signal);
|
|
20292
21119
|
}
|
|
20293
21120
|
async function deleteBySession(sessionId) {
|
|
20294
21121
|
await locked(async function deleteSessionAttachments() {
|
|
20295
|
-
atomicReplace(
|
|
21122
|
+
atomicReplace(import_node_path22.default.join(deletingRoot, `${sessionKey(sessionId)}.json`), JSON.stringify({ sessionId }));
|
|
20296
21123
|
for (const record of records(sessionId)) await retire(record);
|
|
20297
21124
|
await removePresentationRefs(sessionId);
|
|
20298
|
-
|
|
21125
|
+
import_node_fs28.default.rmSync(import_node_path22.default.join(dataRoot, sessionId), { recursive: true, force: true });
|
|
20299
21126
|
}, void 0, "CHAT_ATTACHMENT_CLEANUP_FAILED");
|
|
20300
21127
|
}
|
|
20301
21128
|
async function cleanupExpired(input = {}) {
|
|
20302
21129
|
const limit = input.limit ?? 32;
|
|
20303
21130
|
if (!Number.isInteger(limit) || limit < 1 || limit > 128) throw new NodeChatError("CHAT_ATTACHMENT_CLEANUP_FAILED");
|
|
20304
21131
|
return locked(async function cleanupBatch() {
|
|
20305
|
-
for (const file of
|
|
21132
|
+
for (const file of import_node_fs28.default.readdirSync(root)) {
|
|
20306
21133
|
if (!/^staging-[0-9a-f-]{36}$/.test(file)) continue;
|
|
20307
|
-
const target =
|
|
21134
|
+
const target = import_node_path22.default.join(root, file);
|
|
20308
21135
|
assertSafeNodePath(root, target);
|
|
20309
|
-
|
|
21136
|
+
import_node_fs28.default.rmSync(target, { recursive: true, force: true });
|
|
20310
21137
|
}
|
|
20311
|
-
for (const file of
|
|
21138
|
+
for (const file of import_node_fs28.default.readdirSync(retiredRoot)) {
|
|
20312
21139
|
if (!file.endsWith(".json")) continue;
|
|
20313
|
-
const target =
|
|
21140
|
+
const target = import_node_path22.default.join(retiredRoot, file);
|
|
20314
21141
|
assertSafeNodePath(root, target);
|
|
20315
21142
|
checkSignal(input.signal);
|
|
20316
|
-
const item = JSON.parse(
|
|
21143
|
+
const item = JSON.parse(import_node_fs28.default.readFileSync(target, "utf8"));
|
|
20317
21144
|
if (file !== `${item.ref}.json`) unavailable();
|
|
20318
21145
|
await finishRetirement(item);
|
|
20319
21146
|
}
|
|
20320
21147
|
const expired = [];
|
|
20321
|
-
for (const sessionId of
|
|
21148
|
+
for (const sessionId of import_node_fs28.default.readdirSync(dataRoot)) {
|
|
20322
21149
|
for (const record of records(sessionId)) if (record.expiresAt <= now() || isSessionDeleting(sessionId)) expired.push(record);
|
|
20323
21150
|
}
|
|
20324
21151
|
expired.sort(function oldestFirst(left, right) {
|
|
@@ -20428,6 +21255,7 @@ function createNodeChatCapabilityLoader(options) {
|
|
|
20428
21255
|
}
|
|
20429
21256
|
const attachments = await storage.attachments.list(binding.sessionId);
|
|
20430
21257
|
return {
|
|
21258
|
+
...(binding.retrievalMode === "none" || binding.retrievalMode === "web") && options.interactiveUi === true ? { interactiveUi: true } : {},
|
|
20431
21259
|
/** 目录只含授权字段,实际引用仍由 Core 的冻结交集和 Store 复查约束。 */
|
|
20432
21260
|
attachments: attachments.map(function grant(item) {
|
|
20433
21261
|
return { ref: item.ref, displayName: item.displayName, sessionId: item.sessionId, kind: item.kind, expiresAt: item.expiresAt };
|
|
@@ -20552,8 +21380,8 @@ function createNodeRagRuntime(options) {
|
|
|
20552
21380
|
}
|
|
20553
21381
|
|
|
20554
21382
|
// src/node/settings/node-settings-writer.ts
|
|
20555
|
-
var
|
|
20556
|
-
var
|
|
21383
|
+
var import_node_fs29 = __toESM(require("node:fs"));
|
|
21384
|
+
var import_core18 = require("@autopilot-agent/core");
|
|
20557
21385
|
var CONFIG_KEY_ALLOWLIST = /* @__PURE__ */ new Set([
|
|
20558
21386
|
"model",
|
|
20559
21387
|
"effortLevel",
|
|
@@ -20565,9 +21393,9 @@ function createNodeSettingsWriter(options = {}) {
|
|
|
20565
21393
|
}
|
|
20566
21394
|
function readScope(scope, workspaceRoot) {
|
|
20567
21395
|
const filePath = getPaths(workspaceRoot)[scope];
|
|
20568
|
-
if (!
|
|
21396
|
+
if (!import_node_fs29.default.existsSync(filePath)) return {};
|
|
20569
21397
|
try {
|
|
20570
|
-
const parsed = JSON.parse(
|
|
21398
|
+
const parsed = JSON.parse(import_node_fs29.default.readFileSync(filePath, "utf8"));
|
|
20571
21399
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? { ...parsed } : {};
|
|
20572
21400
|
} catch {
|
|
20573
21401
|
return {};
|
|
@@ -20598,7 +21426,7 @@ function createNodeSettingsWriter(options = {}) {
|
|
|
20598
21426
|
cursor = cursor[part];
|
|
20599
21427
|
}
|
|
20600
21428
|
cursor[parts[parts.length - 1]] = parsedValue;
|
|
20601
|
-
(0,
|
|
21429
|
+
(0, import_core18.resolveAutopilotSettings)([{ scope, value: target }]);
|
|
20602
21430
|
atomicReplace(getPaths(workspaceRoot)[scope], JSON.stringify(target, null, 2));
|
|
20603
21431
|
return toSafeView(target);
|
|
20604
21432
|
}
|
|
@@ -20663,9 +21491,9 @@ function parseConfigValue(key2, rawValue) {
|
|
|
20663
21491
|
}
|
|
20664
21492
|
|
|
20665
21493
|
// src/node/settings/node-user-settings-service.ts
|
|
20666
|
-
var
|
|
20667
|
-
var
|
|
20668
|
-
var
|
|
21494
|
+
var import_node_crypto13 = require("node:crypto");
|
|
21495
|
+
var import_node_fs30 = __toESM(require("node:fs"));
|
|
21496
|
+
var import_core19 = require("@autopilot-agent/core");
|
|
20669
21497
|
var RAG_ROLE_CONTRACT = Object.freeze({
|
|
20670
21498
|
textRerank: { provider: "bailian", key: "RAG_TEXT_RERANK_API_KEY", dimension: false },
|
|
20671
21499
|
visionRerank: { provider: "bailian", key: "RAG_VISION_RERANK_API_KEY", dimension: false },
|
|
@@ -20686,7 +21514,7 @@ function splitDiagnostics(diagnostics) {
|
|
|
20686
21514
|
const blocking = [];
|
|
20687
21515
|
const permissions = [];
|
|
20688
21516
|
for (const diagnostic of diagnostics) {
|
|
20689
|
-
if ((0,
|
|
21517
|
+
if ((0, import_core19.isExternalPermissionDiagnostic)(diagnostic)) permissions.push(safeDiagnostic(diagnostic));
|
|
20690
21518
|
else blocking.push(diagnostic);
|
|
20691
21519
|
}
|
|
20692
21520
|
return { blocking, permissions };
|
|
@@ -20702,14 +21530,14 @@ function parseApiKey(value) {
|
|
|
20702
21530
|
return typeof value === "string" && value.length <= 4096 && !/[\s\u0000-\u001f\u007f]/u.test(value) ? value : void 0;
|
|
20703
21531
|
}
|
|
20704
21532
|
function revisionOf(content) {
|
|
20705
|
-
return (0,
|
|
21533
|
+
return (0, import_node_crypto13.createHash)("sha256").update(content).digest("hex");
|
|
20706
21534
|
}
|
|
20707
21535
|
function readUserSettings(settingsPath) {
|
|
20708
|
-
if (!
|
|
21536
|
+
if (!import_node_fs30.default.existsSync(settingsPath)) return { raw: {}, original: "" };
|
|
20709
21537
|
try {
|
|
20710
|
-
const stat =
|
|
21538
|
+
const stat = import_node_fs30.default.lstatSync(settingsPath);
|
|
20711
21539
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw new Error();
|
|
20712
|
-
const original =
|
|
21540
|
+
const original = import_node_fs30.default.readFileSync(settingsPath, "utf8");
|
|
20713
21541
|
const raw = JSON.parse(original);
|
|
20714
21542
|
if (!isRecord4(raw) || raw.env !== void 0 && !isRecord4(raw.env)) throw new Error();
|
|
20715
21543
|
return { raw: { ...raw }, original };
|
|
@@ -20770,7 +21598,7 @@ function removeLegacyPrimaryRoutes(raw, environment) {
|
|
|
20770
21598
|
for (const key2 of removedKeys) if (!hasCredentialReference(raw, key2)) delete environment[key2];
|
|
20771
21599
|
}
|
|
20772
21600
|
function normalizeMainInput(input) {
|
|
20773
|
-
const baseUrl = (0,
|
|
21601
|
+
const baseUrl = (0, import_core19.normalizeProviderBaseUrl)(input.baseUrl);
|
|
20774
21602
|
const model = parseSettingString(input.model);
|
|
20775
21603
|
const apiKey = parseApiKey(input.apiKey);
|
|
20776
21604
|
const availableModels = input.availableModels?.map(function parseModel(value) {
|
|
@@ -20792,9 +21620,9 @@ function applyMainCategory(raw, input) {
|
|
|
20792
21620
|
return candidate.value;
|
|
20793
21621
|
}))];
|
|
20794
21622
|
if (!normalized.apiKey && distinct.length > 1) throw new NodeUserSettingsError("SETTINGS_MIGRATION_CONFLICT");
|
|
20795
|
-
const previous = (0,
|
|
21623
|
+
const previous = (0, import_core19.resolveAutopilotSettings)([{ scope: "user", value: raw }]);
|
|
20796
21624
|
const previousRoute = previous.modelRef && previous.providerRoutes[previous.modelRef.provider];
|
|
20797
|
-
const previousBaseUrl = (0,
|
|
21625
|
+
const previousBaseUrl = (0, import_core19.normalizeProviderBaseUrl)(previousRoute?.baseUrl ?? previous.firstParty.baseUrl);
|
|
20798
21626
|
const officialDeepSeekMigration = previousBaseUrl === "https://api.deepseek.com" && normalized.baseUrl === "https://api.deepseek.com/anthropic";
|
|
20799
21627
|
if (!normalized.apiKey && previousBaseUrl !== normalized.baseUrl && !officialDeepSeekMigration) throw new NodeUserSettingsError("SETTINGS_KEY_REQUIRED");
|
|
20800
21628
|
const apiKey = normalized.apiKey ?? distinct[0];
|
|
@@ -20835,10 +21663,10 @@ function applyWebSearch(raw, input) {
|
|
|
20835
21663
|
return;
|
|
20836
21664
|
}
|
|
20837
21665
|
const provider = input.provider;
|
|
20838
|
-
const baseUrl = (0,
|
|
21666
|
+
const baseUrl = (0, import_core19.normalizeProviderBaseUrl)(input.baseUrl);
|
|
20839
21667
|
const model = parseSettingString(input.model);
|
|
20840
21668
|
const environment = { ...isRecord4(raw.env) ? raw.env : {} };
|
|
20841
|
-
const mainBaseUrl = (0,
|
|
21669
|
+
const mainBaseUrl = (0, import_core19.normalizeProviderBaseUrl)(environment.ANTHROPIC_BASE_URL);
|
|
20842
21670
|
const canReuseMainKey = mainBaseUrl === "https://api.deepseek.com/anthropic" && Boolean(readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY"));
|
|
20843
21671
|
if (input.useMainKey) {
|
|
20844
21672
|
if (!canReuseMainKey) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
@@ -20853,7 +21681,7 @@ function applyWebSearch(raw, input) {
|
|
|
20853
21681
|
const apiKey = parseApiKey(input.apiKey);
|
|
20854
21682
|
const current = isRecord4(raw.webSearch) ? raw.webSearch : void 0;
|
|
20855
21683
|
const currentRef = current && isRecord4(current.credentialRef) ? current.credentialRef : void 0;
|
|
20856
|
-
const sameConnection = current?.provider === provider && (0,
|
|
21684
|
+
const sameConnection = current?.provider === provider && (0, import_core19.normalizeProviderBaseUrl)(current?.baseUrl) === baseUrl;
|
|
20857
21685
|
const preservedKeyName = sameConnection ? parseSettingString(currentRef?.key) : void 0;
|
|
20858
21686
|
const preservedKey = readEnvironmentKey(environment, preservedKeyName);
|
|
20859
21687
|
if (provider !== "deepseek" && provider !== "openai-compatible" && provider !== "xiaomi-mimo" || !baseUrl || !model || !apiKey && !preservedKey) {
|
|
@@ -20872,7 +21700,7 @@ function applyRagRole(raw, role, input) {
|
|
|
20872
21700
|
delete rag[role];
|
|
20873
21701
|
delete environment[contract.key];
|
|
20874
21702
|
} else {
|
|
20875
|
-
const baseUrl = (0,
|
|
21703
|
+
const baseUrl = (0, import_core19.normalizeProviderBaseUrl)(input.baseUrl);
|
|
20876
21704
|
const model = parseSettingString(input.model);
|
|
20877
21705
|
const apiKey = parseApiKey(input.apiKey);
|
|
20878
21706
|
const current = isRecord4(rag[role]) ? rag[role] : void 0;
|
|
@@ -20897,7 +21725,7 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20897
21725
|
const current = readUserSettings(settingsPath);
|
|
20898
21726
|
assertRevision(current.original, revision);
|
|
20899
21727
|
update2(current.raw);
|
|
20900
|
-
const { blocking } = splitDiagnostics((0,
|
|
21728
|
+
const { blocking } = splitDiagnostics((0, import_core19.resolveAutopilotSettings)([{ scope: "user", value: current.raw }]).diagnostics);
|
|
20901
21729
|
if (blocking.length > 0) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID", safeDiagnostic(blocking[0]));
|
|
20902
21730
|
const content = `${JSON.stringify(current.raw, null, 2)}
|
|
20903
21731
|
`;
|
|
@@ -20911,7 +21739,7 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20911
21739
|
const maintained = ["deepseek-v4-pro[1m]", "deepseek-v4-flash"];
|
|
20912
21740
|
const current = readUserSettings(settingsPath);
|
|
20913
21741
|
const environment = isRecord4(current.raw.env) ? current.raw.env : {};
|
|
20914
|
-
const baseUrl = (0,
|
|
21742
|
+
const baseUrl = (0, import_core19.normalizeProviderBaseUrl)(environment.ANTHROPIC_BASE_URL);
|
|
20915
21743
|
const apiKey = readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY");
|
|
20916
21744
|
if (baseUrl !== "https://api.deepseek.com/anthropic" || !apiKey) return { models: maintained, source: "maintained" };
|
|
20917
21745
|
try {
|
|
@@ -20934,7 +21762,7 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20934
21762
|
const current = readUserSettings(settingsPath);
|
|
20935
21763
|
const raw = current.raw;
|
|
20936
21764
|
const environment = isRecord4(raw.env) ? raw.env : {};
|
|
20937
|
-
const resolved = (0,
|
|
21765
|
+
const resolved = (0, import_core19.resolveAutopilotSettings)([{ scope: "user", value: raw }]);
|
|
20938
21766
|
const { blocking, permissions } = splitDiagnostics(resolved.diagnostics);
|
|
20939
21767
|
if (blocking.length > 0) throw new NodeUserSettingsError("SETTINGS_INVALID", safeDiagnostic(blocking[0]));
|
|
20940
21768
|
const mainBaseUrl = resolved.firstParty.baseUrl ?? "https://api.deepseek.com/anthropic";
|
|
@@ -21019,36 +21847,36 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
21019
21847
|
}
|
|
21020
21848
|
|
|
21021
21849
|
// src/node/capabilities/memory-retriever.ts
|
|
21022
|
-
var
|
|
21023
|
-
var
|
|
21024
|
-
var
|
|
21850
|
+
var import_node_crypto14 = __toESM(require("node:crypto"));
|
|
21851
|
+
var import_node_fs31 = __toESM(require("node:fs"));
|
|
21852
|
+
var import_node_path23 = __toESM(require("node:path"));
|
|
21025
21853
|
function getNodeMemoryWorkspaceId(workspaceRoot) {
|
|
21026
|
-
return
|
|
21854
|
+
return import_node_crypto14.default.createHash("sha256").update(import_node_fs31.default.realpathSync.native(workspaceRoot).toLowerCase()).digest("hex").slice(0, 24);
|
|
21027
21855
|
}
|
|
21028
21856
|
function getNodeMemoryDirectory(stateRoot, workspaceRoot) {
|
|
21029
|
-
return
|
|
21857
|
+
return import_node_path23.default.join(import_node_path23.default.resolve(stateRoot), "memory", getNodeMemoryWorkspaceId(workspaceRoot));
|
|
21030
21858
|
}
|
|
21031
21859
|
function getLegacyWebMemoryDirectory(workspaceRoot, cwd = process.cwd()) {
|
|
21032
|
-
return
|
|
21860
|
+
return import_node_path23.default.join(import_node_path23.default.resolve(cwd), ".local", "agent", "workspaces", getNodeMemoryWorkspaceId(workspaceRoot), "memory");
|
|
21033
21861
|
}
|
|
21034
21862
|
function retrieveNodeMemories(_stateRoot, _workspaceRoot, _query, _maxItems = 5) {
|
|
21035
21863
|
return [];
|
|
21036
21864
|
}
|
|
21037
21865
|
|
|
21038
21866
|
// src/node/trust-policy.ts
|
|
21039
|
-
var
|
|
21040
|
-
var
|
|
21867
|
+
var import_node_fs32 = __toESM(require("node:fs"));
|
|
21868
|
+
var import_node_path24 = __toESM(require("node:path"));
|
|
21041
21869
|
function createNodeTrustStore(options) {
|
|
21042
21870
|
const trustRoot = resolveNodeTrustRoot({ stateRoot: options.stateRoot, trustRoot: options.trustRoot });
|
|
21043
|
-
const trustFile =
|
|
21871
|
+
const trustFile = import_node_path24.default.join(trustRoot, "trust.json");
|
|
21044
21872
|
const now = options.now ?? (() => Date.now());
|
|
21045
21873
|
function ensureDir() {
|
|
21046
|
-
|
|
21874
|
+
import_node_fs32.default.mkdirSync(trustRoot, { recursive: true });
|
|
21047
21875
|
}
|
|
21048
21876
|
function loadStore() {
|
|
21049
|
-
if (!
|
|
21877
|
+
if (!import_node_fs32.default.existsSync(trustFile)) return { version: 1, workspaces: {} };
|
|
21050
21878
|
try {
|
|
21051
|
-
const parsed = JSON.parse(
|
|
21879
|
+
const parsed = JSON.parse(import_node_fs32.default.readFileSync(trustFile, "utf8"));
|
|
21052
21880
|
if (parsed.version !== 1 || !parsed.workspaces || typeof parsed.workspaces !== "object") return { version: 1, workspaces: {} };
|
|
21053
21881
|
return { version: 1, workspaces: parsed.workspaces };
|
|
21054
21882
|
} catch {
|
|
@@ -21150,16 +21978,16 @@ function createNodeTrustPolicy(options) {
|
|
|
21150
21978
|
}
|
|
21151
21979
|
|
|
21152
21980
|
// src/node/workspace-registry.ts
|
|
21153
|
-
var
|
|
21154
|
-
var
|
|
21981
|
+
var import_node_fs33 = __toESM(require("node:fs"));
|
|
21982
|
+
var import_node_path25 = __toESM(require("node:path"));
|
|
21155
21983
|
function createNodeWorkspaceRegistry(options = {}) {
|
|
21156
21984
|
const globalStateRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: options.cwd });
|
|
21157
|
-
const registryPath =
|
|
21985
|
+
const registryPath = import_node_path25.default.join(globalStateRoot, "workspace-registry.json");
|
|
21158
21986
|
const now = options.now ?? (() => Date.now());
|
|
21159
21987
|
function load2() {
|
|
21160
|
-
if (!
|
|
21988
|
+
if (!import_node_fs33.default.existsSync(registryPath)) return [];
|
|
21161
21989
|
try {
|
|
21162
|
-
const parsed = JSON.parse(
|
|
21990
|
+
const parsed = JSON.parse(import_node_fs33.default.readFileSync(registryPath, "utf8"));
|
|
21163
21991
|
if (!Array.isArray(parsed)) return [];
|
|
21164
21992
|
return parsed.filter(function isEntry(value) {
|
|
21165
21993
|
return Boolean(value) && typeof value === "object" && typeof value.workspaceId === "string" && typeof value.workspaceRoot === "string" && typeof value.displayName === "string" && typeof value.lastOpenedAt === "number";
|
|
@@ -21182,7 +22010,7 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21182
22010
|
const next = {
|
|
21183
22011
|
workspaceId,
|
|
21184
22012
|
workspaceRoot: canonicalRoot,
|
|
21185
|
-
displayName:
|
|
22013
|
+
displayName: import_node_path25.default.basename(canonicalRoot) || canonicalRoot,
|
|
21186
22014
|
lastOpenedAt: now()
|
|
21187
22015
|
};
|
|
21188
22016
|
const entries2 = load2().filter(function removeExisting(entry) {
|
|
@@ -21203,12 +22031,467 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21203
22031
|
}
|
|
21204
22032
|
return { list: load2, get, register, remove: remove2 };
|
|
21205
22033
|
}
|
|
22034
|
+
|
|
22035
|
+
// src/node/thread-runner.ts
|
|
22036
|
+
var import_core20 = require("@autopilot-agent/core");
|
|
22037
|
+
var import_node_crypto15 = require("node:crypto");
|
|
22038
|
+
function createNodeThreadRunner(options) {
|
|
22039
|
+
const delivery = options.delivery;
|
|
22040
|
+
const ownerId = delivery.ownerId;
|
|
22041
|
+
const pollIntervalMs = options.pollIntervalMs ?? 250;
|
|
22042
|
+
const staleMs = options.staleMs ?? 45e3;
|
|
22043
|
+
const heartbeatMs = options.heartbeatMs ?? Math.max(200, Math.min(5e3, Math.floor(staleMs / 3)));
|
|
22044
|
+
const reconcileEveryMs = options.reconcileEveryMs ?? 3e3;
|
|
22045
|
+
const active = /* @__PURE__ */ new Map();
|
|
22046
|
+
let timer;
|
|
22047
|
+
let ticking = false;
|
|
22048
|
+
let stopped = false;
|
|
22049
|
+
let lastReconcileAt = 0;
|
|
22050
|
+
let running = false;
|
|
22051
|
+
let kicked = false;
|
|
22052
|
+
let idleDelayMs = pollIntervalMs;
|
|
22053
|
+
async function hasFreshLease(threadId) {
|
|
22054
|
+
const checkpoint = await options.ports.checkpointStore.getLatest(threadId);
|
|
22055
|
+
return Boolean(checkpoint && checkpoint.status === "running" && checkpoint.lease && Date.now() - checkpoint.lease.heartbeatAt <= delivery.leaseStaleMs);
|
|
22056
|
+
}
|
|
22057
|
+
function activeMessageIds() {
|
|
22058
|
+
return [...active.values()].filter(function deliveryRecord(record) {
|
|
22059
|
+
return !record.external && Boolean(record.messageId);
|
|
22060
|
+
}).map(function id(record) {
|
|
22061
|
+
return record.messageId;
|
|
22062
|
+
});
|
|
22063
|
+
}
|
|
22064
|
+
async function safeTick(reconcileFirst = false) {
|
|
22065
|
+
if (ticking || stopped) return;
|
|
22066
|
+
if (timer) clearTimeout(timer);
|
|
22067
|
+
timer = void 0;
|
|
22068
|
+
kicked = false;
|
|
22069
|
+
ticking = true;
|
|
22070
|
+
try {
|
|
22071
|
+
const snapshot = await delivery.querySnapshot();
|
|
22072
|
+
if (reconcileFirst || Date.now() - lastReconcileAt >= reconcileEveryMs) {
|
|
22073
|
+
lastReconcileAt = Date.now();
|
|
22074
|
+
await delivery.reconcile({ staleMs, activeMessageIds: activeMessageIds(), snapshot });
|
|
22075
|
+
}
|
|
22076
|
+
await applyInterrupts(snapshot);
|
|
22077
|
+
await applyResumes(snapshot);
|
|
22078
|
+
await applyInteractionContinuations(snapshot);
|
|
22079
|
+
const claimed = await delivery.claimDeliveries({ snapshot, activeThreads: [...active.values()].filter(function controllable(record) {
|
|
22080
|
+
return record.ready;
|
|
22081
|
+
}).map(function thread(record) {
|
|
22082
|
+
return record.threadId;
|
|
22083
|
+
}) });
|
|
22084
|
+
for (const item of claimed) startDelivery(item);
|
|
22085
|
+
idleDelayMs = active.size || claimed.length ? pollIntervalMs : Math.min(Math.max(pollIntervalMs, 2e3), idleDelayMs * 2);
|
|
22086
|
+
} catch (error) {
|
|
22087
|
+
options.onError?.(error);
|
|
22088
|
+
} finally {
|
|
22089
|
+
ticking = false;
|
|
22090
|
+
if (running && !stopped) {
|
|
22091
|
+
timer = setTimeout(function poll() {
|
|
22092
|
+
void safeTick();
|
|
22093
|
+
}, kicked ? 0 : idleDelayMs);
|
|
22094
|
+
timer.unref?.();
|
|
22095
|
+
}
|
|
22096
|
+
}
|
|
22097
|
+
}
|
|
22098
|
+
async function applyInterrupts(snapshot) {
|
|
22099
|
+
for (const intent of await delivery.pendingInterrupts(snapshot)) {
|
|
22100
|
+
const task = active.get(intent.threadId);
|
|
22101
|
+
if (!task || !task.ready || task.turnId !== intent.expectedTurnId) {
|
|
22102
|
+
const turn = await options.ports.turnStore.get(intent.expectedTurnId);
|
|
22103
|
+
if (turn && (turn.status === "waiting_approval" || turn.status === "waiting_user_input")) {
|
|
22104
|
+
const [session, latest, checkpoint] = await Promise.all([options.ports.sessionStore.get(intent.threadId), options.ports.turnStore.getLatest(intent.threadId), options.ports.checkpointStore.getLatest(intent.threadId)]);
|
|
22105
|
+
const checkpointStatus = turn.status === "waiting_approval" ? "awaiting_approval" : "awaiting_user_input";
|
|
22106
|
+
if (!session || turn.sessionId !== intent.threadId || session.status !== turn.status || session.activeTurnId && session.activeTurnId !== intent.expectedTurnId || latest?.id !== intent.expectedTurnId || checkpoint?.turnId !== intent.expectedTurnId || checkpoint.status !== checkpointStatus) {
|
|
22107
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22108
|
+
continue;
|
|
22109
|
+
}
|
|
22110
|
+
try {
|
|
22111
|
+
await options.runtime.turns.cancel({ sessionId: intent.threadId, turnId: intent.expectedTurnId });
|
|
22112
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: true });
|
|
22113
|
+
} catch {
|
|
22114
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22115
|
+
}
|
|
22116
|
+
continue;
|
|
22117
|
+
}
|
|
22118
|
+
const terminal = turn && turn.status !== "running" && turn.status !== "waiting_approval" && turn.status !== "waiting_user_input";
|
|
22119
|
+
if (terminal) await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22120
|
+
else if (!turn && !await hasFreshLease(intent.threadId)) {
|
|
22121
|
+
const control = await delivery.readGroup(intent.groupId);
|
|
22122
|
+
const recorded = control?.controls.find(function match(item) {
|
|
22123
|
+
return item.controlId === intent.controlId;
|
|
22124
|
+
});
|
|
22125
|
+
if (recorded && Date.now() - recorded.createdAt > staleMs) await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22126
|
+
}
|
|
22127
|
+
continue;
|
|
22128
|
+
}
|
|
22129
|
+
try {
|
|
22130
|
+
if (task.cancelExecution) await task.cancelExecution();
|
|
22131
|
+
else await options.runtime.turns.cancel({ sessionId: intent.threadId, turnId: intent.expectedTurnId });
|
|
22132
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: true });
|
|
22133
|
+
} catch {
|
|
22134
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22135
|
+
}
|
|
22136
|
+
}
|
|
22137
|
+
}
|
|
22138
|
+
async function applyResumes(snapshot) {
|
|
22139
|
+
for (const intent of await delivery.pendingResumes(snapshot)) {
|
|
22140
|
+
if (active.has(intent.threadId) || await hasFreshLease(intent.threadId)) continue;
|
|
22141
|
+
if (!await delivery.claimResume(intent)) continue;
|
|
22142
|
+
const [session, latest, checkpoint] = await Promise.all([options.ports.sessionStore.get(intent.threadId), options.ports.turnStore.getLatest(intent.threadId), options.ports.checkpointStore.getLatest(intent.threadId)]);
|
|
22143
|
+
if (!session || session.status !== "interrupted" || latest?.id !== intent.expectedTurnId || checkpoint?.turnId !== intent.expectedTurnId || (0, import_node_crypto15.createHash)("sha256").update(JSON.stringify(checkpoint)).digest("hex") !== intent.checkpointDigest) {
|
|
22144
|
+
await delivery.rejectResume(intent);
|
|
22145
|
+
continue;
|
|
22146
|
+
}
|
|
22147
|
+
const record = { threadId: intent.threadId, turnId: intent.expectedTurnId, groupId: intent.groupId, messageId: "", cancelled: false, task: Promise.resolve() };
|
|
22148
|
+
active.set(intent.threadId, record);
|
|
22149
|
+
record.task = continueOriginal().finally(function settled() {
|
|
22150
|
+
if (active.get(intent.threadId) === record) active.delete(intent.threadId);
|
|
22151
|
+
kick();
|
|
22152
|
+
});
|
|
22153
|
+
async function continueOriginal() {
|
|
22154
|
+
let started = false;
|
|
22155
|
+
try {
|
|
22156
|
+
for await (const event of options.runtime.turns.continue({ sessionId: intent.threadId, turnId: intent.expectedTurnId })) {
|
|
22157
|
+
if (event.type === "turn_started") {
|
|
22158
|
+
started = true;
|
|
22159
|
+
record.ready = true;
|
|
22160
|
+
}
|
|
22161
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) record.ready = false;
|
|
22162
|
+
}
|
|
22163
|
+
} catch (error) {
|
|
22164
|
+
if (!started) await delivery.rejectResume(intent);
|
|
22165
|
+
options.onError?.(error);
|
|
22166
|
+
} finally {
|
|
22167
|
+
await notifySettled(record);
|
|
22168
|
+
}
|
|
22169
|
+
}
|
|
22170
|
+
}
|
|
22171
|
+
}
|
|
22172
|
+
async function applyInteractionContinuations(snapshot) {
|
|
22173
|
+
for (const intent of await delivery.pendingInteractionContinuations(snapshot)) {
|
|
22174
|
+
if (active.has(intent.threadId) || await hasFreshLease(intent.threadId)) continue;
|
|
22175
|
+
if (!await delivery.claimInteractionContinuation(intent)) continue;
|
|
22176
|
+
const record = { threadId: intent.threadId, turnId: intent.expectedTurnId, groupId: intent.groupId, messageId: "", cancelled: false, task: Promise.resolve() };
|
|
22177
|
+
active.set(intent.threadId, record);
|
|
22178
|
+
record.task = continueInteraction().finally(function settled() {
|
|
22179
|
+
if (active.get(intent.threadId) === record) active.delete(intent.threadId);
|
|
22180
|
+
kick();
|
|
22181
|
+
}).catch(function report(error) {
|
|
22182
|
+
options.onError?.(error);
|
|
22183
|
+
});
|
|
22184
|
+
async function continueInteraction() {
|
|
22185
|
+
const beat = setInterval(function heartbeat() {
|
|
22186
|
+
delivery.settleInteractionContinuation({ groupId: intent.groupId, controlId: intent.controlId }).catch(function failed(error) {
|
|
22187
|
+
options.onError?.(error);
|
|
22188
|
+
});
|
|
22189
|
+
}, heartbeatMs);
|
|
22190
|
+
let stage = "read_decision";
|
|
22191
|
+
let started = false;
|
|
22192
|
+
try {
|
|
22193
|
+
const decision = intent.approvalId ? await options.ports.approvalStore.getDecision({ sessionId: intent.threadId, turnId: intent.expectedTurnId, approvalId: intent.approvalId }) : void 0;
|
|
22194
|
+
if (intent.approvalId && !decision) throw Object.assign(new Error("INTERACTION_DECISION_REQUIRED"), { code: "INTERACTION_DECISION_REQUIRED" });
|
|
22195
|
+
if (stopped || record.cancelled) {
|
|
22196
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "pending" });
|
|
22197
|
+
return;
|
|
22198
|
+
}
|
|
22199
|
+
stage = "continue";
|
|
22200
|
+
for await (const event of options.runtime.turns.continue({ sessionId: intent.threadId, turnId: intent.expectedTurnId, requestId: intent.requestId, ...decision ? { approval: { approvalId: decision.approvalId, decision: decision.decision === "deny" ? "deny" : "allow" } } : {} })) {
|
|
22201
|
+
if (event.type === "turn_started") {
|
|
22202
|
+
started = true;
|
|
22203
|
+
stage = "after_started";
|
|
22204
|
+
record.ready = true;
|
|
22205
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "executing" });
|
|
22206
|
+
}
|
|
22207
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) record.ready = false;
|
|
22208
|
+
}
|
|
22209
|
+
await notifySettled(record);
|
|
22210
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "completed" });
|
|
22211
|
+
} catch (error) {
|
|
22212
|
+
const file = getFileOperationDiagnostic(error) ?? (error instanceof NodeStateError ? error.getStorageDiagnostic() : void 0);
|
|
22213
|
+
const code = file?.osCode ?? (error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : "CONTINUE_UNKNOWN");
|
|
22214
|
+
const failureDiagnostic = (0, import_core20.sanitizeContinuationFailure)({ stage, started, category: "unknown", code, ...file && ["lock", "temporary_write", "rename", "cleanup"].includes(file.phase) ? { filePhase: file.phase } : {} });
|
|
22215
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "failed", failureCode: "CONTINUE_FAILED", failureDiagnostic });
|
|
22216
|
+
options.onError?.(error, { threadId: intent.threadId, expectedTurnId: intent.expectedTurnId, controlId: intent.controlId, approvalId: intent.approvalId, requestId: intent.requestId, failureDiagnostic });
|
|
22217
|
+
await notifySettled(record);
|
|
22218
|
+
} finally {
|
|
22219
|
+
clearInterval(beat);
|
|
22220
|
+
}
|
|
22221
|
+
}
|
|
22222
|
+
}
|
|
22223
|
+
}
|
|
22224
|
+
function startDelivery(item) {
|
|
22225
|
+
const threadId = item.delivery.threadId;
|
|
22226
|
+
const turnId = item.delivery.reservedTurnId;
|
|
22227
|
+
if (!turnId) {
|
|
22228
|
+
void delivery.failDelivery({ groupId: item.groupId, messageId: item.delivery.messageId, reason: "start_failed" });
|
|
22229
|
+
return;
|
|
22230
|
+
}
|
|
22231
|
+
if (active.has(threadId)) {
|
|
22232
|
+
void delivery.releaseDelivery({ groupId: item.groupId, messageId: item.delivery.messageId });
|
|
22233
|
+
return;
|
|
22234
|
+
}
|
|
22235
|
+
const record = { threadId, turnId, groupId: item.groupId, messageId: item.delivery.messageId, cancelled: false, task: Promise.resolve() };
|
|
22236
|
+
record.task = runDelivery(item, record).catch(function ignore() {
|
|
22237
|
+
}).finally(function finish() {
|
|
22238
|
+
if (active.get(threadId) === record) active.delete(threadId);
|
|
22239
|
+
kick();
|
|
22240
|
+
});
|
|
22241
|
+
active.set(threadId, record);
|
|
22242
|
+
}
|
|
22243
|
+
async function notifyStarted(record, message) {
|
|
22244
|
+
if (!options.onTurnStarted) return;
|
|
22245
|
+
try {
|
|
22246
|
+
await options.onTurnStarted({
|
|
22247
|
+
threadId: record.threadId,
|
|
22248
|
+
turnId: record.turnId,
|
|
22249
|
+
prompt: { content: message.content, messageId: message.messageId, from: message.from, ...message.handoff ? { handoff: message.handoff } : {}, ...message.handoffDisplay ? { handoffDisplay: message.handoffDisplay } : {} }
|
|
22250
|
+
});
|
|
22251
|
+
} catch (error) {
|
|
22252
|
+
options.onError?.(error);
|
|
22253
|
+
}
|
|
22254
|
+
}
|
|
22255
|
+
async function notifySettled(record) {
|
|
22256
|
+
if (!options.onTurnSettled) return;
|
|
22257
|
+
try {
|
|
22258
|
+
await options.onTurnSettled({ threadId: record.threadId, turnId: record.turnId });
|
|
22259
|
+
} catch (error) {
|
|
22260
|
+
options.onError?.(error);
|
|
22261
|
+
}
|
|
22262
|
+
}
|
|
22263
|
+
async function runDelivery(item, record) {
|
|
22264
|
+
const { groupId, delivery: claimed, message } = item;
|
|
22265
|
+
const turnId = record.turnId;
|
|
22266
|
+
const existing = await options.ports.turnStore.get(turnId);
|
|
22267
|
+
if (existing) {
|
|
22268
|
+
await settle(item, record, turnId);
|
|
22269
|
+
return;
|
|
22270
|
+
}
|
|
22271
|
+
if (await hasFreshLease(record.threadId)) {
|
|
22272
|
+
await delivery.releaseDelivery({ groupId, messageId: claimed.messageId });
|
|
22273
|
+
return;
|
|
22274
|
+
}
|
|
22275
|
+
let failure;
|
|
22276
|
+
const beat = setInterval(function heartbeat() {
|
|
22277
|
+
void delivery.heartbeat({ groupId, messageId: claimed.messageId });
|
|
22278
|
+
}, heartbeatMs);
|
|
22279
|
+
beat.unref?.();
|
|
22280
|
+
let controlEnded = false;
|
|
22281
|
+
try {
|
|
22282
|
+
await delivery.heartbeat({ groupId, messageId: claimed.messageId });
|
|
22283
|
+
await notifyStarted(record, message);
|
|
22284
|
+
for await (const event of options.runtime.turns.start({
|
|
22285
|
+
sessionId: record.threadId,
|
|
22286
|
+
turnId,
|
|
22287
|
+
content: message.content,
|
|
22288
|
+
// 与页面队列同语义:这是目标空闲后的下一轮,不是新话题。
|
|
22289
|
+
continuity: { source: "claimed_queue" }
|
|
22290
|
+
})) {
|
|
22291
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) controlEnded = true;
|
|
22292
|
+
record.ready = !controlEnded;
|
|
22293
|
+
if (record.cancelled) break;
|
|
22294
|
+
}
|
|
22295
|
+
} catch (error) {
|
|
22296
|
+
failure = error;
|
|
22297
|
+
} finally {
|
|
22298
|
+
clearInterval(beat);
|
|
22299
|
+
}
|
|
22300
|
+
await settle(item, record, turnId, failure);
|
|
22301
|
+
}
|
|
22302
|
+
async function settle(item, record, turnId, failure) {
|
|
22303
|
+
const groupId = item.groupId;
|
|
22304
|
+
const messageId = item.delivery.messageId;
|
|
22305
|
+
const turn = await options.ports.turnStore.get(turnId);
|
|
22306
|
+
if (failure) {
|
|
22307
|
+
options.onError?.(failure);
|
|
22308
|
+
}
|
|
22309
|
+
if (turn) {
|
|
22310
|
+
await delivery.completeDelivery({ groupId, messageId, turnId });
|
|
22311
|
+
await notifySettled(record);
|
|
22312
|
+
return;
|
|
22313
|
+
}
|
|
22314
|
+
const code = failure?.code;
|
|
22315
|
+
if (code === "TURN_ALREADY_RUNNING") {
|
|
22316
|
+
await delivery.releaseDelivery({ groupId, messageId });
|
|
22317
|
+
return;
|
|
22318
|
+
}
|
|
22319
|
+
await delivery.failDelivery({ groupId, messageId, reason: "start_failed" });
|
|
22320
|
+
}
|
|
22321
|
+
async function stop() {
|
|
22322
|
+
stopped = true;
|
|
22323
|
+
running = false;
|
|
22324
|
+
if (timer) {
|
|
22325
|
+
clearTimeout(timer);
|
|
22326
|
+
timer = void 0;
|
|
22327
|
+
}
|
|
22328
|
+
const cancelledTurnIds = [];
|
|
22329
|
+
const unconfirmedTurnIds = [];
|
|
22330
|
+
const releasedMessageIds = [];
|
|
22331
|
+
const waitingTurnIds = [];
|
|
22332
|
+
const pendingMessageIds = [];
|
|
22333
|
+
const recoverableTurnIds = [];
|
|
22334
|
+
const tasks = [...active.values()].filter(function ownDelivery(record) {
|
|
22335
|
+
return !record.external;
|
|
22336
|
+
});
|
|
22337
|
+
for (const record of tasks) {
|
|
22338
|
+
if (record.cancelled) continue;
|
|
22339
|
+
const actual = await options.ports.turnStore.get(record.turnId);
|
|
22340
|
+
if (actual && actual.status !== "running") {
|
|
22341
|
+
if (actual.status === "waiting_approval" || actual.status === "waiting_user_input") waitingTurnIds.push(actual.id);
|
|
22342
|
+
continue;
|
|
22343
|
+
}
|
|
22344
|
+
record.cancelled = true;
|
|
22345
|
+
try {
|
|
22346
|
+
await options.runtime.turns.cancel({ sessionId: record.threadId, turnId: record.turnId });
|
|
22347
|
+
cancelledTurnIds.push(record.turnId);
|
|
22348
|
+
} catch {
|
|
22349
|
+
unconfirmedTurnIds.push(record.turnId);
|
|
22350
|
+
}
|
|
22351
|
+
}
|
|
22352
|
+
await Promise.allSettled(tasks.map(function task(record) {
|
|
22353
|
+
return record.task;
|
|
22354
|
+
}));
|
|
22355
|
+
for (const groupId of await delivery.listGroups()) {
|
|
22356
|
+
const control = await delivery.readGroup(groupId);
|
|
22357
|
+
if (!control) continue;
|
|
22358
|
+
for (const item of control.deliveries) {
|
|
22359
|
+
if (item.status === "pending" || item.status === "blocked") pendingMessageIds.push(item.messageId);
|
|
22360
|
+
const turnId = item.turnId ?? item.reservedTurnId;
|
|
22361
|
+
const turn = turnId ? await options.ports.turnStore.get(turnId) : void 0;
|
|
22362
|
+
if (turn?.status === "waiting_approval" || turn?.status === "waiting_user_input") waitingTurnIds.push(turn.id);
|
|
22363
|
+
if (turn?.status === "interrupted") recoverableTurnIds.push(turn.id);
|
|
22364
|
+
if (item.ownerId === ownerId && item.status === "claimed" && turn?.status === "running" && !cancelledTurnIds.includes(turn.id)) unconfirmedTurnIds.push(turn.id);
|
|
22365
|
+
if (item.status === "claimed" && item.ownerId === ownerId && !turn) {
|
|
22366
|
+
await delivery.releaseDelivery({ groupId, messageId: item.messageId });
|
|
22367
|
+
releasedMessageIds.push(item.messageId);
|
|
22368
|
+
pendingMessageIds.push(item.messageId);
|
|
22369
|
+
}
|
|
22370
|
+
}
|
|
22371
|
+
if (control.deliveries.some(function pending(item) {
|
|
22372
|
+
return item.status === "pending" || item.status === "blocked";
|
|
22373
|
+
})) await delivery.recordHostOffline(groupId);
|
|
22374
|
+
}
|
|
22375
|
+
for (const turnId of cancelledTurnIds) {
|
|
22376
|
+
const turn = await options.ports.turnStore.get(turnId);
|
|
22377
|
+
if (!turn || turn.status === "running") unconfirmedTurnIds.push(turnId);
|
|
22378
|
+
}
|
|
22379
|
+
return { stopped: true, cancelledTurnIds: cancelledTurnIds.filter(function confirmed(id) {
|
|
22380
|
+
return !unconfirmedTurnIds.includes(id);
|
|
22381
|
+
}), unconfirmedTurnIds: [...new Set(unconfirmedTurnIds)], releasedMessageIds, waitingTurnIds: [...new Set(waitingTurnIds)], pendingMessageIds: [...new Set(pendingMessageIds)], recoverableTurnIds: [...new Set(recoverableTurnIds)] };
|
|
22382
|
+
}
|
|
22383
|
+
function kick() {
|
|
22384
|
+
if (!running || stopped) return;
|
|
22385
|
+
idleDelayMs = pollIntervalMs;
|
|
22386
|
+
kicked = true;
|
|
22387
|
+
if (!ticking) void safeTick();
|
|
22388
|
+
}
|
|
22389
|
+
function registerExecution(input) {
|
|
22390
|
+
const previous = active.get(input.threadId);
|
|
22391
|
+
if (previous && (previous.ready || previous.turnId !== input.turnId)) throw Object.assign(new Error("TURN_ALREADY_RUNNING"), { code: "TURN_ALREADY_RUNNING" });
|
|
22392
|
+
const record = { threadId: input.threadId, turnId: input.turnId, groupId: "", messageId: "", cancelled: false, task: Promise.resolve(), external: true, ready: false, cancelExecution: input.cancel };
|
|
22393
|
+
active.set(input.threadId, record);
|
|
22394
|
+
return {
|
|
22395
|
+
activate: function activate() {
|
|
22396
|
+
if (active.get(input.threadId) === record) {
|
|
22397
|
+
record.ready = true;
|
|
22398
|
+
kick();
|
|
22399
|
+
}
|
|
22400
|
+
},
|
|
22401
|
+
release: function release() {
|
|
22402
|
+
if (active.get(input.threadId) === record) {
|
|
22403
|
+
active.delete(input.threadId);
|
|
22404
|
+
kick();
|
|
22405
|
+
}
|
|
22406
|
+
}
|
|
22407
|
+
};
|
|
22408
|
+
}
|
|
22409
|
+
async function start() {
|
|
22410
|
+
if (running) return;
|
|
22411
|
+
stopped = false;
|
|
22412
|
+
running = true;
|
|
22413
|
+
await safeTick(true);
|
|
22414
|
+
}
|
|
22415
|
+
return {
|
|
22416
|
+
start,
|
|
22417
|
+
stop,
|
|
22418
|
+
kick,
|
|
22419
|
+
registerExecution,
|
|
22420
|
+
isRunning: function isRunning() {
|
|
22421
|
+
return running;
|
|
22422
|
+
},
|
|
22423
|
+
reconcile: function converge() {
|
|
22424
|
+
return delivery.reconcile({ staleMs, activeMessageIds: activeMessageIds() });
|
|
22425
|
+
}
|
|
22426
|
+
};
|
|
22427
|
+
}
|
|
22428
|
+
|
|
22429
|
+
// src/node/thread-handoff.ts
|
|
22430
|
+
var import_node_crypto16 = require("node:crypto");
|
|
22431
|
+
var import_node_fs34 = __toESM(require("node:fs"));
|
|
22432
|
+
var import_node_path26 = __toESM(require("node:path"));
|
|
22433
|
+
var HANDOFF_DIRECTORY = ".autopilot";
|
|
22434
|
+
function assertWithinRoot(root, candidate) {
|
|
22435
|
+
const relative = import_node_path26.default.relative(root, candidate);
|
|
22436
|
+
if (!relative || relative.startsWith(`..${import_node_path26.default.sep}`) || relative === ".." || import_node_path26.default.isAbsolute(relative)) {
|
|
22437
|
+
throw new Error("THREAD_HANDOFF_WRITE_FAILED");
|
|
22438
|
+
}
|
|
22439
|
+
}
|
|
22440
|
+
function sha2562(content) {
|
|
22441
|
+
return (0, import_node_crypto16.createHash)("sha256").update(content, "utf8").digest("hex");
|
|
22442
|
+
}
|
|
22443
|
+
function createNodeThreadHandoffWriter(options) {
|
|
22444
|
+
const workspaceRoot = import_node_path26.default.resolve(options.workspaceRoot);
|
|
22445
|
+
function resolveTarget(handoffId) {
|
|
22446
|
+
if (!/^[0-9a-f]{16,64}$/.test(handoffId)) throw new Error("THREAD_HANDOFF_WRITE_FAILED");
|
|
22447
|
+
const realRoot = import_node_fs34.default.realpathSync(workspaceRoot);
|
|
22448
|
+
const directory = import_node_path26.default.resolve(realRoot, HANDOFF_DIRECTORY);
|
|
22449
|
+
assertWithinRoot(realRoot, directory);
|
|
22450
|
+
const filePath = import_node_path26.default.join(directory, `thread-passdown-${handoffId}.md`);
|
|
22451
|
+
assertWithinRoot(realRoot, filePath);
|
|
22452
|
+
return { directory, filePath };
|
|
22453
|
+
}
|
|
22454
|
+
async function write(input) {
|
|
22455
|
+
const { directory, filePath } = resolveTarget(input.handoffId);
|
|
22456
|
+
const content = `# Handoff\uFF1A${input.title}
|
|
22457
|
+
|
|
22458
|
+
${input.markdown}
|
|
22459
|
+
`;
|
|
22460
|
+
import_node_fs34.default.mkdirSync(directory, { recursive: true });
|
|
22461
|
+
const realDirectory = import_node_fs34.default.realpathSync(directory);
|
|
22462
|
+
assertWithinRoot(import_node_fs34.default.realpathSync(workspaceRoot), realDirectory);
|
|
22463
|
+
await withAsyncFileLock(filePath, function writeLocked() {
|
|
22464
|
+
if (import_node_fs34.default.existsSync(filePath)) {
|
|
22465
|
+
const existing = import_node_fs34.default.readFileSync(filePath, "utf8");
|
|
22466
|
+
if (existing !== content) throw new Error("THREAD_HANDOFF_CONFLICT");
|
|
22467
|
+
return;
|
|
22468
|
+
}
|
|
22469
|
+
atomicReplace(filePath, content);
|
|
22470
|
+
});
|
|
22471
|
+
const written = import_node_fs34.default.readFileSync(filePath, "utf8");
|
|
22472
|
+
if (written !== content) throw new Error("THREAD_HANDOFF_CONFLICT");
|
|
22473
|
+
return {
|
|
22474
|
+
handoffId: input.handoffId,
|
|
22475
|
+
relativePath: `${HANDOFF_DIRECTORY}/thread-passdown-${input.handoffId}.md`,
|
|
22476
|
+
sha256: sha2562(content)
|
|
22477
|
+
};
|
|
22478
|
+
}
|
|
22479
|
+
return { write };
|
|
22480
|
+
}
|
|
22481
|
+
|
|
22482
|
+
// src/node/host-identity.ts
|
|
22483
|
+
var import_node_crypto17 = require("node:crypto");
|
|
22484
|
+
var LOCAL_HUMAN_PRINCIPAL_ID = "web-local-user";
|
|
22485
|
+
function createNodeStateRootId(stateRoot) {
|
|
22486
|
+
return (0, import_node_crypto17.createHash)("sha256").update(stateRoot).digest("hex");
|
|
22487
|
+
}
|
|
21206
22488
|
// Annotate the CommonJS export names for ESM import in node:
|
|
21207
22489
|
0 && (module.exports = {
|
|
21208
22490
|
CHAT_ATTACHMENT_TTL_MS,
|
|
21209
22491
|
DEFAULT_COMPACT_TARGET_RATIO,
|
|
21210
22492
|
DEFAULT_COMPACT_TRIGGER_RATIO,
|
|
21211
22493
|
DEFAULT_CONTEXT_WINDOW_TOKENS,
|
|
22494
|
+
LOCAL_HUMAN_PRINCIPAL_ID,
|
|
21212
22495
|
NODE_CHAT_KNOWLEDGE_SPACE_ID,
|
|
21213
22496
|
NODE_STATE_SCHEMA_VERSION,
|
|
21214
22497
|
NODE_WORKSPACE_ID_VERSION,
|
|
@@ -21240,11 +22523,15 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21240
22523
|
createNodeRagRuntime,
|
|
21241
22524
|
createNodeRuntimePorts,
|
|
21242
22525
|
createNodeSandboxPort,
|
|
22526
|
+
createNodeSessionImageStore,
|
|
21243
22527
|
createNodeSessionResourceStore,
|
|
21244
22528
|
createNodeSessionStore,
|
|
21245
22529
|
createNodeSettingsLoader,
|
|
21246
22530
|
createNodeSettingsWriter,
|
|
22531
|
+
createNodeStateRootId,
|
|
21247
22532
|
createNodeStateSchemaManager,
|
|
22533
|
+
createNodeThreadHandoffWriter,
|
|
22534
|
+
createNodeThreadRunner,
|
|
21248
22535
|
createNodeTranscriptStore,
|
|
21249
22536
|
createNodeTrustPolicy,
|
|
21250
22537
|
createNodeTrustStore,
|