@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.mjs
CHANGED
|
@@ -2169,14 +2169,20 @@ var runtimeMessages = {
|
|
|
2169
2169
|
};
|
|
2170
2170
|
var NodeStateError = class extends Error {
|
|
2171
2171
|
/** 只使用固定错误码作为消息,恢复信息保存为不可枚举的私有字段。 */
|
|
2172
|
-
constructor(code, recovery) {
|
|
2172
|
+
constructor(code, recovery, storage) {
|
|
2173
2173
|
super(code);
|
|
2174
2174
|
this.code = code;
|
|
2175
2175
|
this.name = "NodeStateError";
|
|
2176
2176
|
this.#recovery = recovery ? { ...recovery } : void 0;
|
|
2177
|
+
this.#storage = storage ? { ...storage } : void 0;
|
|
2177
2178
|
}
|
|
2178
2179
|
#recovery;
|
|
2180
|
+
#storage;
|
|
2179
2181
|
/** 受信宿主显式取得恢复信息副本,不得将它投影到 HTTP 或模型事件。 */
|
|
2182
|
+
/** 受信CLI诊断显式读取,序列化错误不会暴露内部阶段。 */
|
|
2183
|
+
getStorageDiagnostic() {
|
|
2184
|
+
return this.#storage ? { ...this.#storage } : void 0;
|
|
2185
|
+
}
|
|
2180
2186
|
getRecoveryDiagnostic() {
|
|
2181
2187
|
return this.#recovery ? { ...this.#recovery } : void 0;
|
|
2182
2188
|
}
|
|
@@ -2192,15 +2198,15 @@ var NodeChatError = class extends Error {
|
|
|
2192
2198
|
function createNodeIdentityError(code) {
|
|
2193
2199
|
return new AgentRuntimeError(code, runtimeMessages[code]);
|
|
2194
2200
|
}
|
|
2195
|
-
function toNodeBoundaryError(error, fallback) {
|
|
2201
|
+
function toNodeBoundaryError(error, fallback, storage) {
|
|
2196
2202
|
if (error instanceof Error && "code" in error && typeof error.code === "string") {
|
|
2197
2203
|
if (error.name === "AgentRuntimeError" && Object.prototype.hasOwnProperty.call(runtimeMessages, error.code)) return createNodeIdentityError(error.code);
|
|
2198
2204
|
if (error.name === "NodeStateError" && stateCodes.includes(error.code)) {
|
|
2199
|
-
return new NodeStateError(error.code, error instanceof NodeStateError ? error.getRecoveryDiagnostic() : void 0);
|
|
2205
|
+
return new NodeStateError(error.code, error instanceof NodeStateError ? error.getRecoveryDiagnostic() : void 0, storage ?? (error instanceof NodeStateError ? error.getStorageDiagnostic() : void 0));
|
|
2200
2206
|
}
|
|
2201
2207
|
if (error.name === "NodeChatError" && chatCodes.includes(error.code)) return new NodeChatError(error.code);
|
|
2202
2208
|
}
|
|
2203
|
-
return stateCodes.includes(fallback) ? new NodeStateError(fallback) : new NodeChatError(fallback);
|
|
2209
|
+
return stateCodes.includes(fallback) ? new NodeStateError(fallback, void 0, storage) : new NodeChatError(fallback);
|
|
2204
2210
|
}
|
|
2205
2211
|
|
|
2206
2212
|
// src/node/create-node-runtime-ports.ts
|
|
@@ -17392,7 +17398,7 @@ function loadSrtRuntimeSurface() {
|
|
|
17392
17398
|
}
|
|
17393
17399
|
|
|
17394
17400
|
// src/node/sandbox/node-sandbox-port.ts
|
|
17395
|
-
import
|
|
17401
|
+
import path9 from "node:path";
|
|
17396
17402
|
|
|
17397
17403
|
// src/node/file-mutation-locks.ts
|
|
17398
17404
|
import os2 from "node:os";
|
|
@@ -17404,6 +17410,16 @@ import fs5 from "node:fs";
|
|
|
17404
17410
|
import fsp from "node:fs/promises";
|
|
17405
17411
|
import { randomUUID } from "node:crypto";
|
|
17406
17412
|
import path4 from "node:path";
|
|
17413
|
+
var fileDiagnostics = /* @__PURE__ */ new WeakMap();
|
|
17414
|
+
function getFileOperationDiagnostic(error) {
|
|
17415
|
+
return error && typeof error === "object" ? fileDiagnostics.get(error) : void 0;
|
|
17416
|
+
}
|
|
17417
|
+
function rememberFileFailure(error, diagnostic) {
|
|
17418
|
+
if (!error || typeof error !== "object") return;
|
|
17419
|
+
const code = error.code;
|
|
17420
|
+
const osCode = ["EACCES", "EPERM", "ENOENT", "EEXIST", "ENOSPC", "EIO", "EMFILE", "ENFILE", "EBUSY", "EROFS", "ENOTDIR", "ETIMEDOUT"].includes(code ?? "") ? code : void 0;
|
|
17421
|
+
fileDiagnostics.set(error, { ...diagnostic, ...osCode ? { osCode } : {} });
|
|
17422
|
+
}
|
|
17407
17423
|
var fileLocks = /* @__PURE__ */ new Map();
|
|
17408
17424
|
var PROCESS_LOCK_RETRY_MS = 10;
|
|
17409
17425
|
var PROCESS_LOCK_TIMEOUT_MS = 3e4;
|
|
@@ -17518,7 +17534,14 @@ async function withFileLock(filePath, operation, options) {
|
|
|
17518
17534
|
fileLocks.set(key2, queued);
|
|
17519
17535
|
try {
|
|
17520
17536
|
await previous;
|
|
17521
|
-
const
|
|
17537
|
+
const startedAt = Date.now();
|
|
17538
|
+
let handle;
|
|
17539
|
+
try {
|
|
17540
|
+
handle = await acquireProcessLock(key2, options?.requireExitedOwner);
|
|
17541
|
+
} catch (error) {
|
|
17542
|
+
rememberFileFailure(error, { phase: "lock", lockWaitMs: Date.now() - startedAt });
|
|
17543
|
+
throw error;
|
|
17544
|
+
}
|
|
17522
17545
|
try {
|
|
17523
17546
|
return await operation();
|
|
17524
17547
|
} finally {
|
|
@@ -17597,11 +17620,26 @@ function ensureParentDirectory(filePath) {
|
|
|
17597
17620
|
function atomicReplace(filePath, content) {
|
|
17598
17621
|
ensureParentDirectory(filePath);
|
|
17599
17622
|
const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
17623
|
+
let phase = "temporary_write";
|
|
17624
|
+
let failure;
|
|
17600
17625
|
try {
|
|
17601
17626
|
fs5.writeFileSync(temporaryPath, content, { encoding: "utf8", flag: "wx" });
|
|
17627
|
+
phase = "rename";
|
|
17602
17628
|
fs5.renameSync(temporaryPath, filePath);
|
|
17629
|
+
} catch (error) {
|
|
17630
|
+
failure = error;
|
|
17631
|
+
rememberFileFailure(error, { phase });
|
|
17632
|
+
throw error;
|
|
17603
17633
|
} finally {
|
|
17604
|
-
|
|
17634
|
+
try {
|
|
17635
|
+
if (fs5.existsSync(temporaryPath)) fs5.unlinkSync(temporaryPath);
|
|
17636
|
+
} catch (error) {
|
|
17637
|
+
if (failure) rememberFileFailure(failure, { ...getFileOperationDiagnostic(failure), cleanupFailed: true });
|
|
17638
|
+
else {
|
|
17639
|
+
rememberFileFailure(error, { phase: "cleanup" });
|
|
17640
|
+
throw error;
|
|
17641
|
+
}
|
|
17642
|
+
}
|
|
17605
17643
|
}
|
|
17606
17644
|
}
|
|
17607
17645
|
function safeFilePath(directory, key2, extension) {
|
|
@@ -17677,22 +17715,37 @@ async function withNodeFileMutationLocks(canonicalTargets, operation) {
|
|
|
17677
17715
|
}
|
|
17678
17716
|
|
|
17679
17717
|
// src/node/state-root.ts
|
|
17680
|
-
import
|
|
17681
|
-
import { createHash as
|
|
17718
|
+
import fs8 from "node:fs";
|
|
17719
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
17682
17720
|
import os3 from "node:os";
|
|
17683
|
-
import
|
|
17721
|
+
import path8 from "node:path";
|
|
17684
17722
|
|
|
17685
17723
|
// src/node/state-schema-manager.ts
|
|
17686
17724
|
import fs6 from "node:fs";
|
|
17687
17725
|
import path6 from "node:path";
|
|
17688
17726
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
17727
|
+
function hasExitedLockOwner(file) {
|
|
17728
|
+
try {
|
|
17729
|
+
const metadata = JSON.parse(fs6.readFileSync(file, "utf8"));
|
|
17730
|
+
if (!Number.isSafeInteger(metadata?.pid) || metadata.pid <= 0) return false;
|
|
17731
|
+
try {
|
|
17732
|
+
process.kill(metadata.pid, 0);
|
|
17733
|
+
} catch (error) {
|
|
17734
|
+
return error.code === "ESRCH";
|
|
17735
|
+
}
|
|
17736
|
+
return false;
|
|
17737
|
+
} catch {
|
|
17738
|
+
return false;
|
|
17739
|
+
}
|
|
17740
|
+
}
|
|
17689
17741
|
function assertPlainStateTree(root) {
|
|
17690
17742
|
const entry = fs6.lstatSync(root);
|
|
17691
17743
|
if (entry.isSymbolicLink() || !entry.isDirectory() && !entry.isFile()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17692
17744
|
if (!entry.isDirectory()) return;
|
|
17693
17745
|
for (const name of fs6.readdirSync(root)) {
|
|
17694
|
-
|
|
17695
|
-
assertPlainStateTree(
|
|
17746
|
+
const child = path6.join(root, name);
|
|
17747
|
+
assertPlainStateTree(child);
|
|
17748
|
+
if (name.endsWith(".lock") && !hasExitedLockOwner(child)) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17696
17749
|
}
|
|
17697
17750
|
}
|
|
17698
17751
|
function acquireSchemaLock(root) {
|
|
@@ -17755,6 +17808,14 @@ function createBackupPath(root, fromVersion, toVersion) {
|
|
|
17755
17808
|
function backupStateRoot(root, fromVersion, toVersion) {
|
|
17756
17809
|
if (!hasDurableState(root)) return void 0;
|
|
17757
17810
|
assertPlainStateTree(root);
|
|
17811
|
+
const leases = path6.join(root, "leases");
|
|
17812
|
+
if (fs6.existsSync(leases)) {
|
|
17813
|
+
for (const file of fs6.readdirSync(leases)) {
|
|
17814
|
+
if (!file.endsWith(".json")) continue;
|
|
17815
|
+
const record = JSON.parse(fs6.readFileSync(path6.join(leases, file), "utf8"));
|
|
17816
|
+
if (Number.isFinite(record?.lease?.heartbeatAt) && Date.now() - record.lease.heartbeatAt <= 45e3) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17817
|
+
}
|
|
17818
|
+
}
|
|
17758
17819
|
const backupPath = createBackupPath(root, fromVersion, toVersion);
|
|
17759
17820
|
const backupRoot = path6.dirname(backupPath);
|
|
17760
17821
|
if (fs6.existsSync(backupRoot) && fs6.lstatSync(backupRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
@@ -17840,6 +17901,11 @@ function createNodeStateSchemaManager(options) {
|
|
|
17840
17901
|
if (!Number.isInteger(fromVersion) || !Number.isInteger(toVersion)) {
|
|
17841
17902
|
throw new NodeStateError("STATE_SCHEMA_VERSION_INVALID");
|
|
17842
17903
|
}
|
|
17904
|
+
for (let version = fromVersion; version < toVersion; version++) {
|
|
17905
|
+
if (!options.migrations.some(function adjacent(step) {
|
|
17906
|
+
return step.fromVersion === version && step.toVersion === version + 1;
|
|
17907
|
+
})) throw new NodeStateError("STATE_SCHEMA_MIGRATION_MISSING");
|
|
17908
|
+
}
|
|
17843
17909
|
const backupPath = backup(fromVersion, toVersion);
|
|
17844
17910
|
try {
|
|
17845
17911
|
if (fs6.existsSync(root)) fs6.cpSync(root, stagingRoot, { recursive: true, errorOnExist: true });
|
|
@@ -17890,7 +17956,12 @@ function normalizeNodeSession(value, id) {
|
|
|
17890
17956
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
17891
17957
|
const session = value;
|
|
17892
17958
|
if (session.id !== id || !Number.isFinite(session.createdAt) || !Number.isFinite(session.updatedAt)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
17893
|
-
const
|
|
17959
|
+
const source = session.creationSource;
|
|
17960
|
+
if (source !== void 0) {
|
|
17961
|
+
const actor = source?.actor;
|
|
17962
|
+
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");
|
|
17963
|
+
}
|
|
17964
|
+
const mode = session.productMode;
|
|
17894
17965
|
if (mode === "chat") {
|
|
17895
17966
|
if (session.projectId !== void 0 || !["none", "web", "rag"].includes(session.chatRetrievalMode ?? "")) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17896
17967
|
} else if (mode !== "work" || session.chatRetrievalMode !== void 0 || typeof session.projectId !== "string" || !session.projectId.trim()) {
|
|
@@ -17899,13 +17970,62 @@ function normalizeNodeSession(value, id) {
|
|
|
17899
17970
|
return { ...session, productMode: mode };
|
|
17900
17971
|
}
|
|
17901
17972
|
function assertNodeSessionIdentity(previous, next) {
|
|
17973
|
+
if (JSON.stringify(previous.collaborationAllowedTools) !== JSON.stringify(next.collaborationAllowedTools)) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17974
|
+
if (JSON.stringify(previous.creationSource) !== JSON.stringify(next.creationSource)) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17975
|
+
if (previous.collaborationCreationId !== next.collaborationCreationId) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17902
17976
|
if (previous.workContextVersion !== next.workContextVersion) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17903
17977
|
if (previous.productMode !== next.productMode || previous.projectId !== next.projectId) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17904
17978
|
if (previous.chatRetrievalMode !== next.chatRetrievalMode) throw createNodeIdentityError("CHAT_RETRIEVAL_MODE_LOCKED");
|
|
17905
17979
|
}
|
|
17906
17980
|
|
|
17981
|
+
// src/node/state-upgrade.ts
|
|
17982
|
+
import fs7 from "node:fs";
|
|
17983
|
+
import path7 from "node:path";
|
|
17984
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
17985
|
+
function upgradeSessionIdentity(root, allowLegacyWork) {
|
|
17986
|
+
const directory = path7.join(root, "sessions");
|
|
17987
|
+
if (!fs7.existsSync(directory)) return;
|
|
17988
|
+
for (const file of fs7.readdirSync(directory)) {
|
|
17989
|
+
if (!file.endsWith(".json")) continue;
|
|
17990
|
+
const target = path7.join(directory, file);
|
|
17991
|
+
let value;
|
|
17992
|
+
try {
|
|
17993
|
+
value = JSON.parse(fs7.readFileSync(target, "utf8"));
|
|
17994
|
+
} catch {
|
|
17995
|
+
throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
17996
|
+
}
|
|
17997
|
+
const missingMode = value && typeof value === "object" && value.productMode === void 0;
|
|
17998
|
+
if (missingMode && allowLegacyWork) value.productMode = "work";
|
|
17999
|
+
const session = normalizeNodeSession(value, file.slice(0, -5));
|
|
18000
|
+
if (missingMode && allowLegacyWork) fs7.writeFileSync(target, JSON.stringify(session, null, 2), "utf8");
|
|
18001
|
+
}
|
|
18002
|
+
}
|
|
18003
|
+
function upgradeThreadCreationSources(root) {
|
|
18004
|
+
upgradeSessionIdentity(root, false);
|
|
18005
|
+
const groups = path7.join(root, "threads", "groups");
|
|
18006
|
+
if (!fs7.existsSync(groups)) return;
|
|
18007
|
+
for (const groupId of fs7.readdirSync(groups)) {
|
|
18008
|
+
const file = path7.join(groups, groupId, "control.json");
|
|
18009
|
+
if (!fs7.existsSync(file)) continue;
|
|
18010
|
+
const control = JSON.parse(fs7.readFileSync(file, "utf8"));
|
|
18011
|
+
if (control.group?.groupId !== groupId || !Array.isArray(control.creates)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18012
|
+
for (const intent of control.creates) {
|
|
18013
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(intent.threadId)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18014
|
+
const target = path7.join(root, "sessions", `${intent.threadId}.json`);
|
|
18015
|
+
if (!fs7.existsSync(target)) continue;
|
|
18016
|
+
const session = normalizeNodeSession(JSON.parse(fs7.readFileSync(target, "utf8")), intent.threadId);
|
|
18017
|
+
const creationId = createHash2("sha256").update(JSON.stringify([groupId, intent.actorKey, intent.requestId])).digest("hex");
|
|
18018
|
+
if (session.collaborationCreationId !== creationId || session.projectId !== control.group.projectId) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18019
|
+
const source = { actor: intent.from, requestId: intent.requestId };
|
|
18020
|
+
const next = normalizeNodeSession({ ...session, creationSource: source }, session.id);
|
|
18021
|
+
if (session.creationSource !== void 0 && JSON.stringify(session.creationSource) !== JSON.stringify(source)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18022
|
+
if (session.creationSource === void 0) fs7.writeFileSync(target, JSON.stringify(next, null, 2), "utf8");
|
|
18023
|
+
}
|
|
18024
|
+
}
|
|
18025
|
+
}
|
|
18026
|
+
|
|
17907
18027
|
// src/node/state-root.ts
|
|
17908
|
-
var NODE_STATE_SCHEMA_VERSION =
|
|
18028
|
+
var NODE_STATE_SCHEMA_VERSION = 8;
|
|
17909
18029
|
var NODE_WORKSPACE_ID_VERSION = 1;
|
|
17910
18030
|
var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
17911
18031
|
fromVersion: 0,
|
|
@@ -17916,47 +18036,47 @@ var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
|
17916
18036
|
fromVersion: 1,
|
|
17917
18037
|
toVersion: 2,
|
|
17918
18038
|
migrate(stagingRoot) {
|
|
17919
|
-
|
|
18039
|
+
fs8.mkdirSync(path8.join(stagingRoot, "jobs"), { recursive: true });
|
|
17920
18040
|
}
|
|
17921
18041
|
}, {
|
|
17922
18042
|
fromVersion: 2,
|
|
17923
18043
|
toVersion: 3,
|
|
17924
18044
|
migrate(stagingRoot) {
|
|
17925
|
-
|
|
17926
|
-
|
|
17927
|
-
|
|
17928
|
-
|
|
18045
|
+
fs8.mkdirSync(path8.join(stagingRoot, "mutations"), { recursive: true });
|
|
18046
|
+
fs8.mkdirSync(path8.join(stagingRoot, "mutation-blobs"), { recursive: true });
|
|
18047
|
+
fs8.mkdirSync(path8.join(stagingRoot, "mutation-locks"), { recursive: true });
|
|
18048
|
+
fs8.mkdirSync(path8.join(stagingRoot, "undo-transactions"), { recursive: true });
|
|
17929
18049
|
}
|
|
17930
18050
|
}, {
|
|
17931
18051
|
fromVersion: 3,
|
|
17932
18052
|
toVersion: 4,
|
|
17933
18053
|
migrate(stagingRoot) {
|
|
17934
|
-
|
|
18054
|
+
fs8.mkdirSync(path8.join(stagingRoot, "questions"), { recursive: true });
|
|
17935
18055
|
}
|
|
17936
18056
|
}, {
|
|
17937
18057
|
fromVersion: 4,
|
|
17938
18058
|
toVersion: 5,
|
|
17939
18059
|
/** 仅在迁移副本补写产品身份;缺失归属只能采用唯一已有 Project,不能猜工作区。 */
|
|
17940
18060
|
migrate(stagingRoot) {
|
|
17941
|
-
const sessions =
|
|
17942
|
-
if (!
|
|
17943
|
-
const projects =
|
|
17944
|
-
const candidates =
|
|
18061
|
+
const sessions = path8.join(stagingRoot, "sessions");
|
|
18062
|
+
if (!fs8.existsSync(sessions)) return;
|
|
18063
|
+
const projects = path8.join(stagingRoot, "projects");
|
|
18064
|
+
const candidates = fs8.existsSync(projects) ? fs8.readdirSync(projects).filter(
|
|
17945
18065
|
/** 只检查现有 Project 记录,不创建新的工作区身份。 */
|
|
17946
18066
|
function projectFile(file) {
|
|
17947
18067
|
return file.endsWith(".json");
|
|
17948
18068
|
}
|
|
17949
18069
|
) : [];
|
|
17950
|
-
for (const file of
|
|
18070
|
+
for (const file of fs8.readdirSync(sessions)) {
|
|
17951
18071
|
if (!file.endsWith(".json")) continue;
|
|
17952
|
-
const target =
|
|
17953
|
-
const value = JSON.parse(
|
|
18072
|
+
const target = path8.join(sessions, file);
|
|
18073
|
+
const value = JSON.parse(fs8.readFileSync(target, "utf8"));
|
|
17954
18074
|
if (value && value.productMode === void 0 && value.projectId === void 0 && candidates.length === 1) {
|
|
17955
|
-
const project = JSON.parse(
|
|
18075
|
+
const project = JSON.parse(fs8.readFileSync(path8.join(projects, candidates[0]), "utf8"));
|
|
17956
18076
|
if (project.id === candidates[0].slice(0, -5) && typeof project.workspaceRoot === "string" && project.workspaceRoot) value.projectId = project.id;
|
|
17957
18077
|
}
|
|
17958
18078
|
const session = normalizeNodeSession(value, file.slice(0, -5));
|
|
17959
|
-
|
|
18079
|
+
fs8.writeFileSync(target, JSON.stringify(session, null, 2), "utf8");
|
|
17960
18080
|
}
|
|
17961
18081
|
}
|
|
17962
18082
|
}, {
|
|
@@ -17964,70 +18084,87 @@ var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
|
17964
18084
|
toVersion: 6,
|
|
17965
18085
|
migrate() {
|
|
17966
18086
|
}
|
|
18087
|
+
}, {
|
|
18088
|
+
fromVersion: 6,
|
|
18089
|
+
toVersion: 7,
|
|
18090
|
+
/** v7 严格校验产品身份;旧 Work 缺省值在副本中显式落盘。 */
|
|
18091
|
+
migrate(stagingRoot) {
|
|
18092
|
+
upgradeSessionIdentity(stagingRoot, true);
|
|
18093
|
+
}
|
|
18094
|
+
}, {
|
|
18095
|
+
fromVersion: 7,
|
|
18096
|
+
toVersion: 8,
|
|
18097
|
+
/** 新来源只从已有持久意图恢复;旧进展仍保留为无任务归属的会话进展。 */
|
|
18098
|
+
migrate(stagingRoot) {
|
|
18099
|
+
upgradeThreadCreationSources(stagingRoot);
|
|
18100
|
+
}
|
|
17967
18101
|
}];
|
|
17968
18102
|
function canonicalizeNodePath(candidate, baseDirectory = process.cwd()) {
|
|
17969
|
-
const resolved =
|
|
18103
|
+
const resolved = path8.resolve(baseDirectory, candidate);
|
|
17970
18104
|
try {
|
|
17971
|
-
return
|
|
18105
|
+
return fs8.realpathSync.native(resolved);
|
|
17972
18106
|
} catch {
|
|
17973
18107
|
return resolved;
|
|
17974
18108
|
}
|
|
17975
18109
|
}
|
|
17976
18110
|
function createNodeWorkspaceId(workspaceRoot, baseDirectory) {
|
|
17977
18111
|
const canonicalRoot = canonicalizeNodePath(workspaceRoot, baseDirectory);
|
|
17978
|
-
const digest2 =
|
|
18112
|
+
const digest2 = createHash3("sha256").update(canonicalRoot).digest("hex").slice(0, 24);
|
|
17979
18113
|
return `v${NODE_WORKSPACE_ID_VERSION}-${digest2}`;
|
|
17980
18114
|
}
|
|
17981
18115
|
function resolveNodeGlobalStateRoot(options = {}) {
|
|
17982
18116
|
const baseDirectory = options.cwd ?? process.cwd();
|
|
17983
|
-
const defaultRoot = process.env.LOCALAPPDATA ?
|
|
18117
|
+
const defaultRoot = process.env.LOCALAPPDATA ? path8.join(process.env.LOCALAPPDATA, "autopilot-agent") : path8.join(os3.homedir(), ".autopilot-agent");
|
|
17984
18118
|
return canonicalizeNodePath(options.globalStateRoot ?? defaultRoot, baseDirectory);
|
|
17985
18119
|
}
|
|
17986
18120
|
function resolveNodeStateRoot(options = {}) {
|
|
17987
18121
|
const baseDirectory = options.cwd ?? process.cwd();
|
|
17988
18122
|
if (options.stateRoot) return canonicalizeNodePath(options.stateRoot, baseDirectory);
|
|
17989
18123
|
const workspaceRoot = options.workspaceRoot ?? baseDirectory;
|
|
17990
|
-
return
|
|
18124
|
+
return path8.join(resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: baseDirectory }), "workspaces", createNodeWorkspaceId(workspaceRoot, baseDirectory));
|
|
17991
18125
|
}
|
|
17992
18126
|
function resolveNodeTrustRoot(options) {
|
|
17993
18127
|
const stateRoot = canonicalizeNodePath(options.stateRoot);
|
|
17994
|
-
return canonicalizeNodePath(options.trustRoot ??
|
|
18128
|
+
return canonicalizeNodePath(options.trustRoot ?? path8.resolve(stateRoot, "..", "agent"));
|
|
17995
18129
|
}
|
|
17996
18130
|
function getNodeStatePaths(stateRoot) {
|
|
17997
18131
|
const root = canonicalizeNodePath(stateRoot);
|
|
17998
18132
|
return {
|
|
17999
18133
|
root,
|
|
18000
|
-
schemaFile:
|
|
18001
|
-
sessionsDir:
|
|
18002
|
-
checkpointsDir:
|
|
18003
|
-
transcriptsDir:
|
|
18004
|
-
projectsDir:
|
|
18005
|
-
turnsDir:
|
|
18006
|
-
approvalsDir:
|
|
18007
|
-
inboxDir:
|
|
18008
|
-
leasesDir:
|
|
18009
|
-
jobsDir:
|
|
18010
|
-
mutationsDir:
|
|
18011
|
-
mutationBlobsDir:
|
|
18012
|
-
mutationLocksDir:
|
|
18013
|
-
undoTransactionsDir:
|
|
18014
|
-
questionsDir:
|
|
18134
|
+
schemaFile: path8.join(root, "schema.json"),
|
|
18135
|
+
sessionsDir: path8.join(root, "sessions"),
|
|
18136
|
+
checkpointsDir: path8.join(root, "checkpoints"),
|
|
18137
|
+
transcriptsDir: path8.join(root, "transcripts"),
|
|
18138
|
+
projectsDir: path8.join(root, "projects"),
|
|
18139
|
+
turnsDir: path8.join(root, "turns"),
|
|
18140
|
+
approvalsDir: path8.join(root, "approvals"),
|
|
18141
|
+
inboxDir: path8.join(root, "inbox"),
|
|
18142
|
+
leasesDir: path8.join(root, "leases"),
|
|
18143
|
+
jobsDir: path8.join(root, "jobs"),
|
|
18144
|
+
mutationsDir: path8.join(root, "mutations"),
|
|
18145
|
+
mutationBlobsDir: path8.join(root, "mutation-blobs"),
|
|
18146
|
+
mutationLocksDir: path8.join(root, "mutation-locks"),
|
|
18147
|
+
undoTransactionsDir: path8.join(root, "undo-transactions"),
|
|
18148
|
+
questionsDir: path8.join(root, "questions")
|
|
18015
18149
|
};
|
|
18016
18150
|
}
|
|
18017
18151
|
function assertNodeStateSchema(stateRoot) {
|
|
18018
18152
|
const paths = getNodeStatePaths(stateRoot);
|
|
18019
|
-
if (!
|
|
18020
|
-
createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations:
|
|
18153
|
+
if (!fs8.existsSync(paths.schemaFile)) throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
18154
|
+
createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: [] }).verify();
|
|
18021
18155
|
}
|
|
18022
18156
|
function ensureNodeStateRoot(stateRoot) {
|
|
18023
18157
|
return initializeNodeStateRoot(stateRoot);
|
|
18024
18158
|
}
|
|
18025
18159
|
function initializeNodeStateRoot(stateRoot) {
|
|
18026
18160
|
try {
|
|
18027
|
-
if (
|
|
18161
|
+
if (fs8.existsSync(stateRoot) && fs8.lstatSync(stateRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
18028
18162
|
const paths = getNodeStatePaths(stateRoot);
|
|
18163
|
+
const recovering = fs8.existsSync(`${paths.root}.schema-original`);
|
|
18164
|
+
if (!recovering && !fs8.existsSync(paths.schemaFile) && fs8.existsSync(paths.root) && fs8.readdirSync(paths.root).length !== 0) throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
18029
18165
|
const manager = createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS });
|
|
18030
18166
|
manager.migrate();
|
|
18167
|
+
assertNodeStateSchema(paths.root);
|
|
18031
18168
|
return paths;
|
|
18032
18169
|
} catch (error) {
|
|
18033
18170
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
@@ -18042,11 +18179,11 @@ function getNodeStateCorruptionDiagnostics(stateRoot) {
|
|
|
18042
18179
|
const directories = [paths.approvalsDir, paths.checkpointsDir, paths.inboxDir, paths.transcriptsDir, paths.questionsDir];
|
|
18043
18180
|
const diagnostics = [];
|
|
18044
18181
|
for (const directory of directories) {
|
|
18045
|
-
if (!
|
|
18046
|
-
for (const entry of
|
|
18047
|
-
const filePath =
|
|
18182
|
+
if (!fs8.existsSync(directory)) continue;
|
|
18183
|
+
for (const entry of fs8.readdirSync(directory).filter((file) => file.endsWith(".jsonl"))) {
|
|
18184
|
+
const filePath = path8.join(directory, entry);
|
|
18048
18185
|
const result = readJsonLines(filePath);
|
|
18049
|
-
for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file:
|
|
18186
|
+
for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file: path8.relative(paths.root, filePath) });
|
|
18050
18187
|
}
|
|
18051
18188
|
}
|
|
18052
18189
|
return diagnostics;
|
|
@@ -18099,9 +18236,9 @@ function createNodeSandboxPort(options) {
|
|
|
18099
18236
|
return result;
|
|
18100
18237
|
}
|
|
18101
18238
|
function protectAuthority(policy) {
|
|
18102
|
-
const settingsRoot =
|
|
18239
|
+
const settingsRoot = path9.join(options.workspaceRoot, ".autopilot");
|
|
18103
18240
|
const writes = [getNodeFileMutationLockRoot(), ...["settings.json", "settings.local.json", "mcp.json"].map(function settingsPath(file) {
|
|
18104
|
-
return
|
|
18241
|
+
return path9.join(settingsRoot, file);
|
|
18105
18242
|
})];
|
|
18106
18243
|
const state = options.stateRoot ? [options.stateRoot, canonicalizeNodePath(options.stateRoot)] : [];
|
|
18107
18244
|
return { ...policy, deniedRead: [.../* @__PURE__ */ new Set([...policy.deniedRead, ...state])], deniedWrite: [.../* @__PURE__ */ new Set([...policy.deniedWrite, ...state, ...writes, ...writes.map(function canonical(candidate) {
|
|
@@ -18296,20 +18433,20 @@ function describePlatform() {
|
|
|
18296
18433
|
}
|
|
18297
18434
|
|
|
18298
18435
|
// src/node/workspace-adapter.ts
|
|
18299
|
-
import
|
|
18300
|
-
import
|
|
18436
|
+
import fs9 from "node:fs";
|
|
18437
|
+
import path10 from "node:path";
|
|
18301
18438
|
function findWorkspaceRoot(startDirectory) {
|
|
18302
18439
|
let current = canonicalizeNodePath(startDirectory);
|
|
18303
18440
|
while (true) {
|
|
18304
|
-
const manifestPath =
|
|
18305
|
-
if (
|
|
18441
|
+
const manifestPath = path10.join(current, "package.json");
|
|
18442
|
+
if (fs9.existsSync(manifestPath)) {
|
|
18306
18443
|
try {
|
|
18307
|
-
const manifest = JSON.parse(
|
|
18444
|
+
const manifest = JSON.parse(fs9.readFileSync(manifestPath, "utf8"));
|
|
18308
18445
|
if (manifest.workspaces) return canonicalizeNodePath(current);
|
|
18309
18446
|
} catch {
|
|
18310
18447
|
}
|
|
18311
18448
|
}
|
|
18312
|
-
const parent =
|
|
18449
|
+
const parent = path10.dirname(current);
|
|
18313
18450
|
if (parent === current) throw new Error("\u65E0\u6CD5\u5B9A\u4F4D Agent \u5DE5\u4F5C\u533A\uFF1B\u8BF7\u8BBE\u7F6E AGENT_WORKSPACE_ROOT");
|
|
18314
18451
|
current = parent;
|
|
18315
18452
|
}
|
|
@@ -18328,20 +18465,20 @@ function createNodeWorkspaceAdapter(options = {}) {
|
|
|
18328
18465
|
const root = canonicalizeWorkspaceRoot(workspaceRoot);
|
|
18329
18466
|
const markers = [];
|
|
18330
18467
|
for (const marker of ["AGENTS.md", ".autopilot", ".claude"]) {
|
|
18331
|
-
if (
|
|
18468
|
+
if (fs9.existsSync(path10.join(root, marker))) markers.push(marker);
|
|
18332
18469
|
}
|
|
18333
18470
|
return {
|
|
18334
18471
|
root,
|
|
18335
18472
|
hasTrustMarker: markers.length > 0,
|
|
18336
18473
|
trustMarkers: markers,
|
|
18337
|
-
displayName:
|
|
18474
|
+
displayName: path10.basename(root)
|
|
18338
18475
|
};
|
|
18339
18476
|
}
|
|
18340
18477
|
return { resolveWorkspaceRoot, canonicalizeWorkspaceRoot, getWorkspaceInfo };
|
|
18341
18478
|
}
|
|
18342
18479
|
|
|
18343
18480
|
// src/node/stores/node-approval-store.ts
|
|
18344
|
-
import
|
|
18481
|
+
import fs10 from "node:fs";
|
|
18345
18482
|
import { AgentRuntimeError as AgentRuntimeError2 } from "@autopilot-agent/core";
|
|
18346
18483
|
function createNodeApprovalStore(options) {
|
|
18347
18484
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
@@ -18349,7 +18486,7 @@ function createNodeApprovalStore(options) {
|
|
|
18349
18486
|
const grantsFile = `${paths.approvalsDir}/grants.jsonl`;
|
|
18350
18487
|
function ensureDir() {
|
|
18351
18488
|
const state = ensureNodeStateRoot(paths.root);
|
|
18352
|
-
|
|
18489
|
+
fs10.mkdirSync(state.approvalsDir, { recursive: true });
|
|
18353
18490
|
}
|
|
18354
18491
|
return {
|
|
18355
18492
|
/** 待审批私有身份复用 decisions.jsonl;记录类型不与真实 decision 混淆。 */
|
|
@@ -18596,15 +18733,15 @@ function createNodeApprovalStore(options) {
|
|
|
18596
18733
|
}
|
|
18597
18734
|
|
|
18598
18735
|
// src/node/settings/node-external-permission-projector.ts
|
|
18599
|
-
import
|
|
18736
|
+
import fs13 from "node:fs";
|
|
18600
18737
|
import os6 from "node:os";
|
|
18601
18738
|
import { resolveAutopilotSettings as resolveAutopilotSettings2 } from "@autopilot-agent/core";
|
|
18602
18739
|
import { isValidExternalPermissionRule } from "@autopilot-agent/core";
|
|
18603
18740
|
|
|
18604
18741
|
// src/node/settings/user-config-directory.ts
|
|
18605
|
-
import
|
|
18742
|
+
import fs11 from "node:fs";
|
|
18606
18743
|
import os4 from "node:os";
|
|
18607
|
-
import
|
|
18744
|
+
import path11 from "node:path";
|
|
18608
18745
|
var UserConfigDirectoryError = class extends Error {
|
|
18609
18746
|
constructor(code) {
|
|
18610
18747
|
super(code);
|
|
@@ -18621,20 +18758,20 @@ function resolveUserHome(homeDirectory) {
|
|
|
18621
18758
|
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18622
18759
|
}
|
|
18623
18760
|
}
|
|
18624
|
-
if (!candidate || !
|
|
18625
|
-
return
|
|
18761
|
+
if (!candidate || !path11.isAbsolute(candidate)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18762
|
+
return path11.resolve(candidate);
|
|
18626
18763
|
}
|
|
18627
18764
|
function readEntry(entryPath) {
|
|
18628
18765
|
try {
|
|
18629
|
-
return
|
|
18766
|
+
return fs11.lstatSync(entryPath);
|
|
18630
18767
|
} catch (error) {
|
|
18631
18768
|
if (error.code === "ENOENT") return void 0;
|
|
18632
18769
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18633
18770
|
}
|
|
18634
18771
|
}
|
|
18635
18772
|
function isWithinHome(homeDirectory, configDirectory) {
|
|
18636
|
-
const relative =
|
|
18637
|
-
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${
|
|
18773
|
+
const relative = path11.relative(homeDirectory, configDirectory);
|
|
18774
|
+
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path11.sep}`) && !path11.isAbsolute(relative);
|
|
18638
18775
|
}
|
|
18639
18776
|
function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
18640
18777
|
const entry = readEntry(configDirectory);
|
|
@@ -18642,8 +18779,8 @@ function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
|
18642
18779
|
if (entry.isSymbolicLink()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
18643
18780
|
if (!entry.isDirectory()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_NOT_DIRECTORY");
|
|
18644
18781
|
try {
|
|
18645
|
-
const canonicalHome =
|
|
18646
|
-
const canonicalConfigDirectory =
|
|
18782
|
+
const canonicalHome = fs11.realpathSync.native(homeDirectory);
|
|
18783
|
+
const canonicalConfigDirectory = fs11.realpathSync.native(configDirectory);
|
|
18647
18784
|
if (!isWithinHome(canonicalHome, canonicalConfigDirectory)) {
|
|
18648
18785
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
18649
18786
|
}
|
|
@@ -18654,12 +18791,12 @@ function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
|
18654
18791
|
}
|
|
18655
18792
|
function ensureUserConfigDirectory(options = {}) {
|
|
18656
18793
|
const homeDirectory = resolveUserHome(options.homeDirectory);
|
|
18657
|
-
const configDirectory =
|
|
18794
|
+
const configDirectory = path11.join(homeDirectory, ".autopilot");
|
|
18658
18795
|
const existing = readEntry(configDirectory);
|
|
18659
18796
|
if (existing) assertSafeConfigDirectory(homeDirectory, configDirectory);
|
|
18660
18797
|
else {
|
|
18661
18798
|
try {
|
|
18662
|
-
|
|
18799
|
+
fs11.mkdirSync(configDirectory, { recursive: true, mode: 448 });
|
|
18663
18800
|
} catch {
|
|
18664
18801
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18665
18802
|
}
|
|
@@ -18669,13 +18806,13 @@ function ensureUserConfigDirectory(options = {}) {
|
|
|
18669
18806
|
}
|
|
18670
18807
|
|
|
18671
18808
|
// src/node/settings/node-settings-loader.ts
|
|
18672
|
-
import
|
|
18809
|
+
import fs12 from "node:fs";
|
|
18673
18810
|
import os5 from "node:os";
|
|
18674
|
-
import
|
|
18811
|
+
import path12 from "node:path";
|
|
18675
18812
|
import {
|
|
18676
18813
|
resolveAutopilotSettings
|
|
18677
18814
|
} from "@autopilot-agent/core";
|
|
18678
|
-
function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi =
|
|
18815
|
+
function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = path12) {
|
|
18679
18816
|
try {
|
|
18680
18817
|
const home = homeDirectory ?? os5.homedir();
|
|
18681
18818
|
if (!pathApi.isAbsolute(home)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
@@ -18684,7 +18821,7 @@ function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = path11) {
|
|
|
18684
18821
|
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18685
18822
|
}
|
|
18686
18823
|
}
|
|
18687
|
-
function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = os5.homedir(), pathApi =
|
|
18824
|
+
function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = os5.homedir(), pathApi = path12) {
|
|
18688
18825
|
const root = pathApi.resolve(workspaceRoot);
|
|
18689
18826
|
return {
|
|
18690
18827
|
user: pathApi.join(homeDirectory, ".autopilot", "settings.json"),
|
|
@@ -18694,14 +18831,14 @@ function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = os5.homedir(),
|
|
|
18694
18831
|
}
|
|
18695
18832
|
function isSafeSettingsFile(filePath) {
|
|
18696
18833
|
try {
|
|
18697
|
-
const file =
|
|
18698
|
-
const configDirectory =
|
|
18699
|
-
const directory =
|
|
18834
|
+
const file = fs12.lstatSync(filePath);
|
|
18835
|
+
const configDirectory = path12.dirname(filePath);
|
|
18836
|
+
const directory = fs12.lstatSync(configDirectory);
|
|
18700
18837
|
if (!file.isFile() || file.isSymbolicLink() || !directory.isDirectory() || directory.isSymbolicLink()) return false;
|
|
18701
|
-
const canonicalDirectory =
|
|
18702
|
-
const canonicalFile =
|
|
18703
|
-
const relative =
|
|
18704
|
-
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${
|
|
18838
|
+
const canonicalDirectory = fs12.realpathSync.native(configDirectory);
|
|
18839
|
+
const canonicalFile = fs12.realpathSync.native(filePath);
|
|
18840
|
+
const relative = path12.relative(canonicalDirectory, canonicalFile);
|
|
18841
|
+
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path12.sep}`) && !path12.isAbsolute(relative);
|
|
18705
18842
|
} catch (error) {
|
|
18706
18843
|
return error.code === "ENOENT";
|
|
18707
18844
|
}
|
|
@@ -18709,9 +18846,9 @@ function isSafeSettingsFile(filePath) {
|
|
|
18709
18846
|
function createNodeSettingsLoader(options = {}) {
|
|
18710
18847
|
const debounceMs = options.debounceMs ?? 100;
|
|
18711
18848
|
function readSource(scope, filePath) {
|
|
18712
|
-
if (!
|
|
18849
|
+
if (!fs12.existsSync(filePath)) {
|
|
18713
18850
|
try {
|
|
18714
|
-
if (
|
|
18851
|
+
if (fs12.lstatSync(filePath).isSymbolicLink()) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
18715
18852
|
} catch {
|
|
18716
18853
|
return void 0;
|
|
18717
18854
|
}
|
|
@@ -18719,7 +18856,7 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18719
18856
|
}
|
|
18720
18857
|
if (!isSafeSettingsFile(filePath)) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
18721
18858
|
try {
|
|
18722
|
-
return { scope, value: JSON.parse(
|
|
18859
|
+
return { scope, value: JSON.parse(fs12.readFileSync(filePath, "utf8")), diagnostics: [] };
|
|
18723
18860
|
} catch {
|
|
18724
18861
|
return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_JSON_INVALID" }] };
|
|
18725
18862
|
}
|
|
@@ -18755,18 +18892,18 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18755
18892
|
function installWatchers() {
|
|
18756
18893
|
for (const watcher of watchers) watcher.close();
|
|
18757
18894
|
const uniqueDirectories = [...new Set(watched.flatMap(function collectWatchDirectories(filePath) {
|
|
18758
|
-
const directory =
|
|
18759
|
-
return [directory,
|
|
18895
|
+
const directory = path12.dirname(filePath);
|
|
18896
|
+
return [directory, path12.dirname(directory)];
|
|
18760
18897
|
}))].filter(
|
|
18761
18898
|
/** 不把用户配置目录的链接目标注册为监听面;父目录仍能观察链接被替换。 */
|
|
18762
18899
|
function safeWatchDirectory(directory) {
|
|
18763
|
-
return
|
|
18900
|
+
return fs12.existsSync(directory) && fs12.lstatSync(directory).isDirectory() && !fs12.lstatSync(directory).isSymbolicLink();
|
|
18764
18901
|
}
|
|
18765
18902
|
);
|
|
18766
18903
|
watchers = uniqueDirectories.flatMap(function watchParent(directory) {
|
|
18767
18904
|
try {
|
|
18768
|
-
const watcher =
|
|
18769
|
-
if (!fileName || !watched.some((target) =>
|
|
18905
|
+
const watcher = fs12.watch(directory, function reloadOnTargetFile(_eventType, fileName) {
|
|
18906
|
+
if (!fileName || !watched.some((target) => path12.basename(target) === fileName.toString() || path12.basename(path12.dirname(target)) === fileName.toString())) return;
|
|
18770
18907
|
if (timer) clearTimeout(timer);
|
|
18771
18908
|
timer = setTimeout(function reloadAfterDebounce() {
|
|
18772
18909
|
reload();
|
|
@@ -18795,16 +18932,16 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18795
18932
|
function readScopeValue(filePath, strict = false) {
|
|
18796
18933
|
if (strict) {
|
|
18797
18934
|
try {
|
|
18798
|
-
|
|
18935
|
+
fs13.lstatSync(filePath);
|
|
18799
18936
|
} catch (error) {
|
|
18800
18937
|
if (error.code === "ENOENT") return {};
|
|
18801
18938
|
throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
|
|
18802
18939
|
}
|
|
18803
18940
|
if (!isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
|
|
18804
|
-
} else if (!
|
|
18941
|
+
} else if (!fs13.existsSync(filePath) || !isSafeSettingsFile(filePath)) return {};
|
|
18805
18942
|
let content;
|
|
18806
18943
|
try {
|
|
18807
|
-
content =
|
|
18944
|
+
content = fs13.readFileSync(filePath, "utf8");
|
|
18808
18945
|
} catch {
|
|
18809
18946
|
if (strict) throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
|
|
18810
18947
|
return {};
|
|
@@ -18849,8 +18986,8 @@ function createNodeExternalPermissionProjector(options = {}) {
|
|
|
18849
18986
|
const resolved = resolveAutopilotSettings2([{ scope: "local", value: updated }]);
|
|
18850
18987
|
if (resolved.permissions.restricted === true) throw new Error("EXTERNAL_RULE_PERMISSIONS_UNSAFE");
|
|
18851
18988
|
if (next.length === 0 && Object.keys(permissions).length === 1) delete updated.permissions;
|
|
18852
|
-
if (
|
|
18853
|
-
|
|
18989
|
+
if (fs13.existsSync(filePath) && !isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
|
|
18990
|
+
fs13.mkdirSync(resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory ?? os6.homedir()).local.replace(/[/\\]settings\.local\.json$/u, ""), { recursive: true });
|
|
18854
18991
|
atomicReplace(filePath, `${JSON.stringify(updated, null, 2)}
|
|
18855
18992
|
`);
|
|
18856
18993
|
});
|
|
@@ -18869,16 +19006,16 @@ function createNodeExternalPermissionProjector(options = {}) {
|
|
|
18869
19006
|
}
|
|
18870
19007
|
|
|
18871
19008
|
// src/node/host-mutation-protection.ts
|
|
18872
|
-
import
|
|
19009
|
+
import path13 from "node:path";
|
|
18873
19010
|
function createNodeHostMutationProtection(options) {
|
|
18874
|
-
const stateRoot =
|
|
18875
|
-
const trustFile =
|
|
19011
|
+
const stateRoot = path13.resolve(options.stateRoot);
|
|
19012
|
+
const trustFile = path13.join(resolveNodeTrustRoot(options), "trust.json");
|
|
18876
19013
|
const fixedTargets = [
|
|
18877
19014
|
{ path: getNodeFileMutationLockRoot(), scope: "directory" },
|
|
18878
19015
|
{ path: stateRoot, scope: "directory" },
|
|
18879
19016
|
{ path: canonicalizeNodePath(stateRoot), scope: "directory" },
|
|
18880
19017
|
{ path: trustFile, scope: "file" },
|
|
18881
|
-
...options.userSettingsPath ? [{ path:
|
|
19018
|
+
...options.userSettingsPath ? [{ path: path13.resolve(options.userSettingsPath), scope: "file" }] : []
|
|
18882
19019
|
];
|
|
18883
19020
|
return {
|
|
18884
19021
|
/** 权限配置路径复用真实User/Project/Local resolver,每次保留原路径与canonical判定。 */
|
|
@@ -18894,47 +19031,120 @@ function createNodeHostMutationProtection(options) {
|
|
|
18894
19031
|
}
|
|
18895
19032
|
|
|
18896
19033
|
// src/node/stores/node-checkpoint-store.ts
|
|
18897
|
-
import
|
|
19034
|
+
import fs14 from "node:fs";
|
|
19035
|
+
import path14 from "node:path";
|
|
19036
|
+
import { createInterface } from "node:readline";
|
|
18898
19037
|
function createNodeCheckpointStore(options) {
|
|
18899
19038
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19039
|
+
const latestCache = /* @__PURE__ */ new Map();
|
|
19040
|
+
let cacheBytes = 0;
|
|
19041
|
+
function signature(target) {
|
|
19042
|
+
try {
|
|
19043
|
+
const stat = fs14.statSync(target, { bigint: true });
|
|
19044
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.birthtimeNs}`;
|
|
19045
|
+
} catch (error) {
|
|
19046
|
+
if (error.code === "ENOENT") return "missing";
|
|
19047
|
+
throw error;
|
|
19048
|
+
}
|
|
19049
|
+
}
|
|
19050
|
+
function invalidate(key2) {
|
|
19051
|
+
const previous = latestCache.get(key2);
|
|
19052
|
+
if (previous) cacheBytes -= previous.bytes;
|
|
19053
|
+
latestCache.delete(key2);
|
|
19054
|
+
}
|
|
19055
|
+
function invalidateSession(sessionId) {
|
|
19056
|
+
for (const key2 of latestCache.keys()) if (JSON.parse(key2)[0] === sessionId) invalidate(key2);
|
|
19057
|
+
}
|
|
18900
19058
|
function ensureDir() {
|
|
18901
19059
|
const state = ensureNodeStateRoot(paths.root);
|
|
18902
|
-
|
|
19060
|
+
fs14.mkdirSync(state.checkpointsDir, { recursive: true });
|
|
18903
19061
|
}
|
|
18904
19062
|
function filePath(sessionId) {
|
|
18905
19063
|
return safeFilePath(paths.checkpointsDir, sessionId, ".jsonl");
|
|
18906
19064
|
}
|
|
18907
|
-
function
|
|
18908
|
-
const
|
|
18909
|
-
|
|
18910
|
-
|
|
18911
|
-
|
|
18912
|
-
|
|
18913
|
-
|
|
18914
|
-
|
|
18915
|
-
|
|
19065
|
+
async function readCheckpoint(sessionId, turnId) {
|
|
19066
|
+
const target = filePath(sessionId);
|
|
19067
|
+
const key2 = JSON.stringify([sessionId, turnId ?? null]);
|
|
19068
|
+
try {
|
|
19069
|
+
const before2 = signature(target);
|
|
19070
|
+
const cached = latestCache.get(key2);
|
|
19071
|
+
if (cached?.signature === before2) {
|
|
19072
|
+
latestCache.delete(key2);
|
|
19073
|
+
latestCache.set(key2, cached);
|
|
19074
|
+
return structuredClone(cached.checkpoint);
|
|
19075
|
+
}
|
|
19076
|
+
invalidate(key2);
|
|
19077
|
+
let checkpoint = null;
|
|
19078
|
+
let bytes = 0;
|
|
19079
|
+
const corrupted = [];
|
|
19080
|
+
if (before2 !== "missing") {
|
|
19081
|
+
let failRead2 = function(error) {
|
|
19082
|
+
readError = error;
|
|
19083
|
+
lines.close();
|
|
19084
|
+
};
|
|
19085
|
+
var failRead = failRead2;
|
|
19086
|
+
const input = fs14.createReadStream(target, { encoding: "utf8", highWaterMark: 64 * 1024 });
|
|
19087
|
+
const lines = createInterface({ input, crlfDelay: Infinity });
|
|
19088
|
+
let readError;
|
|
19089
|
+
input.on("error", failRead2);
|
|
19090
|
+
let lineNumber = 0;
|
|
19091
|
+
try {
|
|
19092
|
+
for await (const line of lines) {
|
|
19093
|
+
lineNumber++;
|
|
19094
|
+
if (!line) continue;
|
|
19095
|
+
try {
|
|
19096
|
+
const value = JSON.parse(line);
|
|
19097
|
+
if (!turnId || value?.turnId === turnId) {
|
|
19098
|
+
checkpoint = value;
|
|
19099
|
+
bytes = Buffer.byteLength(line, "utf8");
|
|
19100
|
+
}
|
|
19101
|
+
} catch {
|
|
19102
|
+
corrupted.push(lineNumber);
|
|
19103
|
+
}
|
|
19104
|
+
await new Promise(function yieldParsing(resolve) {
|
|
19105
|
+
setImmediate(resolve);
|
|
19106
|
+
});
|
|
19107
|
+
}
|
|
19108
|
+
if (readError) throw readError;
|
|
19109
|
+
} finally {
|
|
19110
|
+
lines.close();
|
|
19111
|
+
input.destroy();
|
|
19112
|
+
input.off("error", failRead2);
|
|
19113
|
+
}
|
|
19114
|
+
}
|
|
19115
|
+
if (corrupted.length) console.warn(`[DURABLE_JSONL_CORRUPTED] file=${path14.basename(target)} records=${corrupted.length} lines=${corrupted.join(",")}`);
|
|
19116
|
+
if (!corrupted.length && before2 === signature(target) && bytes <= 8 * 1024 * 1024) {
|
|
19117
|
+
while (latestCache.size >= 8 || cacheBytes + bytes > 8 * 1024 * 1024) invalidate(latestCache.keys().next().value);
|
|
19118
|
+
latestCache.set(key2, { signature: before2, checkpoint, bytes });
|
|
19119
|
+
cacheBytes += bytes;
|
|
19120
|
+
return structuredClone(checkpoint);
|
|
19121
|
+
}
|
|
19122
|
+
return checkpoint;
|
|
19123
|
+
} catch (error) {
|
|
19124
|
+
invalidate(key2);
|
|
19125
|
+
throw error;
|
|
18916
19126
|
}
|
|
18917
|
-
return null;
|
|
18918
19127
|
}
|
|
18919
19128
|
return {
|
|
18920
19129
|
async getLatest(sessionId) {
|
|
18921
19130
|
ensureDir();
|
|
18922
|
-
return withFileLock(filePath(sessionId), () =>
|
|
19131
|
+
return withFileLock(filePath(sessionId), () => readCheckpoint(sessionId));
|
|
18923
19132
|
},
|
|
18924
19133
|
async getByTurn(sessionId, turnId) {
|
|
18925
19134
|
ensureDir();
|
|
18926
|
-
return withFileLock(filePath(sessionId), () =>
|
|
19135
|
+
return withFileLock(filePath(sessionId), () => readCheckpoint(sessionId, turnId));
|
|
18927
19136
|
},
|
|
18928
19137
|
async save(sessionId, checkpoint) {
|
|
18929
19138
|
ensureDir();
|
|
18930
19139
|
await withFileLock(filePath(sessionId), () => {
|
|
19140
|
+
invalidateSession(sessionId);
|
|
18931
19141
|
appendJsonLine(filePath(sessionId), JSON.stringify(checkpoint));
|
|
18932
19142
|
});
|
|
18933
19143
|
},
|
|
18934
19144
|
async recoverStale(sessionId, now, staleAfterMs) {
|
|
18935
19145
|
ensureDir();
|
|
18936
|
-
return withFileLock(filePath(sessionId), ()
|
|
18937
|
-
const latest =
|
|
19146
|
+
return withFileLock(filePath(sessionId), async function recover() {
|
|
19147
|
+
const latest = await readCheckpoint(sessionId);
|
|
18938
19148
|
if (!latest) return null;
|
|
18939
19149
|
if (latest.status !== "running" || !latest.lease || now - latest.lease.heartbeatAt <= staleAfterMs) return latest;
|
|
18940
19150
|
const recovered = {
|
|
@@ -18942,6 +19152,7 @@ function createNodeCheckpointStore(options) {
|
|
|
18942
19152
|
status: "interrupted_recoverable",
|
|
18943
19153
|
interruptionReason: "stale_lease"
|
|
18944
19154
|
};
|
|
19155
|
+
invalidateSession(sessionId);
|
|
18945
19156
|
appendJsonLine(filePath(sessionId), JSON.stringify(recovered));
|
|
18946
19157
|
return recovered;
|
|
18947
19158
|
});
|
|
@@ -18950,7 +19161,8 @@ function createNodeCheckpointStore(options) {
|
|
|
18950
19161
|
ensureDir();
|
|
18951
19162
|
const target = filePath(sessionId);
|
|
18952
19163
|
await withFileLock(target, () => {
|
|
18953
|
-
|
|
19164
|
+
invalidateSession(sessionId);
|
|
19165
|
+
if (fs14.existsSync(target)) fs14.unlinkSync(target);
|
|
18954
19166
|
});
|
|
18955
19167
|
}
|
|
18956
19168
|
};
|
|
@@ -18967,12 +19179,13 @@ function createNodeEventSink(_options) {
|
|
|
18967
19179
|
|
|
18968
19180
|
// src/node/stores/node-input-inbox.ts
|
|
18969
19181
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
18970
|
-
import
|
|
19182
|
+
import fs15 from "node:fs";
|
|
19183
|
+
import { inboxOriginKey } from "@autopilot-agent/core";
|
|
18971
19184
|
function createNodeInputInbox(options) {
|
|
18972
19185
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
18973
19186
|
function ensureDir() {
|
|
18974
19187
|
const state = ensureNodeStateRoot(paths.root);
|
|
18975
|
-
|
|
19188
|
+
fs15.mkdirSync(state.inboxDir, { recursive: true });
|
|
18976
19189
|
}
|
|
18977
19190
|
function filePath(sessionId) {
|
|
18978
19191
|
return safeFilePath(paths.inboxDir, sessionId, ".jsonl");
|
|
@@ -18995,7 +19208,10 @@ function createNodeInputInbox(options) {
|
|
|
18995
19208
|
const inputs = readInbox(input.sessionId);
|
|
18996
19209
|
if (input.clientMessageId) {
|
|
18997
19210
|
const existing = inputs.find((candidate) => candidate.clientMessageId === input.clientMessageId);
|
|
18998
|
-
if (existing)
|
|
19211
|
+
if (existing) {
|
|
19212
|
+
if (existing.content !== input.content || inboxOriginKey(existing.origin) !== inboxOriginKey(input.origin)) throw new Error("INBOX_INPUT_CONFLICT");
|
|
19213
|
+
return existing;
|
|
19214
|
+
}
|
|
18999
19215
|
}
|
|
19000
19216
|
const inboxInput = {
|
|
19001
19217
|
inputId: randomUUID3(),
|
|
@@ -19007,6 +19223,7 @@ function createNodeInputInbox(options) {
|
|
|
19007
19223
|
clientMessageId: input.clientMessageId,
|
|
19008
19224
|
attachments: input.attachments ?? [],
|
|
19009
19225
|
selectedSkills: input.selectedSkills ?? [],
|
|
19226
|
+
origin: input.origin,
|
|
19010
19227
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
19011
19228
|
};
|
|
19012
19229
|
inputs.push(inboxInput);
|
|
@@ -19059,7 +19276,7 @@ function createNodeInputInbox(options) {
|
|
|
19059
19276
|
},
|
|
19060
19277
|
async cancel(inputId) {
|
|
19061
19278
|
ensureDir();
|
|
19062
|
-
const files =
|
|
19279
|
+
const files = fs15.readdirSync(paths.inboxDir).filter((file) => file.endsWith(".jsonl"));
|
|
19063
19280
|
for (const file of files) {
|
|
19064
19281
|
const sessionId = file.slice(0, -6);
|
|
19065
19282
|
const cancelled = await withFileLock(filePath(sessionId), () => {
|
|
@@ -19078,7 +19295,7 @@ function createNodeInputInbox(options) {
|
|
|
19078
19295
|
ensureDir();
|
|
19079
19296
|
const target = filePath(sessionId);
|
|
19080
19297
|
await withFileLock(target, () => {
|
|
19081
|
-
if (
|
|
19298
|
+
if (fs15.existsSync(target)) fs15.unlinkSync(target);
|
|
19082
19299
|
});
|
|
19083
19300
|
},
|
|
19084
19301
|
async waitForInput(_query) {
|
|
@@ -19088,20 +19305,20 @@ function createNodeInputInbox(options) {
|
|
|
19088
19305
|
|
|
19089
19306
|
// src/node/stores/node-project-store.ts
|
|
19090
19307
|
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
19091
|
-
import
|
|
19308
|
+
import fs16 from "node:fs";
|
|
19092
19309
|
function createNodeProjectStore(options) {
|
|
19093
19310
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19094
19311
|
function ensureDir() {
|
|
19095
19312
|
const state = ensureNodeStateRoot(paths.root);
|
|
19096
|
-
|
|
19313
|
+
fs16.mkdirSync(state.projectsDir, { recursive: true });
|
|
19097
19314
|
}
|
|
19098
19315
|
function filePath(projectId) {
|
|
19099
19316
|
return safeFilePath(paths.projectsDir, projectId, ".json");
|
|
19100
19317
|
}
|
|
19101
19318
|
return {
|
|
19102
19319
|
async get(id) {
|
|
19103
|
-
|
|
19104
|
-
return
|
|
19320
|
+
assertNodeStateSchema(paths.root);
|
|
19321
|
+
return readJsonFile(filePath(id));
|
|
19105
19322
|
},
|
|
19106
19323
|
async save(project) {
|
|
19107
19324
|
ensureDir();
|
|
@@ -19110,9 +19327,10 @@ function createNodeProjectStore(options) {
|
|
|
19110
19327
|
});
|
|
19111
19328
|
},
|
|
19112
19329
|
async list() {
|
|
19113
|
-
|
|
19330
|
+
assertNodeStateSchema(paths.root);
|
|
19114
19331
|
const projects = [];
|
|
19115
|
-
|
|
19332
|
+
if (!fs16.existsSync(paths.projectsDir)) return projects;
|
|
19333
|
+
for (const file of fs16.readdirSync(paths.projectsDir).filter((entry) => entry.endsWith(".json"))) {
|
|
19116
19334
|
const project = readJsonFile(filePath(file.slice(0, -5)));
|
|
19117
19335
|
if (project) projects.push(project);
|
|
19118
19336
|
}
|
|
@@ -19137,40 +19355,42 @@ function createNodeProjectStore(options) {
|
|
|
19137
19355
|
ensureDir();
|
|
19138
19356
|
const target = filePath(id);
|
|
19139
19357
|
return withFileLock(target, () => {
|
|
19140
|
-
if (!
|
|
19141
|
-
|
|
19358
|
+
if (!fs16.existsSync(target)) return false;
|
|
19359
|
+
fs16.unlinkSync(target);
|
|
19142
19360
|
return true;
|
|
19143
19361
|
});
|
|
19144
19362
|
}
|
|
19145
19363
|
};
|
|
19146
19364
|
}
|
|
19147
19365
|
|
|
19148
|
-
// src/node/stores/node-
|
|
19149
|
-
import
|
|
19366
|
+
// src/node/stores/node-thread-store.ts
|
|
19367
|
+
import { sanitizeContinuationFailure } from "@autopilot-agent/core";
|
|
19368
|
+
import fs18 from "node:fs";
|
|
19369
|
+
import path16 from "node:path";
|
|
19150
19370
|
|
|
19151
19371
|
// src/node/chat-state.ts
|
|
19152
|
-
import
|
|
19372
|
+
import fs17 from "node:fs";
|
|
19153
19373
|
import os7 from "node:os";
|
|
19154
|
-
import
|
|
19374
|
+
import path15 from "node:path";
|
|
19155
19375
|
function resolveNodeChatStatePaths(options = {}) {
|
|
19156
19376
|
try {
|
|
19157
|
-
if (options.globalStateRoot !== void 0 && !
|
|
19377
|
+
if (options.globalStateRoot !== void 0 && !path15.isAbsolute(options.globalStateRoot)) throw new NodeChatError("CHAT_STATE_ROOT_INVALID");
|
|
19158
19378
|
const globalRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: os7.homedir() });
|
|
19159
|
-
const root =
|
|
19160
|
-
return { root, stateRoot:
|
|
19379
|
+
const root = path15.join(globalRoot, "chat");
|
|
19380
|
+
return { root, stateRoot: path15.join(root, "state"), attachmentsRoot: path15.join(root, "attachments"), knowledgeRoot: path15.join(root, "knowledge") };
|
|
19161
19381
|
} catch (error) {
|
|
19162
19382
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19163
19383
|
}
|
|
19164
19384
|
}
|
|
19165
19385
|
function assertSafeNodePath(root, target) {
|
|
19166
19386
|
try {
|
|
19167
|
-
const relative =
|
|
19168
|
-
if (relative === ".." || relative.startsWith(`..${
|
|
19387
|
+
const relative = path15.relative(root, target);
|
|
19388
|
+
if (relative === ".." || relative.startsWith(`..${path15.sep}`) || path15.isAbsolute(relative)) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19169
19389
|
let current = root;
|
|
19170
|
-
for (const segment of ["", ...relative.split(
|
|
19171
|
-
if (segment) current =
|
|
19390
|
+
for (const segment of ["", ...relative.split(path15.sep).filter(Boolean)]) {
|
|
19391
|
+
if (segment) current = path15.join(current, segment);
|
|
19172
19392
|
try {
|
|
19173
|
-
const entry =
|
|
19393
|
+
const entry = fs17.lstatSync(current);
|
|
19174
19394
|
if (entry.isSymbolicLink() || current !== target && !entry.isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19175
19395
|
} catch (error) {
|
|
19176
19396
|
if (error.code !== "ENOENT") throw error;
|
|
@@ -19184,19 +19404,396 @@ function assertSafeNodePath(root, target) {
|
|
|
19184
19404
|
function ensureChatDirectory(root, target) {
|
|
19185
19405
|
try {
|
|
19186
19406
|
assertSafeNodePath(root, target);
|
|
19187
|
-
|
|
19407
|
+
fs17.mkdirSync(target, { recursive: true, mode: 448 });
|
|
19188
19408
|
assertSafeNodePath(root, target);
|
|
19189
|
-
if (!
|
|
19409
|
+
if (!fs17.lstatSync(target).isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19190
19410
|
} catch (error) {
|
|
19191
19411
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19192
19412
|
}
|
|
19193
19413
|
}
|
|
19194
19414
|
function initializeNodeChatDirectories(paths) {
|
|
19195
|
-
ensureChatDirectory(
|
|
19415
|
+
ensureChatDirectory(path15.dirname(paths.root), paths.root);
|
|
19196
19416
|
ensureChatDirectory(paths.root, paths.stateRoot);
|
|
19197
19417
|
ensureChatDirectory(paths.root, paths.attachmentsRoot);
|
|
19198
19418
|
}
|
|
19199
19419
|
|
|
19420
|
+
// src/node/stores/node-thread-store.ts
|
|
19421
|
+
function createNodeThreadStore(stateRoot) {
|
|
19422
|
+
const groups = path16.join(stateRoot, "threads", "groups");
|
|
19423
|
+
const controlCache = /* @__PURE__ */ new Map();
|
|
19424
|
+
let controlCacheBytes = 0;
|
|
19425
|
+
function controlSignature(target) {
|
|
19426
|
+
const stat = fs18.statSync(target, { bigint: true });
|
|
19427
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.birthtimeNs}`;
|
|
19428
|
+
}
|
|
19429
|
+
function forgetControl(target) {
|
|
19430
|
+
controlCacheBytes -= controlCache.get(target)?.bytes ?? 0;
|
|
19431
|
+
controlCache.delete(target);
|
|
19432
|
+
}
|
|
19433
|
+
function assertTargetRoot() {
|
|
19434
|
+
const manifest = path16.join(stateRoot, "schema.json");
|
|
19435
|
+
let value;
|
|
19436
|
+
try {
|
|
19437
|
+
if (fs18.lstatSync(stateRoot).isSymbolicLink() || fs18.lstatSync(manifest).isSymbolicLink()) throw new Error("unsafe");
|
|
19438
|
+
value = JSON.parse(fs18.readFileSync(manifest, "utf8"));
|
|
19439
|
+
} catch {
|
|
19440
|
+
throw new Error("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
19441
|
+
}
|
|
19442
|
+
if (!value || typeof value !== "object" || value.schemaVersion !== 8) throw new Error("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
19443
|
+
}
|
|
19444
|
+
function controlPath(groupId) {
|
|
19445
|
+
const target = path16.join(safeFilePath(groups, groupId, ""), "control.json");
|
|
19446
|
+
assertSafeNodePath(stateRoot, target);
|
|
19447
|
+
return target;
|
|
19448
|
+
}
|
|
19449
|
+
function assertInteractionControls(control) {
|
|
19450
|
+
if (control.controls !== void 0 && !Array.isArray(control.controls)) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19451
|
+
for (const intent of control.controls ?? []) {
|
|
19452
|
+
if (intent?.kind !== "continue_interaction") continue;
|
|
19453
|
+
if (intent.failureDiagnostic !== void 0 && (!sanitizeContinuationFailure(intent.failureDiagnostic) || Object.keys(intent.failureDiagnostic).some(function invalid(key2) {
|
|
19454
|
+
return !Object.prototype.hasOwnProperty.call(sanitizeContinuationFailure(intent.failureDiagnostic), key2) || intent.failureDiagnostic[key2] !== sanitizeContinuationFailure(intent.failureDiagnostic)[key2];
|
|
19455
|
+
}))) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19456
|
+
const ids = [intent.controlId, intent.threadId, intent.expectedTurnId, intent.approvalId ?? intent.requestId];
|
|
19457
|
+
if (ids.some(function invalid(id) {
|
|
19458
|
+
return typeof id !== "string" || !id || id.length > 200 || /[\\/\x00-\x1f]/u.test(id);
|
|
19459
|
+
}) || 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");
|
|
19460
|
+
}
|
|
19461
|
+
}
|
|
19462
|
+
function read(groupId) {
|
|
19463
|
+
const target = controlPath(groupId);
|
|
19464
|
+
try {
|
|
19465
|
+
const before2 = controlSignature(target);
|
|
19466
|
+
const cached = controlCache.get(target);
|
|
19467
|
+
if (cached?.signature === before2) {
|
|
19468
|
+
controlCache.delete(target);
|
|
19469
|
+
controlCache.set(target, cached);
|
|
19470
|
+
return structuredClone(cached.value);
|
|
19471
|
+
}
|
|
19472
|
+
forgetControl(target);
|
|
19473
|
+
const text = fs18.readFileSync(target, "utf8");
|
|
19474
|
+
let value;
|
|
19475
|
+
try {
|
|
19476
|
+
value = JSON.parse(text);
|
|
19477
|
+
} catch {
|
|
19478
|
+
throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19479
|
+
}
|
|
19480
|
+
if (!value || value.group?.groupId !== groupId || !Number.isSafeInteger(value.revision) || value.revision < 0) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19481
|
+
assertInteractionControls(value);
|
|
19482
|
+
const bytes = Buffer.byteLength(text, "utf8");
|
|
19483
|
+
if (bytes <= 8 * 1024 * 1024 && before2 === controlSignature(target)) {
|
|
19484
|
+
while (controlCache.size >= 128 || controlCacheBytes + bytes > 8 * 1024 * 1024) forgetControl(controlCache.keys().next().value);
|
|
19485
|
+
controlCache.set(target, { signature: before2, value, bytes });
|
|
19486
|
+
controlCacheBytes += bytes;
|
|
19487
|
+
return structuredClone(value);
|
|
19488
|
+
}
|
|
19489
|
+
return value;
|
|
19490
|
+
} catch (error) {
|
|
19491
|
+
forgetControl(target);
|
|
19492
|
+
if (error.code === "ENOENT") return null;
|
|
19493
|
+
throw error;
|
|
19494
|
+
}
|
|
19495
|
+
}
|
|
19496
|
+
function messagePath(groupId, threadId, seq2) {
|
|
19497
|
+
if (!Number.isSafeInteger(seq2) || seq2 < 1) throw new Error("THREAD_CURSOR_INVALID");
|
|
19498
|
+
const dir = path16.join(safeFilePath(groups, groupId, ""), "messages");
|
|
19499
|
+
const threadDir = safeFilePath(dir, threadId, "");
|
|
19500
|
+
const target = safeFilePath(threadDir, String(seq2), ".json");
|
|
19501
|
+
assertSafeNodePath(stateRoot, target);
|
|
19502
|
+
return target;
|
|
19503
|
+
}
|
|
19504
|
+
function readMessage(groupId, threadId, seq2) {
|
|
19505
|
+
let value;
|
|
19506
|
+
try {
|
|
19507
|
+
value = JSON.parse(fs18.readFileSync(messagePath(groupId, threadId, seq2), "utf8"));
|
|
19508
|
+
} catch (error) {
|
|
19509
|
+
if (error.code === "ENOENT") return null;
|
|
19510
|
+
throw new Error("THREAD_MESSAGE_CORRUPTED");
|
|
19511
|
+
}
|
|
19512
|
+
if (!value || value.groupId !== groupId || value.toThreadId !== threadId || value.deliverySeq !== seq2) throw new Error("THREAD_MESSAGE_CORRUPTED");
|
|
19513
|
+
return value;
|
|
19514
|
+
}
|
|
19515
|
+
function eventPath(groupId, seq2) {
|
|
19516
|
+
if (!Number.isSafeInteger(seq2) || seq2 < 1) throw new Error("THREAD_CURSOR_INVALID");
|
|
19517
|
+
const dir = path16.join(safeFilePath(groups, groupId, ""), "events");
|
|
19518
|
+
const target = safeFilePath(dir, String(seq2), ".json");
|
|
19519
|
+
assertSafeNodePath(stateRoot, target);
|
|
19520
|
+
return target;
|
|
19521
|
+
}
|
|
19522
|
+
function readEvent(groupId, seq2) {
|
|
19523
|
+
let value;
|
|
19524
|
+
try {
|
|
19525
|
+
value = JSON.parse(fs18.readFileSync(eventPath(groupId, seq2), "utf8"));
|
|
19526
|
+
} catch (error) {
|
|
19527
|
+
if (error.code === "ENOENT") return null;
|
|
19528
|
+
throw new Error("THREAD_EVENT_CORRUPTED");
|
|
19529
|
+
}
|
|
19530
|
+
if (!value || value.groupId !== groupId || value.groupSeq !== seq2) throw new Error("THREAD_EVENT_CORRUPTED");
|
|
19531
|
+
return value;
|
|
19532
|
+
}
|
|
19533
|
+
function readRequest(id) {
|
|
19534
|
+
const target = safeFilePath(path16.join(stateRoot, "threads", "requests"), id, ".json");
|
|
19535
|
+
assertSafeNodePath(stateRoot, target);
|
|
19536
|
+
try {
|
|
19537
|
+
return JSON.parse(fs18.readFileSync(target, "utf8"));
|
|
19538
|
+
} catch (error) {
|
|
19539
|
+
if (error.code === "ENOENT") return null;
|
|
19540
|
+
throw new Error("THREAD_REQUEST_CORRUPTED");
|
|
19541
|
+
}
|
|
19542
|
+
}
|
|
19543
|
+
return {
|
|
19544
|
+
/** 只读检查,和预留中的最终检查共同处理并发。 */
|
|
19545
|
+
async verifyRequest(id, groupId, payloadDigest) {
|
|
19546
|
+
assertTargetRoot();
|
|
19547
|
+
const prior = readRequest(id);
|
|
19548
|
+
if (prior && (prior.groupId !== groupId || prior.payloadDigest !== payloadDigest)) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19549
|
+
},
|
|
19550
|
+
/** 请求身份独立于组,跨进程锁内持久预留,冲突不得重绑。 */
|
|
19551
|
+
async reserveRequest(id, groupId, payloadDigest) {
|
|
19552
|
+
assertTargetRoot();
|
|
19553
|
+
const target = safeFilePath(path16.join(stateRoot, "threads", "requests"), id, ".json");
|
|
19554
|
+
assertSafeNodePath(stateRoot, target);
|
|
19555
|
+
await withFileLock(target, function reserveLocked() {
|
|
19556
|
+
if (fs18.existsSync(target)) {
|
|
19557
|
+
let prior;
|
|
19558
|
+
try {
|
|
19559
|
+
prior = JSON.parse(fs18.readFileSync(target, "utf8"));
|
|
19560
|
+
} catch {
|
|
19561
|
+
throw new Error("THREAD_REQUEST_CORRUPTED");
|
|
19562
|
+
}
|
|
19563
|
+
if (prior.groupId !== groupId || prior.payloadDigest !== payloadDigest) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19564
|
+
return;
|
|
19565
|
+
}
|
|
19566
|
+
atomicReplace(target, JSON.stringify({ groupId, payloadDigest }));
|
|
19567
|
+
}, { requireExitedOwner: true });
|
|
19568
|
+
},
|
|
19569
|
+
/** 同序号重放幂等,不同事件冲突。 */
|
|
19570
|
+
async writeEvent(event) {
|
|
19571
|
+
assertTargetRoot();
|
|
19572
|
+
const target = eventPath(event.groupId, event.groupSeq);
|
|
19573
|
+
const serialized = JSON.stringify(event);
|
|
19574
|
+
if (Buffer.byteLength(serialized, "utf8") > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
19575
|
+
await withFileLock(target, function writeEventLocked() {
|
|
19576
|
+
const previous = readEvent(event.groupId, event.groupSeq);
|
|
19577
|
+
if (previous && JSON.stringify(previous) !== serialized) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19578
|
+
if (!previous) atomicReplace(target, serialized);
|
|
19579
|
+
}, { requireExitedOwner: true });
|
|
19580
|
+
},
|
|
19581
|
+
/** 查询不创建锁或目录。 */
|
|
19582
|
+
async readEvent(groupId, seq2) {
|
|
19583
|
+
assertTargetRoot();
|
|
19584
|
+
return readEvent(groupId, seq2);
|
|
19585
|
+
},
|
|
19586
|
+
/** 短期 Session 锁只覆盖元数据变更与删除,不覆盖 Turn 执行。 */
|
|
19587
|
+
async withSessionLock(threadId, operation) {
|
|
19588
|
+
assertTargetRoot();
|
|
19589
|
+
const target = safeFilePath(path16.join(stateRoot, "threads", "session-locks"), threadId, "");
|
|
19590
|
+
assertSafeNodePath(stateRoot, target);
|
|
19591
|
+
return withFileLock(target, operation, { requireExitedOwner: true });
|
|
19592
|
+
},
|
|
19593
|
+
/** 检查全部组控制记录;损坏记录明确报错,不遗漏受管引用。 */
|
|
19594
|
+
async hasMembership(threadId) {
|
|
19595
|
+
assertTargetRoot();
|
|
19596
|
+
if (!fs18.existsSync(groups)) return false;
|
|
19597
|
+
for (const groupId of fs18.readdirSync(groups)) {
|
|
19598
|
+
const control = read(groupId);
|
|
19599
|
+
if (!control) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19600
|
+
if (control.members.some(function member(item) {
|
|
19601
|
+
return item.threadId === threadId;
|
|
19602
|
+
}) || control.creates.some(function intent(item) {
|
|
19603
|
+
return item.threadId === threadId || item.parentThreadId === threadId;
|
|
19604
|
+
})) return true;
|
|
19605
|
+
}
|
|
19606
|
+
return false;
|
|
19607
|
+
},
|
|
19608
|
+
/** 目标格式与稳定身份校验后按消息锁幂等写入。 */
|
|
19609
|
+
async writeMessage(message) {
|
|
19610
|
+
assertTargetRoot();
|
|
19611
|
+
const target = messagePath(message.groupId, message.toThreadId, message.deliverySeq);
|
|
19612
|
+
const serialized = JSON.stringify(message);
|
|
19613
|
+
if (Buffer.byteLength(serialized, "utf8") > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
19614
|
+
await withFileLock(target, function writeLocked() {
|
|
19615
|
+
const prior = readMessage(message.groupId, message.toThreadId, message.deliverySeq);
|
|
19616
|
+
if (prior && JSON.stringify(prior) !== serialized) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19617
|
+
if (!prior) atomicReplace(target, serialized);
|
|
19618
|
+
}, { requireExitedOwner: true });
|
|
19619
|
+
},
|
|
19620
|
+
/** 按序号读取,不创建目录或锁文件。 */
|
|
19621
|
+
async readMessage(groupId, threadId, seq2) {
|
|
19622
|
+
assertTargetRoot();
|
|
19623
|
+
return readMessage(groupId, threadId, seq2);
|
|
19624
|
+
},
|
|
19625
|
+
/** 查询不触发状态根初始化或执行恢复。 */
|
|
19626
|
+
async readControl(groupId) {
|
|
19627
|
+
assertTargetRoot();
|
|
19628
|
+
return read(groupId);
|
|
19629
|
+
},
|
|
19630
|
+
/** 只列出已有 control.json 的组,半初始化目录不冒充可执行目标。 */
|
|
19631
|
+
async listGroups() {
|
|
19632
|
+
assertTargetRoot();
|
|
19633
|
+
if (!fs18.existsSync(groups)) return [];
|
|
19634
|
+
return fs18.readdirSync(groups).filter(function hasControl(name) {
|
|
19635
|
+
return fs18.existsSync(controlPath(name));
|
|
19636
|
+
}).sort();
|
|
19637
|
+
},
|
|
19638
|
+
/**
|
|
19639
|
+
* 本进程内的文件变化唤醒;watchFile 只做 stat 轮询,不创建锁或文件。
|
|
19640
|
+
* 跨进程写入同样会改变 mtime,因此订阅不依赖同一进程的 CAS 回调。
|
|
19641
|
+
*/
|
|
19642
|
+
subscribe(groupId, listener) {
|
|
19643
|
+
const target = controlPath(groupId);
|
|
19644
|
+
const onChange = function changed() {
|
|
19645
|
+
try {
|
|
19646
|
+
listener();
|
|
19647
|
+
} catch {
|
|
19648
|
+
}
|
|
19649
|
+
};
|
|
19650
|
+
fs18.watchFile(target, { interval: 200, persistent: false }, onChange);
|
|
19651
|
+
return () => {
|
|
19652
|
+
fs18.unwatchFile(target, onChange);
|
|
19653
|
+
};
|
|
19654
|
+
},
|
|
19655
|
+
/** 加锁后重新读取和校验版本,原子替换而不跨 Session 持锁执行。 */
|
|
19656
|
+
async compareAndSetControl(groupId, expectedRevision, value) {
|
|
19657
|
+
assertTargetRoot();
|
|
19658
|
+
if (value.group.groupId !== groupId || value.revision !== (expectedRevision === null ? 0 : expectedRevision + 1)) throw new Error("THREAD_CONTROL_INVALID");
|
|
19659
|
+
assertInteractionControls(value);
|
|
19660
|
+
const serialized = JSON.stringify(value);
|
|
19661
|
+
if (Buffer.byteLength(serialized, "utf8") > 4 * 1024 * 1024) throw new Error("THREAD_STORAGE_FULL");
|
|
19662
|
+
return withFileLock(controlPath(groupId), function updateUnderLock() {
|
|
19663
|
+
const current = read(groupId);
|
|
19664
|
+
if (expectedRevision === null ? current !== null : current?.revision !== expectedRevision) return false;
|
|
19665
|
+
atomicReplace(controlPath(groupId), serialized);
|
|
19666
|
+
return true;
|
|
19667
|
+
}, { requireExitedOwner: true });
|
|
19668
|
+
}
|
|
19669
|
+
};
|
|
19670
|
+
}
|
|
19671
|
+
|
|
19672
|
+
// src/node/stores/node-session-store.ts
|
|
19673
|
+
import fs20 from "node:fs";
|
|
19674
|
+
|
|
19675
|
+
// src/node/stores/session-directory.ts
|
|
19676
|
+
import fs19 from "node:fs";
|
|
19677
|
+
var DIRECTORY_FIELDS = /* @__PURE__ */ new Set(["id", "title", "productMode", "projectId", "chatRetrievalMode", "createdAt", "updatedAt", "status", "activeTurnId"]);
|
|
19678
|
+
async function readSessionDirectoryRecord(filePath, id) {
|
|
19679
|
+
const fields = {};
|
|
19680
|
+
const stack = [];
|
|
19681
|
+
let root = false;
|
|
19682
|
+
let finished = false;
|
|
19683
|
+
let token;
|
|
19684
|
+
let text = "";
|
|
19685
|
+
let capture = false;
|
|
19686
|
+
let keyToken = false;
|
|
19687
|
+
let target;
|
|
19688
|
+
let escaped = false;
|
|
19689
|
+
let unicode = 0;
|
|
19690
|
+
function invalid() {
|
|
19691
|
+
throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
19692
|
+
}
|
|
19693
|
+
function beginValue() {
|
|
19694
|
+
if (!stack.length) {
|
|
19695
|
+
if (root) invalid();
|
|
19696
|
+
root = true;
|
|
19697
|
+
return void 0;
|
|
19698
|
+
}
|
|
19699
|
+
const frame = stack[stack.length - 1];
|
|
19700
|
+
if (frame.expect !== "value" && frame.expect !== "valueOrEnd") invalid();
|
|
19701
|
+
frame.expect = "commaOrEnd";
|
|
19702
|
+
return stack.length === 1 && frame.kind === "object" && frame.key && DIRECTORY_FIELDS.has(frame.key) ? frame.key : void 0;
|
|
19703
|
+
}
|
|
19704
|
+
function finishToken() {
|
|
19705
|
+
if (keyToken) {
|
|
19706
|
+
const frame = stack[stack.length - 1];
|
|
19707
|
+
frame.key = stack.length === 1 ? JSON.parse(text) : void 0;
|
|
19708
|
+
frame.expect = "colon";
|
|
19709
|
+
} else if (target) fields[target] = JSON.parse(text);
|
|
19710
|
+
token = void 0;
|
|
19711
|
+
text = "";
|
|
19712
|
+
target = void 0;
|
|
19713
|
+
}
|
|
19714
|
+
const stream = fs19.createReadStream(filePath, { encoding: "utf8", highWaterMark: 16 * 1024 });
|
|
19715
|
+
for await (const chunk of stream) {
|
|
19716
|
+
for (const character of chunk) {
|
|
19717
|
+
if (token === "string") {
|
|
19718
|
+
if (capture) text += character;
|
|
19719
|
+
if (unicode) {
|
|
19720
|
+
if (!/[0-9a-f]/iu.test(character)) invalid();
|
|
19721
|
+
unicode--;
|
|
19722
|
+
continue;
|
|
19723
|
+
}
|
|
19724
|
+
if (escaped) {
|
|
19725
|
+
if (character === "u") unicode = 4;
|
|
19726
|
+
else if (!/["\\/bfnrt]/u.test(character)) invalid();
|
|
19727
|
+
escaped = false;
|
|
19728
|
+
continue;
|
|
19729
|
+
}
|
|
19730
|
+
if (character === "\\") {
|
|
19731
|
+
escaped = true;
|
|
19732
|
+
continue;
|
|
19733
|
+
}
|
|
19734
|
+
if (character === '"') {
|
|
19735
|
+
finishToken();
|
|
19736
|
+
continue;
|
|
19737
|
+
}
|
|
19738
|
+
if (character.charCodeAt(0) < 32) invalid();
|
|
19739
|
+
continue;
|
|
19740
|
+
}
|
|
19741
|
+
if (token === "primitive") {
|
|
19742
|
+
if (!/[ \t\r\n,}\]]/u.test(character)) {
|
|
19743
|
+
text += character;
|
|
19744
|
+
if (text.length > 128) invalid();
|
|
19745
|
+
continue;
|
|
19746
|
+
}
|
|
19747
|
+
if (!/^(?:null|true|false|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)$/u.test(text)) invalid();
|
|
19748
|
+
finishToken();
|
|
19749
|
+
}
|
|
19750
|
+
if (/[ \t\r\n]/u.test(character)) continue;
|
|
19751
|
+
if (finished) invalid();
|
|
19752
|
+
const frame = stack[stack.length - 1];
|
|
19753
|
+
if (character === '"') {
|
|
19754
|
+
keyToken = frame?.kind === "object" && (frame.expect === "key" || frame.expect === "keyOrEnd");
|
|
19755
|
+
target = keyToken ? void 0 : beginValue();
|
|
19756
|
+
capture = keyToken ? stack.length === 1 : target !== void 0;
|
|
19757
|
+
text = capture ? '"' : "";
|
|
19758
|
+
token = "string";
|
|
19759
|
+
continue;
|
|
19760
|
+
}
|
|
19761
|
+
if (character === "{" || character === "[") {
|
|
19762
|
+
const topLevel = !root;
|
|
19763
|
+
if (topLevel && character !== "{") invalid();
|
|
19764
|
+
beginValue();
|
|
19765
|
+
if (stack.length >= 128) invalid();
|
|
19766
|
+
stack.push({ kind: character === "{" ? "object" : "array", expect: character === "{" ? "keyOrEnd" : "valueOrEnd" });
|
|
19767
|
+
continue;
|
|
19768
|
+
}
|
|
19769
|
+
if (character === "}" || character === "]") {
|
|
19770
|
+
if (!frame || frame.kind !== (character === "}" ? "object" : "array") || !["commaOrEnd", character === "}" ? "keyOrEnd" : "valueOrEnd"].includes(frame.expect)) invalid();
|
|
19771
|
+
stack.pop();
|
|
19772
|
+
if (!stack.length) finished = true;
|
|
19773
|
+
continue;
|
|
19774
|
+
}
|
|
19775
|
+
if (character === ":") {
|
|
19776
|
+
if (frame?.expect !== "colon") invalid();
|
|
19777
|
+
frame.expect = "value";
|
|
19778
|
+
continue;
|
|
19779
|
+
}
|
|
19780
|
+
if (character === ",") {
|
|
19781
|
+
if (frame?.expect !== "commaOrEnd") invalid();
|
|
19782
|
+
frame.expect = frame.kind === "object" ? "key" : "value";
|
|
19783
|
+
continue;
|
|
19784
|
+
}
|
|
19785
|
+
target = beginValue();
|
|
19786
|
+
keyToken = false;
|
|
19787
|
+
capture = true;
|
|
19788
|
+
text = character;
|
|
19789
|
+
token = "primitive";
|
|
19790
|
+
}
|
|
19791
|
+
}
|
|
19792
|
+
if (!finished || token || stack.length) invalid();
|
|
19793
|
+
if (fields.title !== void 0 && typeof fields.title !== "string") invalid();
|
|
19794
|
+
return normalizeNodeSession(fields, id);
|
|
19795
|
+
}
|
|
19796
|
+
|
|
19200
19797
|
// src/node/stores/node-session-store.ts
|
|
19201
19798
|
function createNodeSessionStore(options) {
|
|
19202
19799
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
@@ -19204,7 +19801,7 @@ function createNodeSessionStore(options) {
|
|
|
19204
19801
|
function ensureDir() {
|
|
19205
19802
|
const state = ensureNodeStateRoot(options.stateRoot);
|
|
19206
19803
|
assertSafeNodePath(state.root, state.sessionsDir);
|
|
19207
|
-
|
|
19804
|
+
fs20.mkdirSync(state.sessionsDir, { recursive: true });
|
|
19208
19805
|
}
|
|
19209
19806
|
function filePath(sessionId) {
|
|
19210
19807
|
const target = safeFilePath(paths.sessionsDir, sessionId, ".json");
|
|
@@ -19213,9 +19810,9 @@ function createNodeSessionStore(options) {
|
|
|
19213
19810
|
}
|
|
19214
19811
|
function read(id) {
|
|
19215
19812
|
const target = filePath(id);
|
|
19216
|
-
if (!
|
|
19813
|
+
if (!fs20.existsSync(target)) return null;
|
|
19217
19814
|
let value;
|
|
19218
|
-
const content =
|
|
19815
|
+
const content = fs20.readFileSync(target, "utf8");
|
|
19219
19816
|
try {
|
|
19220
19817
|
value = JSON.parse(content);
|
|
19221
19818
|
} catch {
|
|
@@ -19223,17 +19820,27 @@ function createNodeSessionStore(options) {
|
|
|
19223
19820
|
}
|
|
19224
19821
|
const session = normalizeNodeSession(value, id);
|
|
19225
19822
|
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19226
|
-
if (value.productMode === void 0) atomicReplace(target, JSON.stringify(session, null, 2));
|
|
19227
19823
|
return session;
|
|
19228
19824
|
}
|
|
19229
19825
|
return {
|
|
19230
19826
|
/** 在文件锁内校验并读取当前产品域的 Session。 */
|
|
19231
19827
|
async get(id) {
|
|
19232
19828
|
try {
|
|
19233
|
-
|
|
19234
|
-
return
|
|
19235
|
-
|
|
19236
|
-
|
|
19829
|
+
assertNodeStateSchema(paths.root);
|
|
19830
|
+
return read(id);
|
|
19831
|
+
} catch (error) {
|
|
19832
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19833
|
+
}
|
|
19834
|
+
},
|
|
19835
|
+
/** 单个关联目标也复用流式元数据边界,不读取完整Session正文。 */
|
|
19836
|
+
async getDirectoryEntry(id) {
|
|
19837
|
+
try {
|
|
19838
|
+
assertNodeStateSchema(paths.root);
|
|
19839
|
+
const target = filePath(id);
|
|
19840
|
+
if (!fs20.existsSync(target)) return null;
|
|
19841
|
+
const session = await readSessionDirectoryRecord(target, id);
|
|
19842
|
+
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19843
|
+
return session;
|
|
19237
19844
|
} catch (error) {
|
|
19238
19845
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19239
19846
|
}
|
|
@@ -19241,9 +19848,10 @@ function createNodeSessionStore(options) {
|
|
|
19241
19848
|
/** 逐项加锁读取,损坏记录不能从列表中无声消失。 */
|
|
19242
19849
|
async list() {
|
|
19243
19850
|
try {
|
|
19244
|
-
|
|
19851
|
+
assertNodeStateSchema(paths.root);
|
|
19245
19852
|
const sessions = [];
|
|
19246
|
-
|
|
19853
|
+
if (!fs20.existsSync(paths.sessionsDir)) return sessions;
|
|
19854
|
+
for (const file of fs20.readdirSync(paths.sessionsDir)) {
|
|
19247
19855
|
if (!file.endsWith(".json")) continue;
|
|
19248
19856
|
const session = await this.get(file.slice(0, -5));
|
|
19249
19857
|
if (session) sessions.push(session);
|
|
@@ -19253,19 +19861,69 @@ function createNodeSessionStore(options) {
|
|
|
19253
19861
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19254
19862
|
}
|
|
19255
19863
|
},
|
|
19864
|
+
/** 每页只扫描limit个稳定UUID记录;流式跳过正文,不回退完整get/list。 */
|
|
19865
|
+
async listDirectoryPage(query2) {
|
|
19866
|
+
try {
|
|
19867
|
+
assertNodeStateSchema(paths.root);
|
|
19868
|
+
if (!Number.isInteger(query2.limit) || query2.limit < 1 || query2.limit > 100 || !query2.projectId.trim()) throw new Error("SESSION_CURSOR_INVALID");
|
|
19869
|
+
let after2 = "";
|
|
19870
|
+
if (query2.cursor) {
|
|
19871
|
+
try {
|
|
19872
|
+
const value = JSON.parse(Buffer.from(query2.cursor, "base64url").toString("utf8"));
|
|
19873
|
+
if (value.view !== "session-directory" || value.root !== paths.root || value.mode !== productMode || value.projectId !== query2.projectId || typeof value.after !== "string") throw new Error();
|
|
19874
|
+
after2 = value.after;
|
|
19875
|
+
} catch {
|
|
19876
|
+
throw new Error("SESSION_CURSOR_INVALID");
|
|
19877
|
+
}
|
|
19878
|
+
}
|
|
19879
|
+
const names = fs20.existsSync(paths.sessionsDir) ? fs20.readdirSync(paths.sessionsDir).filter(function session(file) {
|
|
19880
|
+
return file.endsWith(".json") && file.slice(0, -5) > after2;
|
|
19881
|
+
}).sort() : [];
|
|
19882
|
+
const items = [];
|
|
19883
|
+
for (const name of names.slice(0, query2.limit)) {
|
|
19884
|
+
after2 = name.slice(0, -5);
|
|
19885
|
+
const session = await readSessionDirectoryRecord(filePath(after2), after2);
|
|
19886
|
+
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19887
|
+
if (session.projectId === query2.projectId) items.push({ id: session.id, ...session.title !== void 0 ? { title: session.title } : {} });
|
|
19888
|
+
}
|
|
19889
|
+
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;
|
|
19890
|
+
return { items, ...nextCursor ? { nextCursor } : {} };
|
|
19891
|
+
} catch (error) {
|
|
19892
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19893
|
+
}
|
|
19894
|
+
},
|
|
19895
|
+
/** 跨进程锁内确认不存在再创建,防止并发覆盖已有 Session。 */
|
|
19896
|
+
async createIfAbsent(session) {
|
|
19897
|
+
try {
|
|
19898
|
+
ensureDir();
|
|
19899
|
+
const next = normalizeNodeSession(session, session.id);
|
|
19900
|
+
if (next.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19901
|
+
return await withFileLock(filePath(session.id), function createLocked() {
|
|
19902
|
+
if (read(session.id)) return false;
|
|
19903
|
+
atomicReplace(filePath(session.id), JSON.stringify(next, null, 2));
|
|
19904
|
+
return true;
|
|
19905
|
+
}, { requireExitedOwner: true });
|
|
19906
|
+
} catch (error) {
|
|
19907
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19908
|
+
}
|
|
19909
|
+
},
|
|
19256
19910
|
/** 在同一临界区比较持久化身份并原子替换,拒绝底层直接越权写入。 */
|
|
19257
19911
|
async save(session) {
|
|
19912
|
+
let phase = "prepare";
|
|
19258
19913
|
try {
|
|
19259
19914
|
ensureDir();
|
|
19915
|
+
phase = "identity";
|
|
19260
19916
|
const next = normalizeNodeSession(session, session.id);
|
|
19261
19917
|
if (next.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19918
|
+
phase = "lock";
|
|
19262
19919
|
await withFileLock(filePath(session.id), function saveLocked() {
|
|
19920
|
+
phase = "identity";
|
|
19263
19921
|
const previous = read(session.id);
|
|
19264
19922
|
if (previous) assertNodeSessionIdentity(previous, next);
|
|
19265
19923
|
atomicReplace(filePath(session.id), JSON.stringify(next, null, 2));
|
|
19266
19924
|
});
|
|
19267
19925
|
} catch (error) {
|
|
19268
|
-
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19926
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE", { operation: "session_save", target: "session", phase, ...getFileOperationDiagnostic(error) });
|
|
19269
19927
|
}
|
|
19270
19928
|
},
|
|
19271
19929
|
/** 只删除当前产品域记录;外围资源仍由 SessionResourceStore 先行清理。 */
|
|
@@ -19275,7 +19933,7 @@ function createNodeSessionStore(options) {
|
|
|
19275
19933
|
const target = filePath(id);
|
|
19276
19934
|
return await withFileLock(target, function deleteLocked() {
|
|
19277
19935
|
if (!read(id)) return false;
|
|
19278
|
-
|
|
19936
|
+
fs20.unlinkSync(target);
|
|
19279
19937
|
return true;
|
|
19280
19938
|
});
|
|
19281
19939
|
} catch (error) {
|
|
@@ -19287,11 +19945,16 @@ function createNodeSessionStore(options) {
|
|
|
19287
19945
|
|
|
19288
19946
|
// src/node/stores/node-transcript-store.ts
|
|
19289
19947
|
import fsp2 from "node:fs/promises";
|
|
19290
|
-
import
|
|
19948
|
+
import path17 from "node:path";
|
|
19291
19949
|
var transcriptIndexes = /* @__PURE__ */ new Map();
|
|
19292
19950
|
var transcriptRootInitializations = /* @__PURE__ */ new Map();
|
|
19951
|
+
function parseTranscriptFileIdentity(value) {
|
|
19952
|
+
if (typeof value === "string" && /^\d{1,20}$/.test(value)) return BigInt(value).toString();
|
|
19953
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return String(value);
|
|
19954
|
+
throw new Error("THREAD_CURSOR_INVALID");
|
|
19955
|
+
}
|
|
19293
19956
|
function getTranscriptIndex(filePath) {
|
|
19294
|
-
const key2 =
|
|
19957
|
+
const key2 = path17.resolve(filePath);
|
|
19295
19958
|
const existing = transcriptIndexes.get(key2);
|
|
19296
19959
|
if (existing) return existing;
|
|
19297
19960
|
const created = { initialized: false, offset: 0, pendingBytes: Buffer.alloc(0), endsWithNewline: true, keys: /* @__PURE__ */ new Set() };
|
|
@@ -19302,7 +19965,7 @@ function getEnvelopeKey(envelope) {
|
|
|
19302
19965
|
return `${envelope.sessionId}\0${envelope.turnId}\0${envelope.seq}`;
|
|
19303
19966
|
}
|
|
19304
19967
|
function ensureTranscriptDirectory(stateRoot) {
|
|
19305
|
-
const key2 =
|
|
19968
|
+
const key2 = path17.resolve(stateRoot);
|
|
19306
19969
|
const existing = transcriptRootInitializations.get(key2);
|
|
19307
19970
|
if (existing) return existing;
|
|
19308
19971
|
const initialization = Promise.resolve().then(async function initializeTranscriptDirectory() {
|
|
@@ -19324,7 +19987,7 @@ async function readTranscriptBuffer(filePath) {
|
|
|
19324
19987
|
}
|
|
19325
19988
|
}
|
|
19326
19989
|
function reportCorruptedLine(filePath) {
|
|
19327
|
-
console.warn(`[DURABLE_JSONL_CORRUPTED] file=${
|
|
19990
|
+
console.warn(`[DURABLE_JSONL_CORRUPTED] file=${path17.basename(filePath)} records=1 lines=unknown`);
|
|
19328
19991
|
}
|
|
19329
19992
|
function parseTranscriptLine(filePath, line, index, parsed) {
|
|
19330
19993
|
if (line.length === 0) return;
|
|
@@ -19388,26 +20051,28 @@ async function readTranscriptTail(filePath, offset) {
|
|
|
19388
20051
|
}
|
|
19389
20052
|
}
|
|
19390
20053
|
async function refreshTranscriptIndex(filePath, index) {
|
|
19391
|
-
if (!index.initialized) {
|
|
19392
|
-
rebuildTranscriptIndex(filePath, await readTranscriptBuffer(filePath), index);
|
|
19393
|
-
return;
|
|
19394
|
-
}
|
|
19395
20054
|
let stats;
|
|
19396
20055
|
try {
|
|
19397
|
-
stats = await fsp2.stat(filePath);
|
|
20056
|
+
stats = await fsp2.stat(filePath, { bigint: true });
|
|
19398
20057
|
} catch (error) {
|
|
19399
20058
|
if (error.code !== "ENOENT") throw error;
|
|
19400
20059
|
rebuildTranscriptIndex(filePath, Buffer.alloc(0), index);
|
|
20060
|
+
index.identity = void 0;
|
|
20061
|
+
index.signature = void 0;
|
|
19401
20062
|
return;
|
|
19402
20063
|
}
|
|
19403
|
-
|
|
20064
|
+
const identity = `${stats.dev}:${stats.ino}:${stats.birthtimeNs}`;
|
|
20065
|
+
const signature = `${identity}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
|
|
20066
|
+
const size = Number(stats.size);
|
|
20067
|
+
if (!index.initialized || index.identity !== identity || size < index.offset || size === index.offset && index.signature !== signature) {
|
|
19404
20068
|
rebuildTranscriptIndex(filePath, await readTranscriptBuffer(filePath), index);
|
|
19405
|
-
|
|
20069
|
+
} else if (size > index.offset) {
|
|
20070
|
+
const tail = await readTranscriptTail(filePath, index.offset);
|
|
20071
|
+
consumeTranscriptBytes(filePath, tail.bytes, index);
|
|
20072
|
+
index.offset = tail.size;
|
|
19406
20073
|
}
|
|
19407
|
-
|
|
19408
|
-
|
|
19409
|
-
consumeTranscriptBytes(filePath, tail.bytes, index);
|
|
19410
|
-
index.offset = tail.size;
|
|
20074
|
+
index.identity = identity;
|
|
20075
|
+
index.signature = signature;
|
|
19411
20076
|
}
|
|
19412
20077
|
async function appendTranscriptEnvelope(filePath, envelope) {
|
|
19413
20078
|
const index = getTranscriptIndex(filePath);
|
|
@@ -19424,6 +20089,9 @@ async function appendTranscriptEnvelope(filePath, envelope) {
|
|
|
19424
20089
|
index.endsWithNewline = true;
|
|
19425
20090
|
index.offset += bytes.length;
|
|
19426
20091
|
index.keys.add(key2);
|
|
20092
|
+
const stats = await fsp2.stat(filePath, { bigint: true });
|
|
20093
|
+
index.identity = `${stats.dev}:${stats.ino}:${stats.birthtimeNs}`;
|
|
20094
|
+
index.signature = `${index.identity}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
|
|
19427
20095
|
});
|
|
19428
20096
|
}
|
|
19429
20097
|
function removeAdjacentDuplicateEnvelopes(parsed) {
|
|
@@ -19440,7 +20108,9 @@ function removeAdjacentDuplicateEnvelopes(parsed) {
|
|
|
19440
20108
|
function createNodeTranscriptStore(options) {
|
|
19441
20109
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19442
20110
|
function filePath(sessionId) {
|
|
19443
|
-
|
|
20111
|
+
const target = safeFilePath(paths.transcriptsDir, sessionId, ".jsonl");
|
|
20112
|
+
assertSafeNodePath(paths.root, target);
|
|
20113
|
+
return target;
|
|
19444
20114
|
}
|
|
19445
20115
|
return {
|
|
19446
20116
|
async append(sessionId, envelope) {
|
|
@@ -19455,6 +20125,88 @@ function createNodeTranscriptStore(options) {
|
|
|
19455
20125
|
return removeAdjacentDuplicateEnvelopes(rebuildTranscriptIndex(target, await readTranscriptBuffer(target), index));
|
|
19456
20126
|
});
|
|
19457
20127
|
},
|
|
20128
|
+
/** 从字节游标增量读取 JSONL,不初始化目录、不持有写锁。 */
|
|
20129
|
+
async readPage(sessionId, options2) {
|
|
20130
|
+
if (!Number.isInteger(options2.limit) || options2.limit < 1 || options2.limit > 100) throw new Error("THREAD_CURSOR_INVALID");
|
|
20131
|
+
assertNodeStateSchema(paths.root);
|
|
20132
|
+
let offset = 0;
|
|
20133
|
+
let identity;
|
|
20134
|
+
if (options2.cursor) {
|
|
20135
|
+
try {
|
|
20136
|
+
const data = JSON.parse(Buffer.from(options2.cursor, "base64url").toString("utf8"));
|
|
20137
|
+
if (data.sessionId !== sessionId || !Number.isSafeInteger(data.offset) || data.offset < 0) throw new Error();
|
|
20138
|
+
offset = data.offset;
|
|
20139
|
+
identity = { dev: parseTranscriptFileIdentity(data.dev), ino: parseTranscriptFileIdentity(data.ino), size: data.size, stamp: data.stamp };
|
|
20140
|
+
if (data.size !== void 0 && (!Number.isSafeInteger(data.size) || data.size < offset) || data.stamp !== void 0 && typeof data.stamp !== "string") throw new Error();
|
|
20141
|
+
} catch {
|
|
20142
|
+
throw new Error("THREAD_CURSOR_INVALID");
|
|
20143
|
+
}
|
|
20144
|
+
}
|
|
20145
|
+
let handle;
|
|
20146
|
+
try {
|
|
20147
|
+
handle = await fsp2.open(filePath(sessionId), "r");
|
|
20148
|
+
} catch (error) {
|
|
20149
|
+
if (error.code === "ENOENT") {
|
|
20150
|
+
if (offset === 0) return { items: [] };
|
|
20151
|
+
throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20152
|
+
}
|
|
20153
|
+
throw error;
|
|
20154
|
+
}
|
|
20155
|
+
try {
|
|
20156
|
+
const stats = await handle.stat({ bigint: true });
|
|
20157
|
+
const size = Number(stats.size);
|
|
20158
|
+
const dev = stats.dev.toString();
|
|
20159
|
+
const ino = stats.ino.toString();
|
|
20160
|
+
if (!Number.isSafeInteger(size)) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20161
|
+
const stamp = `${stats.mtimeNs}:${stats.ctimeNs}:${stats.birthtimeNs}`;
|
|
20162
|
+
if (identity && (identity.dev !== dev || identity.ino !== ino || identity.size === size && identity.stamp !== void 0 && identity.stamp !== stamp)) throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20163
|
+
if (offset > size) throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20164
|
+
if (offset > 0) {
|
|
20165
|
+
const previous = Buffer.alloc(1);
|
|
20166
|
+
await handle.read(previous, 0, 1, offset - 1);
|
|
20167
|
+
if (previous[0] !== 10) throw new Error("THREAD_CURSOR_INVALID");
|
|
20168
|
+
}
|
|
20169
|
+
const items = [];
|
|
20170
|
+
let position = offset;
|
|
20171
|
+
let lineStart = offset;
|
|
20172
|
+
let pending = Buffer.alloc(0);
|
|
20173
|
+
const chunk = Buffer.alloc(16 * 1024);
|
|
20174
|
+
while (position < size && items.length < options2.limit) {
|
|
20175
|
+
const result = await handle.read(chunk, 0, Math.min(chunk.length, size - position), position);
|
|
20176
|
+
if (!result.bytesRead) break;
|
|
20177
|
+
let start = 0;
|
|
20178
|
+
for (let i = 0; i < result.bytesRead; i++) {
|
|
20179
|
+
if (chunk[i] !== 10) continue;
|
|
20180
|
+
const line = pending.length ? Buffer.concat([pending, chunk.subarray(start, i)]) : chunk.subarray(start, i);
|
|
20181
|
+
if (line.length > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20182
|
+
let item;
|
|
20183
|
+
try {
|
|
20184
|
+
item = JSON.parse(line.toString("utf8"));
|
|
20185
|
+
} catch {
|
|
20186
|
+
throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20187
|
+
}
|
|
20188
|
+
if (item.sessionId !== sessionId) throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20189
|
+
items.push(item);
|
|
20190
|
+
lineStart = position + i + 1;
|
|
20191
|
+
pending = Buffer.alloc(0);
|
|
20192
|
+
start = i + 1;
|
|
20193
|
+
if (items.length === options2.limit) break;
|
|
20194
|
+
}
|
|
20195
|
+
if (items.length === options2.limit) {
|
|
20196
|
+
position = lineStart;
|
|
20197
|
+
break;
|
|
20198
|
+
}
|
|
20199
|
+
pending = Buffer.concat([pending, chunk.subarray(start, result.bytesRead)]);
|
|
20200
|
+
if (pending.length > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20201
|
+
position += result.bytesRead;
|
|
20202
|
+
}
|
|
20203
|
+
if (position >= size && pending.length > 0) throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20204
|
+
const cursor = Buffer.from(JSON.stringify({ sessionId, offset: lineStart, dev, ino, size, stamp })).toString("base64url");
|
|
20205
|
+
return { items, cursor, ...lineStart < size ? { nextCursor: cursor } : {} };
|
|
20206
|
+
} finally {
|
|
20207
|
+
await handle.close();
|
|
20208
|
+
}
|
|
20209
|
+
},
|
|
19458
20210
|
async deleteBySession(sessionId) {
|
|
19459
20211
|
await ensureTranscriptDirectory(paths.root);
|
|
19460
20212
|
const target = filePath(sessionId);
|
|
@@ -19476,20 +20228,20 @@ function createNodeTranscriptStore(options) {
|
|
|
19476
20228
|
}
|
|
19477
20229
|
|
|
19478
20230
|
// src/node/stores/node-turn-store.ts
|
|
19479
|
-
import
|
|
20231
|
+
import fs21 from "node:fs";
|
|
19480
20232
|
function createNodeTurnStore(options) {
|
|
19481
20233
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19482
20234
|
function ensureDir() {
|
|
19483
20235
|
const state = ensureNodeStateRoot(paths.root);
|
|
19484
|
-
|
|
20236
|
+
fs21.mkdirSync(state.turnsDir, { recursive: true });
|
|
19485
20237
|
}
|
|
19486
20238
|
function filePath(turnId) {
|
|
19487
20239
|
return safeFilePath(paths.turnsDir, turnId, ".json");
|
|
19488
20240
|
}
|
|
19489
20241
|
return {
|
|
19490
20242
|
async get(id) {
|
|
19491
|
-
|
|
19492
|
-
return
|
|
20243
|
+
assertNodeStateSchema(paths.root);
|
|
20244
|
+
return readJsonFile(filePath(id));
|
|
19493
20245
|
},
|
|
19494
20246
|
async save(turn) {
|
|
19495
20247
|
ensureDir();
|
|
@@ -19498,9 +20250,10 @@ function createNodeTurnStore(options) {
|
|
|
19498
20250
|
});
|
|
19499
20251
|
},
|
|
19500
20252
|
async list(sessionId) {
|
|
19501
|
-
|
|
20253
|
+
assertNodeStateSchema(paths.root);
|
|
19502
20254
|
const turns = [];
|
|
19503
|
-
|
|
20255
|
+
if (!fs21.existsSync(paths.turnsDir)) return turns;
|
|
20256
|
+
for (const file of fs21.readdirSync(paths.turnsDir).filter((entry) => entry.endsWith(".json"))) {
|
|
19504
20257
|
const turn = readJsonFile(filePath(file.slice(0, -5)));
|
|
19505
20258
|
if (turn?.sessionId === sessionId) turns.push(turn);
|
|
19506
20259
|
}
|
|
@@ -19517,7 +20270,7 @@ function createNodeTurnStore(options) {
|
|
|
19517
20270
|
for (const turn of turns) {
|
|
19518
20271
|
const target = filePath(turn.id);
|
|
19519
20272
|
await withFileLock(target, () => {
|
|
19520
|
-
if (
|
|
20273
|
+
if (fs21.existsSync(target)) fs21.unlinkSync(target);
|
|
19521
20274
|
});
|
|
19522
20275
|
}
|
|
19523
20276
|
}
|
|
@@ -19525,12 +20278,12 @@ function createNodeTurnStore(options) {
|
|
|
19525
20278
|
}
|
|
19526
20279
|
|
|
19527
20280
|
// src/node/stores/node-lease-store.ts
|
|
19528
|
-
import
|
|
20281
|
+
import fs22 from "node:fs";
|
|
19529
20282
|
function createNodeLeaseStore(options) {
|
|
19530
20283
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19531
20284
|
function ensureDir() {
|
|
19532
20285
|
const state = ensureNodeStateRoot(paths.root);
|
|
19533
|
-
|
|
20286
|
+
fs22.mkdirSync(state.leasesDir, { recursive: true });
|
|
19534
20287
|
}
|
|
19535
20288
|
function filePath(sessionId) {
|
|
19536
20289
|
return safeFilePath(paths.leasesDir, sessionId, ".json");
|
|
@@ -19539,6 +20292,11 @@ function createNodeLeaseStore(options) {
|
|
|
19539
20292
|
return now - record.lease.heartbeatAt <= staleAfterMs;
|
|
19540
20293
|
}
|
|
19541
20294
|
return {
|
|
20295
|
+
/** 原子替换文件允许无锁只读;禁止在状态查询中初始化或迁移存储。 */
|
|
20296
|
+
async readCurrent(sessionId) {
|
|
20297
|
+
const current = readJsonFile(filePath(sessionId));
|
|
20298
|
+
return current ? { turnId: current.turnId, lease: { ...current.lease } } : null;
|
|
20299
|
+
},
|
|
19542
20300
|
async acquire(input) {
|
|
19543
20301
|
ensureDir();
|
|
19544
20302
|
const target = filePath(input.sessionId);
|
|
@@ -19567,7 +20325,7 @@ function createNodeLeaseStore(options) {
|
|
|
19567
20325
|
return withFileLock(target, () => {
|
|
19568
20326
|
const current = readJsonFile(target);
|
|
19569
20327
|
if (!current || current.lease.leaseId !== input.lease.leaseId || current.lease.ownerId !== input.lease.ownerId) return false;
|
|
19570
|
-
if (
|
|
20328
|
+
if (fs22.existsSync(target)) fs22.unlinkSync(target);
|
|
19571
20329
|
return true;
|
|
19572
20330
|
});
|
|
19573
20331
|
},
|
|
@@ -19575,7 +20333,7 @@ function createNodeLeaseStore(options) {
|
|
|
19575
20333
|
ensureDir();
|
|
19576
20334
|
const target = filePath(sessionId);
|
|
19577
20335
|
await withFileLock(target, () => {
|
|
19578
|
-
if (
|
|
20336
|
+
if (fs22.existsSync(target)) fs22.unlinkSync(target);
|
|
19579
20337
|
});
|
|
19580
20338
|
}
|
|
19581
20339
|
};
|
|
@@ -19590,26 +20348,26 @@ function createNodeClock() {
|
|
|
19590
20348
|
}
|
|
19591
20349
|
|
|
19592
20350
|
// src/node/stores/node-job-store.ts
|
|
19593
|
-
import
|
|
19594
|
-
import
|
|
20351
|
+
import fs23 from "node:fs";
|
|
20352
|
+
import path18 from "node:path";
|
|
19595
20353
|
function createNodeJobStore(options) {
|
|
19596
20354
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19597
20355
|
function ensureDir() {
|
|
19598
20356
|
const state = ensureNodeStateRoot(paths.root);
|
|
19599
|
-
|
|
20357
|
+
fs23.mkdirSync(state.jobsDir, { recursive: true });
|
|
19600
20358
|
}
|
|
19601
20359
|
function filePath(id) {
|
|
19602
20360
|
return safeFilePath(paths.jobsDir, id, ".json");
|
|
19603
20361
|
}
|
|
19604
20362
|
function sessionLockPath(sessionId) {
|
|
19605
|
-
return safeFilePath(
|
|
20363
|
+
return safeFilePath(path18.join(paths.jobsDir, ".session-locks"), sessionId, ".guard");
|
|
19606
20364
|
}
|
|
19607
20365
|
function sameOwner(first, second) {
|
|
19608
20366
|
return first?.runtimeInstanceId === second.runtimeInstanceId && first.hostProcessId === second.hostProcessId;
|
|
19609
20367
|
}
|
|
19610
20368
|
function readAll() {
|
|
19611
20369
|
ensureDir();
|
|
19612
|
-
return
|
|
20370
|
+
return fs23.readdirSync(paths.jobsDir).filter((file) => file.endsWith(".json")).flatMap((file) => {
|
|
19613
20371
|
const job = readJsonFile(filePath(file.slice(0, -5)));
|
|
19614
20372
|
return job ? [job] : [];
|
|
19615
20373
|
});
|
|
@@ -19622,7 +20380,7 @@ function createNodeJobStore(options) {
|
|
|
19622
20380
|
async create(job) {
|
|
19623
20381
|
ensureDir();
|
|
19624
20382
|
return withFileLock(filePath(job.id), function createIfMissing() {
|
|
19625
|
-
if (
|
|
20383
|
+
if (fs23.existsSync(filePath(job.id))) return false;
|
|
19626
20384
|
atomicReplace(filePath(job.id), JSON.stringify(job, null, 2));
|
|
19627
20385
|
return true;
|
|
19628
20386
|
});
|
|
@@ -19651,7 +20409,7 @@ function createNodeJobStore(options) {
|
|
|
19651
20409
|
for (const job of await this.listBySession(sessionId)) {
|
|
19652
20410
|
const target = filePath(job.id);
|
|
19653
20411
|
await withFileLock(target, () => {
|
|
19654
|
-
if (
|
|
20412
|
+
if (fs23.existsSync(target)) fs23.unlinkSync(target);
|
|
19655
20413
|
});
|
|
19656
20414
|
}
|
|
19657
20415
|
},
|
|
@@ -19679,43 +20437,43 @@ function createNodeJobOwnerProbe() {
|
|
|
19679
20437
|
}
|
|
19680
20438
|
|
|
19681
20439
|
// src/node/stores/node-file-mutation-store.ts
|
|
19682
|
-
import { createHash as
|
|
19683
|
-
import
|
|
19684
|
-
import
|
|
20440
|
+
import { createHash as createHash4, randomUUID as randomUUID5 } from "node:crypto";
|
|
20441
|
+
import fs24 from "node:fs";
|
|
20442
|
+
import path19 from "node:path";
|
|
19685
20443
|
var MAX_FILE_SNAPSHOT_BYTES = 512 * 1024;
|
|
19686
20444
|
var MAX_SESSION_SNAPSHOT_BYTES = 5 * 1024 * 1024;
|
|
19687
20445
|
function sha256(content) {
|
|
19688
|
-
return
|
|
20446
|
+
return createHash4("sha256").update(content).digest("hex");
|
|
19689
20447
|
}
|
|
19690
20448
|
function writeBlob(blobPath, content) {
|
|
19691
|
-
if (
|
|
19692
|
-
|
|
20449
|
+
if (fs24.existsSync(blobPath)) return;
|
|
20450
|
+
fs24.mkdirSync(path19.dirname(blobPath), { recursive: true });
|
|
19693
20451
|
const temporary = `${blobPath}.${process.pid}.${randomUUID5()}.tmp`;
|
|
19694
20452
|
try {
|
|
19695
|
-
const descriptor =
|
|
20453
|
+
const descriptor = fs24.openSync(temporary, "wx");
|
|
19696
20454
|
try {
|
|
19697
|
-
|
|
19698
|
-
|
|
20455
|
+
fs24.writeFileSync(descriptor, content);
|
|
20456
|
+
fs24.fsyncSync(descriptor);
|
|
19699
20457
|
} finally {
|
|
19700
|
-
|
|
20458
|
+
fs24.closeSync(descriptor);
|
|
19701
20459
|
}
|
|
19702
20460
|
try {
|
|
19703
|
-
|
|
20461
|
+
fs24.renameSync(temporary, blobPath);
|
|
19704
20462
|
} catch (error) {
|
|
19705
|
-
if (!
|
|
20463
|
+
if (!fs24.existsSync(blobPath)) throw error;
|
|
19706
20464
|
}
|
|
19707
20465
|
} finally {
|
|
19708
|
-
if (
|
|
20466
|
+
if (fs24.existsSync(temporary)) fs24.unlinkSync(temporary);
|
|
19709
20467
|
}
|
|
19710
20468
|
}
|
|
19711
20469
|
function createNodeFileMutationStore(options) {
|
|
19712
20470
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19713
20471
|
function ensureDir() {
|
|
19714
20472
|
const state = ensureNodeStateRoot(paths.root);
|
|
19715
|
-
|
|
19716
|
-
|
|
19717
|
-
|
|
19718
|
-
|
|
20473
|
+
fs24.mkdirSync(state.mutationsDir, { recursive: true });
|
|
20474
|
+
fs24.mkdirSync(state.mutationBlobsDir, { recursive: true });
|
|
20475
|
+
fs24.mkdirSync(state.mutationLocksDir, { recursive: true });
|
|
20476
|
+
fs24.mkdirSync(state.undoTransactionsDir, { recursive: true });
|
|
19719
20477
|
}
|
|
19720
20478
|
function mutationPath(id) {
|
|
19721
20479
|
return safeFilePath(paths.mutationsDir, id, ".json");
|
|
@@ -19729,9 +20487,9 @@ function createNodeFileMutationStore(options) {
|
|
|
19729
20487
|
}
|
|
19730
20488
|
function readAll() {
|
|
19731
20489
|
ensureDir();
|
|
19732
|
-
return
|
|
20490
|
+
return fs24.readdirSync(paths.mutationsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
|
|
19733
20491
|
try {
|
|
19734
|
-
return [JSON.parse(
|
|
20492
|
+
return [JSON.parse(fs24.readFileSync(mutationPath(entry.slice(0, -5)), "utf8"))];
|
|
19735
20493
|
} catch {
|
|
19736
20494
|
return [];
|
|
19737
20495
|
}
|
|
@@ -19739,9 +20497,9 @@ function createNodeFileMutationStore(options) {
|
|
|
19739
20497
|
}
|
|
19740
20498
|
function readTransactions() {
|
|
19741
20499
|
ensureDir();
|
|
19742
|
-
return
|
|
20500
|
+
return fs24.readdirSync(paths.undoTransactionsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
|
|
19743
20501
|
try {
|
|
19744
|
-
return [JSON.parse(
|
|
20502
|
+
return [JSON.parse(fs24.readFileSync(transactionPath(entry.slice(0, -5)), "utf8"))];
|
|
19745
20503
|
} catch {
|
|
19746
20504
|
return [];
|
|
19747
20505
|
}
|
|
@@ -19749,7 +20507,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19749
20507
|
}
|
|
19750
20508
|
function sessionBlobBytes(sessionId) {
|
|
19751
20509
|
const refs3 = new Set(readAll().filter((item) => item.sessionId === sessionId).flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
|
|
19752
|
-
return [...refs3].reduce((total, ref) => total + (
|
|
20510
|
+
return [...refs3].reduce((total, ref) => total + (fs24.statSync(blobPath(ref), { throwIfNoEntry: false })?.size ?? 0), 0);
|
|
19753
20511
|
}
|
|
19754
20512
|
return {
|
|
19755
20513
|
async prepare(input) {
|
|
@@ -19759,7 +20517,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19759
20517
|
const refs3 = /* @__PURE__ */ new Map();
|
|
19760
20518
|
if (input.before) refs3.set(beforeRef, input.before);
|
|
19761
20519
|
if (input.after) refs3.set(afterRef, input.after);
|
|
19762
|
-
const additionalBytes = [...refs3.entries()].filter(([ref]) => !
|
|
20520
|
+
const additionalBytes = [...refs3.entries()].filter(([ref]) => !fs24.existsSync(blobPath(ref))).reduce((total, [, content]) => total + content.byteLength, 0);
|
|
19763
20521
|
const byteCount = (input.before?.byteLength ?? 0) + (input.after?.byteLength ?? 0);
|
|
19764
20522
|
const binary2 = Boolean(input.before?.includes(0) || input.after?.includes(0));
|
|
19765
20523
|
const reversible = !binary2 && byteCount <= MAX_FILE_SNAPSHOT_BYTES && sessionBlobBytes(input.sessionId) + additionalBytes <= MAX_SESSION_SNAPSHOT_BYTES;
|
|
@@ -19790,7 +20548,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19790
20548
|
async getBlob(ref) {
|
|
19791
20549
|
ensureDir();
|
|
19792
20550
|
try {
|
|
19793
|
-
const content =
|
|
20551
|
+
const content = fs24.readFileSync(blobPath(ref));
|
|
19794
20552
|
return sha256(content) === ref ? content : null;
|
|
19795
20553
|
} catch {
|
|
19796
20554
|
return null;
|
|
@@ -19808,14 +20566,14 @@ function createNodeFileMutationStore(options) {
|
|
|
19808
20566
|
},
|
|
19809
20567
|
async deleteBySession(sessionId) {
|
|
19810
20568
|
ensureDir();
|
|
19811
|
-
for (const mutation of readAll().filter((item) => item.sessionId === sessionId))
|
|
19812
|
-
for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId))
|
|
20569
|
+
for (const mutation of readAll().filter((item) => item.sessionId === sessionId)) fs24.rmSync(mutationPath(mutation.id), { force: true });
|
|
20570
|
+
for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId)) fs24.rmSync(transactionPath(transaction.id), { force: true });
|
|
19813
20571
|
const referenced = new Set(readAll().flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
|
|
19814
|
-
for (const entry of
|
|
20572
|
+
for (const entry of fs24.readdirSync(paths.mutationBlobsDir).filter((item) => item.endsWith(".blob"))) if (!referenced.has(entry.slice(0, -5))) fs24.rmSync(path19.join(paths.mutationBlobsDir, entry), { force: true });
|
|
19815
20573
|
},
|
|
19816
20574
|
async withWorkspaceLock(workspaceRoot, operation, canonicalTargets = []) {
|
|
19817
20575
|
ensureDir();
|
|
19818
|
-
const lockId =
|
|
20576
|
+
const lockId = createHash4("sha256").update(path19.resolve(workspaceRoot)).digest("hex");
|
|
19819
20577
|
return withFileLock(safeFilePath(paths.mutationLocksDir, lockId, ".lock-target"), function lockTargets() {
|
|
19820
20578
|
return withNodeFileMutationLocks(canonicalTargets, operation);
|
|
19821
20579
|
}, { requireExitedOwner: true });
|
|
@@ -19824,32 +20582,94 @@ function createNodeFileMutationStore(options) {
|
|
|
19824
20582
|
}
|
|
19825
20583
|
|
|
19826
20584
|
// src/node/stores/node-session-resource-store.ts
|
|
19827
|
-
import
|
|
19828
|
-
import
|
|
20585
|
+
import fs25 from "node:fs";
|
|
20586
|
+
import path20 from "node:path";
|
|
19829
20587
|
function isAttachmentSessionId(sessionId) {
|
|
19830
20588
|
return /^[0-9a-f-]{36}$/iu.test(sessionId);
|
|
19831
20589
|
}
|
|
19832
20590
|
function createNodeSessionResourceStore(workspaceRoot) {
|
|
19833
20591
|
const root = canonicalizeNodePath(workspaceRoot);
|
|
19834
|
-
const uploadsRoot =
|
|
20592
|
+
const uploadsRoot = path20.join(root, ".local", "session-uploads");
|
|
19835
20593
|
return {
|
|
19836
20594
|
async deleteBySession(sessionId) {
|
|
19837
20595
|
if (!isAttachmentSessionId(sessionId)) return;
|
|
19838
|
-
const target =
|
|
19839
|
-
if (!target.startsWith(`${uploadsRoot}${
|
|
19840
|
-
|
|
20596
|
+
const target = path20.join(uploadsRoot, sessionId);
|
|
20597
|
+
if (!target.startsWith(`${uploadsRoot}${path20.sep}`)) throw new Error("SESSION_RESOURCE_PATH_INVALID");
|
|
20598
|
+
fs25.rmSync(target, { recursive: true, force: true, maxRetries: 2 });
|
|
20599
|
+
}
|
|
20600
|
+
};
|
|
20601
|
+
}
|
|
20602
|
+
|
|
20603
|
+
// src/node/stores/node-session-image-store.ts
|
|
20604
|
+
import crypto3 from "node:crypto";
|
|
20605
|
+
import fs26 from "node:fs";
|
|
20606
|
+
import path21 from "node:path";
|
|
20607
|
+
import { normalizeWorkImage } from "@autopilot-agent/core";
|
|
20608
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
20609
|
+
function sessionDirectory(root, sessionId, create3) {
|
|
20610
|
+
if (!UUID.test(sessionId)) throw new Error("SESSION_IMAGE_INVALID");
|
|
20611
|
+
let current = fs26.realpathSync(root);
|
|
20612
|
+
for (const part of [".local", "session-uploads", sessionId]) {
|
|
20613
|
+
current = path21.join(current, part);
|
|
20614
|
+
if (create3) {
|
|
20615
|
+
try {
|
|
20616
|
+
fs26.mkdirSync(current);
|
|
20617
|
+
} catch (error) {
|
|
20618
|
+
if (error.code !== "EEXIST") throw error;
|
|
20619
|
+
}
|
|
20620
|
+
}
|
|
20621
|
+
const stat = fs26.lstatSync(current);
|
|
20622
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("SESSION_IMAGE_INVALID");
|
|
20623
|
+
}
|
|
20624
|
+
return current;
|
|
20625
|
+
}
|
|
20626
|
+
function createNodeSessionImageStore(workspaceRoot) {
|
|
20627
|
+
return {
|
|
20628
|
+
/** 校验并保存规范化副本与不可变元数据。 */
|
|
20629
|
+
async put(input) {
|
|
20630
|
+
let normalized;
|
|
20631
|
+
try {
|
|
20632
|
+
normalized = await normalizeWorkImage({ bytes: input.bytes, mimeType: input.mimeType });
|
|
20633
|
+
} catch {
|
|
20634
|
+
throw new Error("SESSION_IMAGE_INVALID");
|
|
20635
|
+
}
|
|
20636
|
+
const directory = sessionDirectory(workspaceRoot, input.sessionId, true);
|
|
20637
|
+
const id = crypto3.randomUUID();
|
|
20638
|
+
const extension = normalized.mimeType === "image/jpeg" ? ".jpg" : normalized.mimeType === "image/png" ? ".png" : normalized.mimeType === "image/webp" ? ".webp" : ".gif";
|
|
20639
|
+
const bytes = Buffer.from(normalized.bytes);
|
|
20640
|
+
const image = { id, name: path21.basename(input.name), mimeType: normalized.mimeType, relativePath: `.local/session-uploads/${input.sessionId}/${id}${extension}`, sha256: crypto3.createHash("sha256").update(bytes).digest("hex"), width: normalized.width, height: normalized.height, bytes: bytes.length, gifFirstFrame: normalized.gifFirstFrame };
|
|
20641
|
+
fs26.writeFileSync(path21.join(directory, `${id}${extension}`), bytes, { flag: "wx" });
|
|
20642
|
+
fs26.writeFileSync(path21.join(directory, `${id}.json`), JSON.stringify(image), { flag: "wx" });
|
|
20643
|
+
return image;
|
|
20644
|
+
},
|
|
20645
|
+
/** 按会话和图片标识读取并复核文件哈希。 */
|
|
20646
|
+
async read(input) {
|
|
20647
|
+
if (!UUID.test(input.id)) throw new Error("SESSION_IMAGE_INVALID");
|
|
20648
|
+
const directory = sessionDirectory(workspaceRoot, input.sessionId, false);
|
|
20649
|
+
const metadataPath = path21.join(directory, `${input.id}.json`);
|
|
20650
|
+
const metadataStat = fs26.lstatSync(metadataPath);
|
|
20651
|
+
if (!metadataStat.isFile() || metadataStat.isSymbolicLink() || metadataStat.size > 4096) throw new Error("SESSION_IMAGE_INVALID");
|
|
20652
|
+
const image = JSON.parse(fs26.readFileSync(metadataPath, "utf8"));
|
|
20653
|
+
const extension = image.mimeType === "image/jpeg" ? ".jpg" : image.mimeType === "image/png" ? ".png" : image.mimeType === "image/webp" ? ".webp" : image.mimeType === "image/gif" ? ".gif" : "";
|
|
20654
|
+
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");
|
|
20655
|
+
const filePath = path21.join(directory, `${input.id}${extension}`);
|
|
20656
|
+
const stat = fs26.lstatSync(filePath);
|
|
20657
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== image.bytes) throw new Error("SESSION_IMAGE_INVALID");
|
|
20658
|
+
const bytes = fs26.readFileSync(filePath);
|
|
20659
|
+
if (bytes.length !== image.bytes || crypto3.createHash("sha256").update(bytes).digest("hex") !== image.sha256) throw new Error("SESSION_IMAGE_INVALID");
|
|
20660
|
+
return { image, bytes };
|
|
19841
20661
|
}
|
|
19842
20662
|
};
|
|
19843
20663
|
}
|
|
19844
20664
|
|
|
19845
20665
|
// src/node/stores/node-user-question-store.ts
|
|
19846
|
-
import
|
|
20666
|
+
import fs27 from "node:fs";
|
|
19847
20667
|
function createNodeUserQuestionStore(options) {
|
|
19848
20668
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19849
20669
|
const recordsFile = `${paths.questionsDir}/requests.jsonl`;
|
|
19850
20670
|
function ensureDir() {
|
|
19851
20671
|
const state = ensureNodeStateRoot(paths.root);
|
|
19852
|
-
|
|
20672
|
+
fs27.mkdirSync(state.questionsDir, { recursive: true });
|
|
19853
20673
|
}
|
|
19854
20674
|
function answersEqual(left, right) {
|
|
19855
20675
|
return JSON.stringify(left) === JSON.stringify(right);
|
|
@@ -19914,6 +20734,7 @@ function createNodeRuntimePorts(options) {
|
|
|
19914
20734
|
}
|
|
19915
20735
|
return {
|
|
19916
20736
|
hostMutationProtection: options.productMode === "chat" ? void 0 : createNodeHostMutationProtection(options),
|
|
20737
|
+
threadStore: createNodeThreadStore(options.stateRoot),
|
|
19917
20738
|
sessionStore: createNodeSessionStore({ ...storeOptions, productMode: options.productMode }),
|
|
19918
20739
|
checkpointStore: createNodeCheckpointStore(storeOptions),
|
|
19919
20740
|
transcriptStore: createNodeTranscriptStore(storeOptions),
|
|
@@ -19937,6 +20758,7 @@ function createNodeRuntimePorts(options) {
|
|
|
19937
20758
|
throw new NodeChatError("CHAT_ATTACHMENT_STORE_REQUIRED");
|
|
19938
20759
|
}
|
|
19939
20760
|
} : createNodeSessionResourceStore(options.workspaceRoot ?? options.cwd ?? process.cwd()),
|
|
20761
|
+
sessionImageStore: options.productMode === "chat" || !options.workspaceRoot ? void 0 : createNodeSessionImageStore(options.workspaceRoot),
|
|
19940
20762
|
userQuestionStore: createNodeUserQuestionStore(storeOptions),
|
|
19941
20763
|
/**
|
|
19942
20764
|
* Stage 2:Work 模式装配真实 SRT adapter(绑定 canonical workspaceRoot;tempRoot
|
|
@@ -19954,9 +20776,9 @@ function createNodeRuntimePorts(options) {
|
|
|
19954
20776
|
}
|
|
19955
20777
|
|
|
19956
20778
|
// src/node/stores/node-chat-attachment-store.ts
|
|
19957
|
-
import
|
|
19958
|
-
import
|
|
19959
|
-
import { createHash as
|
|
20779
|
+
import fs28 from "node:fs";
|
|
20780
|
+
import path22 from "node:path";
|
|
20781
|
+
import { createHash as createHash5, randomUUID as randomUUID6 } from "node:crypto";
|
|
19960
20782
|
var CHAT_ATTACHMENT_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
19961
20783
|
var MAX_BYTES = 20 * 1024 * 1024;
|
|
19962
20784
|
var IMAGE_BYTES = 5 * 1024 * 1024;
|
|
@@ -19969,7 +20791,7 @@ function sessionKey(id) {
|
|
|
19969
20791
|
return id;
|
|
19970
20792
|
}
|
|
19971
20793
|
function digest(bytes) {
|
|
19972
|
-
return
|
|
20794
|
+
return createHash5("sha256").update(bytes).digest("hex");
|
|
19973
20795
|
}
|
|
19974
20796
|
function detectMime(bytes) {
|
|
19975
20797
|
if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png";
|
|
@@ -19995,12 +20817,12 @@ function createNodeChatAttachmentStore(options) {
|
|
|
19995
20817
|
const { paths, sessionStore } = options;
|
|
19996
20818
|
const now = options.now ?? Date.now;
|
|
19997
20819
|
const root = paths.attachmentsRoot;
|
|
19998
|
-
const dataRoot =
|
|
19999
|
-
const retiredRoot =
|
|
20000
|
-
const deletingRoot =
|
|
20001
|
-
const lock =
|
|
20820
|
+
const dataRoot = path22.join(root, "sessions");
|
|
20821
|
+
const retiredRoot = path22.join(root, "retired");
|
|
20822
|
+
const deletingRoot = path22.join(root, "deleting");
|
|
20823
|
+
const lock = path22.join(root, "lifecycle");
|
|
20002
20824
|
function ensure() {
|
|
20003
|
-
assertSafeNodePath(
|
|
20825
|
+
assertSafeNodePath(path22.dirname(paths.root), paths.root);
|
|
20004
20826
|
for (const directory of [root, dataRoot, retiredRoot, deletingRoot]) ensureChatDirectory(paths.root, directory);
|
|
20005
20827
|
assertSafeNodePath(root, `${lock}.lock`);
|
|
20006
20828
|
}
|
|
@@ -20022,9 +20844,9 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20022
20844
|
}
|
|
20023
20845
|
function isSessionDeleting(sessionId) {
|
|
20024
20846
|
try {
|
|
20025
|
-
const target =
|
|
20847
|
+
const target = path22.join(deletingRoot, `${sessionKey(sessionId)}.json`);
|
|
20026
20848
|
assertSafeNodePath(root, target);
|
|
20027
|
-
return
|
|
20849
|
+
return fs28.existsSync(target);
|
|
20028
20850
|
} catch (error) {
|
|
20029
20851
|
throw toNodeBoundaryError(error, "CHAT_ATTACHMENT_UNAVAILABLE");
|
|
20030
20852
|
}
|
|
@@ -20041,16 +20863,16 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20041
20863
|
if (session?.productMode !== "chat" || !["none", "web"].includes(session.chatRetrievalMode ?? "")) throw new NodeChatError("CHAT_UPLOAD_MODE_MISMATCH");
|
|
20042
20864
|
}
|
|
20043
20865
|
function records(sessionId) {
|
|
20044
|
-
const directory =
|
|
20866
|
+
const directory = path22.join(dataRoot, sessionKey(sessionId));
|
|
20045
20867
|
assertSafeNodePath(root, directory);
|
|
20046
|
-
if (!
|
|
20868
|
+
if (!fs28.existsSync(directory)) return [];
|
|
20047
20869
|
const result = [];
|
|
20048
|
-
for (const ref of
|
|
20870
|
+
for (const ref of fs28.readdirSync(directory)) {
|
|
20049
20871
|
if (!opaque.test(ref)) unavailable();
|
|
20050
|
-
const target =
|
|
20872
|
+
const target = path22.join(directory, ref, "metadata.json");
|
|
20051
20873
|
assertSafeNodePath(root, target);
|
|
20052
|
-
if (!
|
|
20053
|
-
const record = JSON.parse(
|
|
20874
|
+
if (!fs28.statSync(target).isFile() || fs28.statSync(target).size > 16384) unavailable();
|
|
20875
|
+
const record = JSON.parse(fs28.readFileSync(target, "utf8"));
|
|
20054
20876
|
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();
|
|
20055
20877
|
for (const page of record.pages) if (!opaque.test(page.ref)) unavailable();
|
|
20056
20878
|
result.push(record);
|
|
@@ -20061,7 +20883,7 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20061
20883
|
return { ref: record.ref, sessionId: record.sessionId, kind: record.kind, expiresAt: record.expiresAt };
|
|
20062
20884
|
}
|
|
20063
20885
|
function active(record) {
|
|
20064
|
-
return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !
|
|
20886
|
+
return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !fs28.existsSync(path22.join(retiredRoot, `${record.ref}.json`));
|
|
20065
20887
|
}
|
|
20066
20888
|
function sanitizeSession(session) {
|
|
20067
20889
|
try {
|
|
@@ -20100,17 +20922,17 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20100
20922
|
return !opaque.test(ref);
|
|
20101
20923
|
}
|
|
20102
20924
|
)) unavailable();
|
|
20103
|
-
const directory =
|
|
20925
|
+
const directory = path22.join(dataRoot, item.sessionId, item.ref);
|
|
20104
20926
|
assertSafeNodePath(root, directory);
|
|
20105
|
-
|
|
20927
|
+
fs28.rmSync(directory, { recursive: true, force: true });
|
|
20106
20928
|
await removePresentationRefs(item.sessionId, item.refs);
|
|
20107
|
-
|
|
20929
|
+
fs28.rmSync(path22.join(retiredRoot, `${item.ref}.json`), { force: true });
|
|
20108
20930
|
}
|
|
20109
20931
|
async function retire(record) {
|
|
20110
20932
|
const item = { sessionId: record.sessionId, ref: record.ref, refs: [record.ref, ...record.pages.map(function pageRef(page) {
|
|
20111
20933
|
return page.ref;
|
|
20112
20934
|
})] };
|
|
20113
|
-
atomicReplace(
|
|
20935
|
+
atomicReplace(path22.join(retiredRoot, `${record.ref}.json`), JSON.stringify(item));
|
|
20114
20936
|
await finishRetirement(item);
|
|
20115
20937
|
}
|
|
20116
20938
|
async function put(input) {
|
|
@@ -20143,13 +20965,13 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20143
20965
|
const createdAt = now();
|
|
20144
20966
|
if (!Number.isSafeInteger(createdAt) || createdAt < 0) unavailable();
|
|
20145
20967
|
const ref = randomUUID6();
|
|
20146
|
-
const parent =
|
|
20968
|
+
const parent = path22.join(dataRoot, sessionKey(input.sessionId));
|
|
20147
20969
|
ensureChatDirectory(root, parent);
|
|
20148
|
-
const staging =
|
|
20970
|
+
const staging = path22.join(root, `staging-${ref}`);
|
|
20149
20971
|
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: [] };
|
|
20150
20972
|
try {
|
|
20151
20973
|
ensureChatDirectory(root, staging);
|
|
20152
|
-
|
|
20974
|
+
fs28.writeFileSync(path22.join(staging, "content"), bytes, { flag: "wx", mode: 384 });
|
|
20153
20975
|
let pageBytes = 0;
|
|
20154
20976
|
for (const inputPage of parsed?.pages ?? []) {
|
|
20155
20977
|
const page = Buffer.from(inputPage);
|
|
@@ -20157,17 +20979,17 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20157
20979
|
pageBytes += page.length;
|
|
20158
20980
|
if (!type2.startsWith("image/") || !page.length || page.length > IMAGE_BYTES || pageBytes > MAX_BYTES) unavailable();
|
|
20159
20981
|
const pageRef = randomUUID6();
|
|
20160
|
-
|
|
20982
|
+
fs28.writeFileSync(path22.join(staging, pageRef), page, { flag: "wx", mode: 384 });
|
|
20161
20983
|
record.pages.push({ ref: pageRef, mimeType: type2, byteLength: page.length, sha256: digest(page) });
|
|
20162
20984
|
}
|
|
20163
|
-
if (parsed)
|
|
20164
|
-
|
|
20985
|
+
if (parsed) fs28.writeFileSync(path22.join(staging, "parsed.json"), JSON.stringify({ text: parsed.text.slice(0, 16e3) }), { flag: "wx", mode: 384 });
|
|
20986
|
+
fs28.writeFileSync(path22.join(staging, "metadata.json"), JSON.stringify(record), { flag: "wx", mode: 384 });
|
|
20165
20987
|
checkSignal(input.signal);
|
|
20166
|
-
|
|
20988
|
+
fs28.renameSync(staging, path22.join(parent, ref));
|
|
20167
20989
|
const { pages: _pages, ...view } = record;
|
|
20168
20990
|
return view;
|
|
20169
20991
|
} finally {
|
|
20170
|
-
|
|
20992
|
+
fs28.rmSync(staging, { recursive: true, force: true });
|
|
20171
20993
|
}
|
|
20172
20994
|
}, input.signal);
|
|
20173
20995
|
} catch (error) {
|
|
@@ -20209,10 +21031,10 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20209
21031
|
return locked(async function readParsed() {
|
|
20210
21032
|
const { record, page } = await find3(sessionId, ref);
|
|
20211
21033
|
if (page || record.kind !== "document") unavailable();
|
|
20212
|
-
const target =
|
|
21034
|
+
const target = path22.join(dataRoot, sessionId, ref, "parsed.json");
|
|
20213
21035
|
assertSafeNodePath(root, target);
|
|
20214
|
-
if (
|
|
20215
|
-
const parsed = JSON.parse(
|
|
21036
|
+
if (fs28.statSync(target).size > 1e5) unavailable();
|
|
21037
|
+
const parsed = JSON.parse(fs28.readFileSync(target, "utf8"));
|
|
20216
21038
|
if (typeof parsed.text !== "string") unavailable();
|
|
20217
21039
|
return { text: parsed.text.slice(0, 16e3), pageImages: record.pages.map(function pageGrant(item) {
|
|
20218
21040
|
return grant({ ...record, ref: item.ref, kind: "image" });
|
|
@@ -20222,44 +21044,44 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20222
21044
|
async function readBytes(sessionId, ref, signal) {
|
|
20223
21045
|
return locked(async function readContent() {
|
|
20224
21046
|
const { record, page } = await find3(sessionId, ref);
|
|
20225
|
-
const target =
|
|
21047
|
+
const target = path22.join(dataRoot, sessionId, record.ref, page?.ref ?? "content");
|
|
20226
21048
|
assertSafeNodePath(root, target);
|
|
20227
21049
|
const metadata = page ?? record;
|
|
20228
|
-
if (
|
|
20229
|
-
const bytes =
|
|
21050
|
+
if (fs28.statSync(target).size !== metadata.byteLength || metadata.byteLength > MAX_BYTES) unavailable();
|
|
21051
|
+
const bytes = fs28.readFileSync(target);
|
|
20230
21052
|
if (digest(bytes) !== metadata.sha256) unavailable();
|
|
20231
21053
|
return { bytes: new Uint8Array(bytes), mimeType: metadata.mimeType };
|
|
20232
21054
|
}, signal);
|
|
20233
21055
|
}
|
|
20234
21056
|
async function deleteBySession(sessionId) {
|
|
20235
21057
|
await locked(async function deleteSessionAttachments() {
|
|
20236
|
-
atomicReplace(
|
|
21058
|
+
atomicReplace(path22.join(deletingRoot, `${sessionKey(sessionId)}.json`), JSON.stringify({ sessionId }));
|
|
20237
21059
|
for (const record of records(sessionId)) await retire(record);
|
|
20238
21060
|
await removePresentationRefs(sessionId);
|
|
20239
|
-
|
|
21061
|
+
fs28.rmSync(path22.join(dataRoot, sessionId), { recursive: true, force: true });
|
|
20240
21062
|
}, void 0, "CHAT_ATTACHMENT_CLEANUP_FAILED");
|
|
20241
21063
|
}
|
|
20242
21064
|
async function cleanupExpired(input = {}) {
|
|
20243
21065
|
const limit = input.limit ?? 32;
|
|
20244
21066
|
if (!Number.isInteger(limit) || limit < 1 || limit > 128) throw new NodeChatError("CHAT_ATTACHMENT_CLEANUP_FAILED");
|
|
20245
21067
|
return locked(async function cleanupBatch() {
|
|
20246
|
-
for (const file of
|
|
21068
|
+
for (const file of fs28.readdirSync(root)) {
|
|
20247
21069
|
if (!/^staging-[0-9a-f-]{36}$/.test(file)) continue;
|
|
20248
|
-
const target =
|
|
21070
|
+
const target = path22.join(root, file);
|
|
20249
21071
|
assertSafeNodePath(root, target);
|
|
20250
|
-
|
|
21072
|
+
fs28.rmSync(target, { recursive: true, force: true });
|
|
20251
21073
|
}
|
|
20252
|
-
for (const file of
|
|
21074
|
+
for (const file of fs28.readdirSync(retiredRoot)) {
|
|
20253
21075
|
if (!file.endsWith(".json")) continue;
|
|
20254
|
-
const target =
|
|
21076
|
+
const target = path22.join(retiredRoot, file);
|
|
20255
21077
|
assertSafeNodePath(root, target);
|
|
20256
21078
|
checkSignal(input.signal);
|
|
20257
|
-
const item = JSON.parse(
|
|
21079
|
+
const item = JSON.parse(fs28.readFileSync(target, "utf8"));
|
|
20258
21080
|
if (file !== `${item.ref}.json`) unavailable();
|
|
20259
21081
|
await finishRetirement(item);
|
|
20260
21082
|
}
|
|
20261
21083
|
const expired = [];
|
|
20262
|
-
for (const sessionId of
|
|
21084
|
+
for (const sessionId of fs28.readdirSync(dataRoot)) {
|
|
20263
21085
|
for (const record of records(sessionId)) if (record.expiresAt <= now() || isSessionDeleting(sessionId)) expired.push(record);
|
|
20264
21086
|
}
|
|
20265
21087
|
expired.sort(function oldestFirst(left, right) {
|
|
@@ -20369,6 +21191,7 @@ function createNodeChatCapabilityLoader(options) {
|
|
|
20369
21191
|
}
|
|
20370
21192
|
const attachments = await storage.attachments.list(binding.sessionId);
|
|
20371
21193
|
return {
|
|
21194
|
+
...(binding.retrievalMode === "none" || binding.retrievalMode === "web") && options.interactiveUi === true ? { interactiveUi: true } : {},
|
|
20372
21195
|
/** 目录只含授权字段,实际引用仍由 Core 的冻结交集和 Store 复查约束。 */
|
|
20373
21196
|
attachments: attachments.map(function grant(item) {
|
|
20374
21197
|
return { ref: item.ref, displayName: item.displayName, sessionId: item.sessionId, kind: item.kind, expiresAt: item.expiresAt };
|
|
@@ -20493,7 +21316,7 @@ function createNodeRagRuntime(options) {
|
|
|
20493
21316
|
}
|
|
20494
21317
|
|
|
20495
21318
|
// src/node/settings/node-settings-writer.ts
|
|
20496
|
-
import
|
|
21319
|
+
import fs29 from "node:fs";
|
|
20497
21320
|
import { resolveAutopilotSettings as resolveAutopilotSettings3 } from "@autopilot-agent/core";
|
|
20498
21321
|
var CONFIG_KEY_ALLOWLIST = /* @__PURE__ */ new Set([
|
|
20499
21322
|
"model",
|
|
@@ -20506,9 +21329,9 @@ function createNodeSettingsWriter(options = {}) {
|
|
|
20506
21329
|
}
|
|
20507
21330
|
function readScope(scope, workspaceRoot) {
|
|
20508
21331
|
const filePath = getPaths(workspaceRoot)[scope];
|
|
20509
|
-
if (!
|
|
21332
|
+
if (!fs29.existsSync(filePath)) return {};
|
|
20510
21333
|
try {
|
|
20511
|
-
const parsed = JSON.parse(
|
|
21334
|
+
const parsed = JSON.parse(fs29.readFileSync(filePath, "utf8"));
|
|
20512
21335
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? { ...parsed } : {};
|
|
20513
21336
|
} catch {
|
|
20514
21337
|
return {};
|
|
@@ -20604,8 +21427,8 @@ function parseConfigValue(key2, rawValue) {
|
|
|
20604
21427
|
}
|
|
20605
21428
|
|
|
20606
21429
|
// src/node/settings/node-user-settings-service.ts
|
|
20607
|
-
import { createHash as
|
|
20608
|
-
import
|
|
21430
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
21431
|
+
import fs30 from "node:fs";
|
|
20609
21432
|
import { isExternalPermissionDiagnostic, normalizeProviderBaseUrl, resolveAutopilotSettings as resolveAutopilotSettings4 } from "@autopilot-agent/core";
|
|
20610
21433
|
var RAG_ROLE_CONTRACT = Object.freeze({
|
|
20611
21434
|
textRerank: { provider: "bailian", key: "RAG_TEXT_RERANK_API_KEY", dimension: false },
|
|
@@ -20643,14 +21466,14 @@ function parseApiKey(value) {
|
|
|
20643
21466
|
return typeof value === "string" && value.length <= 4096 && !/[\s\u0000-\u001f\u007f]/u.test(value) ? value : void 0;
|
|
20644
21467
|
}
|
|
20645
21468
|
function revisionOf(content) {
|
|
20646
|
-
return
|
|
21469
|
+
return createHash6("sha256").update(content).digest("hex");
|
|
20647
21470
|
}
|
|
20648
21471
|
function readUserSettings(settingsPath) {
|
|
20649
|
-
if (!
|
|
21472
|
+
if (!fs30.existsSync(settingsPath)) return { raw: {}, original: "" };
|
|
20650
21473
|
try {
|
|
20651
|
-
const stat =
|
|
21474
|
+
const stat = fs30.lstatSync(settingsPath);
|
|
20652
21475
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw new Error();
|
|
20653
|
-
const original =
|
|
21476
|
+
const original = fs30.readFileSync(settingsPath, "utf8");
|
|
20654
21477
|
const raw = JSON.parse(original);
|
|
20655
21478
|
if (!isRecord4(raw) || raw.env !== void 0 && !isRecord4(raw.env)) throw new Error();
|
|
20656
21479
|
return { raw: { ...raw }, original };
|
|
@@ -20960,36 +21783,36 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20960
21783
|
}
|
|
20961
21784
|
|
|
20962
21785
|
// src/node/capabilities/memory-retriever.ts
|
|
20963
|
-
import
|
|
20964
|
-
import
|
|
20965
|
-
import
|
|
21786
|
+
import crypto4 from "node:crypto";
|
|
21787
|
+
import fs31 from "node:fs";
|
|
21788
|
+
import path23 from "node:path";
|
|
20966
21789
|
function getNodeMemoryWorkspaceId(workspaceRoot) {
|
|
20967
|
-
return
|
|
21790
|
+
return crypto4.createHash("sha256").update(fs31.realpathSync.native(workspaceRoot).toLowerCase()).digest("hex").slice(0, 24);
|
|
20968
21791
|
}
|
|
20969
21792
|
function getNodeMemoryDirectory(stateRoot, workspaceRoot) {
|
|
20970
|
-
return
|
|
21793
|
+
return path23.join(path23.resolve(stateRoot), "memory", getNodeMemoryWorkspaceId(workspaceRoot));
|
|
20971
21794
|
}
|
|
20972
21795
|
function getLegacyWebMemoryDirectory(workspaceRoot, cwd = process.cwd()) {
|
|
20973
|
-
return
|
|
21796
|
+
return path23.join(path23.resolve(cwd), ".local", "agent", "workspaces", getNodeMemoryWorkspaceId(workspaceRoot), "memory");
|
|
20974
21797
|
}
|
|
20975
21798
|
function retrieveNodeMemories(_stateRoot, _workspaceRoot, _query, _maxItems = 5) {
|
|
20976
21799
|
return [];
|
|
20977
21800
|
}
|
|
20978
21801
|
|
|
20979
21802
|
// src/node/trust-policy.ts
|
|
20980
|
-
import
|
|
20981
|
-
import
|
|
21803
|
+
import fs32 from "node:fs";
|
|
21804
|
+
import path24 from "node:path";
|
|
20982
21805
|
function createNodeTrustStore(options) {
|
|
20983
21806
|
const trustRoot = resolveNodeTrustRoot({ stateRoot: options.stateRoot, trustRoot: options.trustRoot });
|
|
20984
|
-
const trustFile =
|
|
21807
|
+
const trustFile = path24.join(trustRoot, "trust.json");
|
|
20985
21808
|
const now = options.now ?? (() => Date.now());
|
|
20986
21809
|
function ensureDir() {
|
|
20987
|
-
|
|
21810
|
+
fs32.mkdirSync(trustRoot, { recursive: true });
|
|
20988
21811
|
}
|
|
20989
21812
|
function loadStore() {
|
|
20990
|
-
if (!
|
|
21813
|
+
if (!fs32.existsSync(trustFile)) return { version: 1, workspaces: {} };
|
|
20991
21814
|
try {
|
|
20992
|
-
const parsed = JSON.parse(
|
|
21815
|
+
const parsed = JSON.parse(fs32.readFileSync(trustFile, "utf8"));
|
|
20993
21816
|
if (parsed.version !== 1 || !parsed.workspaces || typeof parsed.workspaces !== "object") return { version: 1, workspaces: {} };
|
|
20994
21817
|
return { version: 1, workspaces: parsed.workspaces };
|
|
20995
21818
|
} catch {
|
|
@@ -21091,16 +21914,16 @@ function createNodeTrustPolicy(options) {
|
|
|
21091
21914
|
}
|
|
21092
21915
|
|
|
21093
21916
|
// src/node/workspace-registry.ts
|
|
21094
|
-
import
|
|
21095
|
-
import
|
|
21917
|
+
import fs33 from "node:fs";
|
|
21918
|
+
import path25 from "node:path";
|
|
21096
21919
|
function createNodeWorkspaceRegistry(options = {}) {
|
|
21097
21920
|
const globalStateRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: options.cwd });
|
|
21098
|
-
const registryPath =
|
|
21921
|
+
const registryPath = path25.join(globalStateRoot, "workspace-registry.json");
|
|
21099
21922
|
const now = options.now ?? (() => Date.now());
|
|
21100
21923
|
function load2() {
|
|
21101
|
-
if (!
|
|
21924
|
+
if (!fs33.existsSync(registryPath)) return [];
|
|
21102
21925
|
try {
|
|
21103
|
-
const parsed = JSON.parse(
|
|
21926
|
+
const parsed = JSON.parse(fs33.readFileSync(registryPath, "utf8"));
|
|
21104
21927
|
if (!Array.isArray(parsed)) return [];
|
|
21105
21928
|
return parsed.filter(function isEntry(value) {
|
|
21106
21929
|
return Boolean(value) && typeof value === "object" && typeof value.workspaceId === "string" && typeof value.workspaceRoot === "string" && typeof value.displayName === "string" && typeof value.lastOpenedAt === "number";
|
|
@@ -21123,7 +21946,7 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21123
21946
|
const next = {
|
|
21124
21947
|
workspaceId,
|
|
21125
21948
|
workspaceRoot: canonicalRoot,
|
|
21126
|
-
displayName:
|
|
21949
|
+
displayName: path25.basename(canonicalRoot) || canonicalRoot,
|
|
21127
21950
|
lastOpenedAt: now()
|
|
21128
21951
|
};
|
|
21129
21952
|
const entries2 = load2().filter(function removeExisting(entry) {
|
|
@@ -21144,11 +21967,466 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21144
21967
|
}
|
|
21145
21968
|
return { list: load2, get, register, remove: remove2 };
|
|
21146
21969
|
}
|
|
21970
|
+
|
|
21971
|
+
// src/node/thread-runner.ts
|
|
21972
|
+
import { sanitizeContinuationFailure as sanitizeContinuationFailure2 } from "@autopilot-agent/core";
|
|
21973
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
21974
|
+
function createNodeThreadRunner(options) {
|
|
21975
|
+
const delivery = options.delivery;
|
|
21976
|
+
const ownerId = delivery.ownerId;
|
|
21977
|
+
const pollIntervalMs = options.pollIntervalMs ?? 250;
|
|
21978
|
+
const staleMs = options.staleMs ?? 45e3;
|
|
21979
|
+
const heartbeatMs = options.heartbeatMs ?? Math.max(200, Math.min(5e3, Math.floor(staleMs / 3)));
|
|
21980
|
+
const reconcileEveryMs = options.reconcileEveryMs ?? 3e3;
|
|
21981
|
+
const active = /* @__PURE__ */ new Map();
|
|
21982
|
+
let timer;
|
|
21983
|
+
let ticking = false;
|
|
21984
|
+
let stopped = false;
|
|
21985
|
+
let lastReconcileAt = 0;
|
|
21986
|
+
let running = false;
|
|
21987
|
+
let kicked = false;
|
|
21988
|
+
let idleDelayMs = pollIntervalMs;
|
|
21989
|
+
async function hasFreshLease(threadId) {
|
|
21990
|
+
const checkpoint = await options.ports.checkpointStore.getLatest(threadId);
|
|
21991
|
+
return Boolean(checkpoint && checkpoint.status === "running" && checkpoint.lease && Date.now() - checkpoint.lease.heartbeatAt <= delivery.leaseStaleMs);
|
|
21992
|
+
}
|
|
21993
|
+
function activeMessageIds() {
|
|
21994
|
+
return [...active.values()].filter(function deliveryRecord(record) {
|
|
21995
|
+
return !record.external && Boolean(record.messageId);
|
|
21996
|
+
}).map(function id(record) {
|
|
21997
|
+
return record.messageId;
|
|
21998
|
+
});
|
|
21999
|
+
}
|
|
22000
|
+
async function safeTick(reconcileFirst = false) {
|
|
22001
|
+
if (ticking || stopped) return;
|
|
22002
|
+
if (timer) clearTimeout(timer);
|
|
22003
|
+
timer = void 0;
|
|
22004
|
+
kicked = false;
|
|
22005
|
+
ticking = true;
|
|
22006
|
+
try {
|
|
22007
|
+
const snapshot = await delivery.querySnapshot();
|
|
22008
|
+
if (reconcileFirst || Date.now() - lastReconcileAt >= reconcileEveryMs) {
|
|
22009
|
+
lastReconcileAt = Date.now();
|
|
22010
|
+
await delivery.reconcile({ staleMs, activeMessageIds: activeMessageIds(), snapshot });
|
|
22011
|
+
}
|
|
22012
|
+
await applyInterrupts(snapshot);
|
|
22013
|
+
await applyResumes(snapshot);
|
|
22014
|
+
await applyInteractionContinuations(snapshot);
|
|
22015
|
+
const claimed = await delivery.claimDeliveries({ snapshot, activeThreads: [...active.values()].filter(function controllable(record) {
|
|
22016
|
+
return record.ready;
|
|
22017
|
+
}).map(function thread(record) {
|
|
22018
|
+
return record.threadId;
|
|
22019
|
+
}) });
|
|
22020
|
+
for (const item of claimed) startDelivery(item);
|
|
22021
|
+
idleDelayMs = active.size || claimed.length ? pollIntervalMs : Math.min(Math.max(pollIntervalMs, 2e3), idleDelayMs * 2);
|
|
22022
|
+
} catch (error) {
|
|
22023
|
+
options.onError?.(error);
|
|
22024
|
+
} finally {
|
|
22025
|
+
ticking = false;
|
|
22026
|
+
if (running && !stopped) {
|
|
22027
|
+
timer = setTimeout(function poll() {
|
|
22028
|
+
void safeTick();
|
|
22029
|
+
}, kicked ? 0 : idleDelayMs);
|
|
22030
|
+
timer.unref?.();
|
|
22031
|
+
}
|
|
22032
|
+
}
|
|
22033
|
+
}
|
|
22034
|
+
async function applyInterrupts(snapshot) {
|
|
22035
|
+
for (const intent of await delivery.pendingInterrupts(snapshot)) {
|
|
22036
|
+
const task = active.get(intent.threadId);
|
|
22037
|
+
if (!task || !task.ready || task.turnId !== intent.expectedTurnId) {
|
|
22038
|
+
const turn = await options.ports.turnStore.get(intent.expectedTurnId);
|
|
22039
|
+
if (turn && (turn.status === "waiting_approval" || turn.status === "waiting_user_input")) {
|
|
22040
|
+
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)]);
|
|
22041
|
+
const checkpointStatus = turn.status === "waiting_approval" ? "awaiting_approval" : "awaiting_user_input";
|
|
22042
|
+
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) {
|
|
22043
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22044
|
+
continue;
|
|
22045
|
+
}
|
|
22046
|
+
try {
|
|
22047
|
+
await options.runtime.turns.cancel({ sessionId: intent.threadId, turnId: intent.expectedTurnId });
|
|
22048
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: true });
|
|
22049
|
+
} catch {
|
|
22050
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22051
|
+
}
|
|
22052
|
+
continue;
|
|
22053
|
+
}
|
|
22054
|
+
const terminal = turn && turn.status !== "running" && turn.status !== "waiting_approval" && turn.status !== "waiting_user_input";
|
|
22055
|
+
if (terminal) await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22056
|
+
else if (!turn && !await hasFreshLease(intent.threadId)) {
|
|
22057
|
+
const control = await delivery.readGroup(intent.groupId);
|
|
22058
|
+
const recorded = control?.controls.find(function match(item) {
|
|
22059
|
+
return item.controlId === intent.controlId;
|
|
22060
|
+
});
|
|
22061
|
+
if (recorded && Date.now() - recorded.createdAt > staleMs) await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22062
|
+
}
|
|
22063
|
+
continue;
|
|
22064
|
+
}
|
|
22065
|
+
try {
|
|
22066
|
+
if (task.cancelExecution) await task.cancelExecution();
|
|
22067
|
+
else await options.runtime.turns.cancel({ sessionId: intent.threadId, turnId: intent.expectedTurnId });
|
|
22068
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: true });
|
|
22069
|
+
} catch {
|
|
22070
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22071
|
+
}
|
|
22072
|
+
}
|
|
22073
|
+
}
|
|
22074
|
+
async function applyResumes(snapshot) {
|
|
22075
|
+
for (const intent of await delivery.pendingResumes(snapshot)) {
|
|
22076
|
+
if (active.has(intent.threadId) || await hasFreshLease(intent.threadId)) continue;
|
|
22077
|
+
if (!await delivery.claimResume(intent)) continue;
|
|
22078
|
+
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)]);
|
|
22079
|
+
if (!session || session.status !== "interrupted" || latest?.id !== intent.expectedTurnId || checkpoint?.turnId !== intent.expectedTurnId || createHash7("sha256").update(JSON.stringify(checkpoint)).digest("hex") !== intent.checkpointDigest) {
|
|
22080
|
+
await delivery.rejectResume(intent);
|
|
22081
|
+
continue;
|
|
22082
|
+
}
|
|
22083
|
+
const record = { threadId: intent.threadId, turnId: intent.expectedTurnId, groupId: intent.groupId, messageId: "", cancelled: false, task: Promise.resolve() };
|
|
22084
|
+
active.set(intent.threadId, record);
|
|
22085
|
+
record.task = continueOriginal().finally(function settled() {
|
|
22086
|
+
if (active.get(intent.threadId) === record) active.delete(intent.threadId);
|
|
22087
|
+
kick();
|
|
22088
|
+
});
|
|
22089
|
+
async function continueOriginal() {
|
|
22090
|
+
let started = false;
|
|
22091
|
+
try {
|
|
22092
|
+
for await (const event of options.runtime.turns.continue({ sessionId: intent.threadId, turnId: intent.expectedTurnId })) {
|
|
22093
|
+
if (event.type === "turn_started") {
|
|
22094
|
+
started = true;
|
|
22095
|
+
record.ready = true;
|
|
22096
|
+
}
|
|
22097
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) record.ready = false;
|
|
22098
|
+
}
|
|
22099
|
+
} catch (error) {
|
|
22100
|
+
if (!started) await delivery.rejectResume(intent);
|
|
22101
|
+
options.onError?.(error);
|
|
22102
|
+
} finally {
|
|
22103
|
+
await notifySettled(record);
|
|
22104
|
+
}
|
|
22105
|
+
}
|
|
22106
|
+
}
|
|
22107
|
+
}
|
|
22108
|
+
async function applyInteractionContinuations(snapshot) {
|
|
22109
|
+
for (const intent of await delivery.pendingInteractionContinuations(snapshot)) {
|
|
22110
|
+
if (active.has(intent.threadId) || await hasFreshLease(intent.threadId)) continue;
|
|
22111
|
+
if (!await delivery.claimInteractionContinuation(intent)) continue;
|
|
22112
|
+
const record = { threadId: intent.threadId, turnId: intent.expectedTurnId, groupId: intent.groupId, messageId: "", cancelled: false, task: Promise.resolve() };
|
|
22113
|
+
active.set(intent.threadId, record);
|
|
22114
|
+
record.task = continueInteraction().finally(function settled() {
|
|
22115
|
+
if (active.get(intent.threadId) === record) active.delete(intent.threadId);
|
|
22116
|
+
kick();
|
|
22117
|
+
}).catch(function report(error) {
|
|
22118
|
+
options.onError?.(error);
|
|
22119
|
+
});
|
|
22120
|
+
async function continueInteraction() {
|
|
22121
|
+
const beat = setInterval(function heartbeat() {
|
|
22122
|
+
delivery.settleInteractionContinuation({ groupId: intent.groupId, controlId: intent.controlId }).catch(function failed(error) {
|
|
22123
|
+
options.onError?.(error);
|
|
22124
|
+
});
|
|
22125
|
+
}, heartbeatMs);
|
|
22126
|
+
let stage = "read_decision";
|
|
22127
|
+
let started = false;
|
|
22128
|
+
try {
|
|
22129
|
+
const decision = intent.approvalId ? await options.ports.approvalStore.getDecision({ sessionId: intent.threadId, turnId: intent.expectedTurnId, approvalId: intent.approvalId }) : void 0;
|
|
22130
|
+
if (intent.approvalId && !decision) throw Object.assign(new Error("INTERACTION_DECISION_REQUIRED"), { code: "INTERACTION_DECISION_REQUIRED" });
|
|
22131
|
+
if (stopped || record.cancelled) {
|
|
22132
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "pending" });
|
|
22133
|
+
return;
|
|
22134
|
+
}
|
|
22135
|
+
stage = "continue";
|
|
22136
|
+
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" } } : {} })) {
|
|
22137
|
+
if (event.type === "turn_started") {
|
|
22138
|
+
started = true;
|
|
22139
|
+
stage = "after_started";
|
|
22140
|
+
record.ready = true;
|
|
22141
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "executing" });
|
|
22142
|
+
}
|
|
22143
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) record.ready = false;
|
|
22144
|
+
}
|
|
22145
|
+
await notifySettled(record);
|
|
22146
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "completed" });
|
|
22147
|
+
} catch (error) {
|
|
22148
|
+
const file = getFileOperationDiagnostic(error) ?? (error instanceof NodeStateError ? error.getStorageDiagnostic() : void 0);
|
|
22149
|
+
const code = file?.osCode ?? (error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : "CONTINUE_UNKNOWN");
|
|
22150
|
+
const failureDiagnostic = sanitizeContinuationFailure2({ stage, started, category: "unknown", code, ...file && ["lock", "temporary_write", "rename", "cleanup"].includes(file.phase) ? { filePhase: file.phase } : {} });
|
|
22151
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "failed", failureCode: "CONTINUE_FAILED", failureDiagnostic });
|
|
22152
|
+
options.onError?.(error, { threadId: intent.threadId, expectedTurnId: intent.expectedTurnId, controlId: intent.controlId, approvalId: intent.approvalId, requestId: intent.requestId, failureDiagnostic });
|
|
22153
|
+
await notifySettled(record);
|
|
22154
|
+
} finally {
|
|
22155
|
+
clearInterval(beat);
|
|
22156
|
+
}
|
|
22157
|
+
}
|
|
22158
|
+
}
|
|
22159
|
+
}
|
|
22160
|
+
function startDelivery(item) {
|
|
22161
|
+
const threadId = item.delivery.threadId;
|
|
22162
|
+
const turnId = item.delivery.reservedTurnId;
|
|
22163
|
+
if (!turnId) {
|
|
22164
|
+
void delivery.failDelivery({ groupId: item.groupId, messageId: item.delivery.messageId, reason: "start_failed" });
|
|
22165
|
+
return;
|
|
22166
|
+
}
|
|
22167
|
+
if (active.has(threadId)) {
|
|
22168
|
+
void delivery.releaseDelivery({ groupId: item.groupId, messageId: item.delivery.messageId });
|
|
22169
|
+
return;
|
|
22170
|
+
}
|
|
22171
|
+
const record = { threadId, turnId, groupId: item.groupId, messageId: item.delivery.messageId, cancelled: false, task: Promise.resolve() };
|
|
22172
|
+
record.task = runDelivery(item, record).catch(function ignore() {
|
|
22173
|
+
}).finally(function finish() {
|
|
22174
|
+
if (active.get(threadId) === record) active.delete(threadId);
|
|
22175
|
+
kick();
|
|
22176
|
+
});
|
|
22177
|
+
active.set(threadId, record);
|
|
22178
|
+
}
|
|
22179
|
+
async function notifyStarted(record, message) {
|
|
22180
|
+
if (!options.onTurnStarted) return;
|
|
22181
|
+
try {
|
|
22182
|
+
await options.onTurnStarted({
|
|
22183
|
+
threadId: record.threadId,
|
|
22184
|
+
turnId: record.turnId,
|
|
22185
|
+
prompt: { content: message.content, messageId: message.messageId, from: message.from, ...message.handoff ? { handoff: message.handoff } : {}, ...message.handoffDisplay ? { handoffDisplay: message.handoffDisplay } : {} }
|
|
22186
|
+
});
|
|
22187
|
+
} catch (error) {
|
|
22188
|
+
options.onError?.(error);
|
|
22189
|
+
}
|
|
22190
|
+
}
|
|
22191
|
+
async function notifySettled(record) {
|
|
22192
|
+
if (!options.onTurnSettled) return;
|
|
22193
|
+
try {
|
|
22194
|
+
await options.onTurnSettled({ threadId: record.threadId, turnId: record.turnId });
|
|
22195
|
+
} catch (error) {
|
|
22196
|
+
options.onError?.(error);
|
|
22197
|
+
}
|
|
22198
|
+
}
|
|
22199
|
+
async function runDelivery(item, record) {
|
|
22200
|
+
const { groupId, delivery: claimed, message } = item;
|
|
22201
|
+
const turnId = record.turnId;
|
|
22202
|
+
const existing = await options.ports.turnStore.get(turnId);
|
|
22203
|
+
if (existing) {
|
|
22204
|
+
await settle(item, record, turnId);
|
|
22205
|
+
return;
|
|
22206
|
+
}
|
|
22207
|
+
if (await hasFreshLease(record.threadId)) {
|
|
22208
|
+
await delivery.releaseDelivery({ groupId, messageId: claimed.messageId });
|
|
22209
|
+
return;
|
|
22210
|
+
}
|
|
22211
|
+
let failure;
|
|
22212
|
+
const beat = setInterval(function heartbeat() {
|
|
22213
|
+
void delivery.heartbeat({ groupId, messageId: claimed.messageId });
|
|
22214
|
+
}, heartbeatMs);
|
|
22215
|
+
beat.unref?.();
|
|
22216
|
+
let controlEnded = false;
|
|
22217
|
+
try {
|
|
22218
|
+
await delivery.heartbeat({ groupId, messageId: claimed.messageId });
|
|
22219
|
+
await notifyStarted(record, message);
|
|
22220
|
+
for await (const event of options.runtime.turns.start({
|
|
22221
|
+
sessionId: record.threadId,
|
|
22222
|
+
turnId,
|
|
22223
|
+
content: message.content,
|
|
22224
|
+
// 与页面队列同语义:这是目标空闲后的下一轮,不是新话题。
|
|
22225
|
+
continuity: { source: "claimed_queue" }
|
|
22226
|
+
})) {
|
|
22227
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) controlEnded = true;
|
|
22228
|
+
record.ready = !controlEnded;
|
|
22229
|
+
if (record.cancelled) break;
|
|
22230
|
+
}
|
|
22231
|
+
} catch (error) {
|
|
22232
|
+
failure = error;
|
|
22233
|
+
} finally {
|
|
22234
|
+
clearInterval(beat);
|
|
22235
|
+
}
|
|
22236
|
+
await settle(item, record, turnId, failure);
|
|
22237
|
+
}
|
|
22238
|
+
async function settle(item, record, turnId, failure) {
|
|
22239
|
+
const groupId = item.groupId;
|
|
22240
|
+
const messageId = item.delivery.messageId;
|
|
22241
|
+
const turn = await options.ports.turnStore.get(turnId);
|
|
22242
|
+
if (failure) {
|
|
22243
|
+
options.onError?.(failure);
|
|
22244
|
+
}
|
|
22245
|
+
if (turn) {
|
|
22246
|
+
await delivery.completeDelivery({ groupId, messageId, turnId });
|
|
22247
|
+
await notifySettled(record);
|
|
22248
|
+
return;
|
|
22249
|
+
}
|
|
22250
|
+
const code = failure?.code;
|
|
22251
|
+
if (code === "TURN_ALREADY_RUNNING") {
|
|
22252
|
+
await delivery.releaseDelivery({ groupId, messageId });
|
|
22253
|
+
return;
|
|
22254
|
+
}
|
|
22255
|
+
await delivery.failDelivery({ groupId, messageId, reason: "start_failed" });
|
|
22256
|
+
}
|
|
22257
|
+
async function stop() {
|
|
22258
|
+
stopped = true;
|
|
22259
|
+
running = false;
|
|
22260
|
+
if (timer) {
|
|
22261
|
+
clearTimeout(timer);
|
|
22262
|
+
timer = void 0;
|
|
22263
|
+
}
|
|
22264
|
+
const cancelledTurnIds = [];
|
|
22265
|
+
const unconfirmedTurnIds = [];
|
|
22266
|
+
const releasedMessageIds = [];
|
|
22267
|
+
const waitingTurnIds = [];
|
|
22268
|
+
const pendingMessageIds = [];
|
|
22269
|
+
const recoverableTurnIds = [];
|
|
22270
|
+
const tasks = [...active.values()].filter(function ownDelivery(record) {
|
|
22271
|
+
return !record.external;
|
|
22272
|
+
});
|
|
22273
|
+
for (const record of tasks) {
|
|
22274
|
+
if (record.cancelled) continue;
|
|
22275
|
+
const actual = await options.ports.turnStore.get(record.turnId);
|
|
22276
|
+
if (actual && actual.status !== "running") {
|
|
22277
|
+
if (actual.status === "waiting_approval" || actual.status === "waiting_user_input") waitingTurnIds.push(actual.id);
|
|
22278
|
+
continue;
|
|
22279
|
+
}
|
|
22280
|
+
record.cancelled = true;
|
|
22281
|
+
try {
|
|
22282
|
+
await options.runtime.turns.cancel({ sessionId: record.threadId, turnId: record.turnId });
|
|
22283
|
+
cancelledTurnIds.push(record.turnId);
|
|
22284
|
+
} catch {
|
|
22285
|
+
unconfirmedTurnIds.push(record.turnId);
|
|
22286
|
+
}
|
|
22287
|
+
}
|
|
22288
|
+
await Promise.allSettled(tasks.map(function task(record) {
|
|
22289
|
+
return record.task;
|
|
22290
|
+
}));
|
|
22291
|
+
for (const groupId of await delivery.listGroups()) {
|
|
22292
|
+
const control = await delivery.readGroup(groupId);
|
|
22293
|
+
if (!control) continue;
|
|
22294
|
+
for (const item of control.deliveries) {
|
|
22295
|
+
if (item.status === "pending" || item.status === "blocked") pendingMessageIds.push(item.messageId);
|
|
22296
|
+
const turnId = item.turnId ?? item.reservedTurnId;
|
|
22297
|
+
const turn = turnId ? await options.ports.turnStore.get(turnId) : void 0;
|
|
22298
|
+
if (turn?.status === "waiting_approval" || turn?.status === "waiting_user_input") waitingTurnIds.push(turn.id);
|
|
22299
|
+
if (turn?.status === "interrupted") recoverableTurnIds.push(turn.id);
|
|
22300
|
+
if (item.ownerId === ownerId && item.status === "claimed" && turn?.status === "running" && !cancelledTurnIds.includes(turn.id)) unconfirmedTurnIds.push(turn.id);
|
|
22301
|
+
if (item.status === "claimed" && item.ownerId === ownerId && !turn) {
|
|
22302
|
+
await delivery.releaseDelivery({ groupId, messageId: item.messageId });
|
|
22303
|
+
releasedMessageIds.push(item.messageId);
|
|
22304
|
+
pendingMessageIds.push(item.messageId);
|
|
22305
|
+
}
|
|
22306
|
+
}
|
|
22307
|
+
if (control.deliveries.some(function pending(item) {
|
|
22308
|
+
return item.status === "pending" || item.status === "blocked";
|
|
22309
|
+
})) await delivery.recordHostOffline(groupId);
|
|
22310
|
+
}
|
|
22311
|
+
for (const turnId of cancelledTurnIds) {
|
|
22312
|
+
const turn = await options.ports.turnStore.get(turnId);
|
|
22313
|
+
if (!turn || turn.status === "running") unconfirmedTurnIds.push(turnId);
|
|
22314
|
+
}
|
|
22315
|
+
return { stopped: true, cancelledTurnIds: cancelledTurnIds.filter(function confirmed(id) {
|
|
22316
|
+
return !unconfirmedTurnIds.includes(id);
|
|
22317
|
+
}), unconfirmedTurnIds: [...new Set(unconfirmedTurnIds)], releasedMessageIds, waitingTurnIds: [...new Set(waitingTurnIds)], pendingMessageIds: [...new Set(pendingMessageIds)], recoverableTurnIds: [...new Set(recoverableTurnIds)] };
|
|
22318
|
+
}
|
|
22319
|
+
function kick() {
|
|
22320
|
+
if (!running || stopped) return;
|
|
22321
|
+
idleDelayMs = pollIntervalMs;
|
|
22322
|
+
kicked = true;
|
|
22323
|
+
if (!ticking) void safeTick();
|
|
22324
|
+
}
|
|
22325
|
+
function registerExecution(input) {
|
|
22326
|
+
const previous = active.get(input.threadId);
|
|
22327
|
+
if (previous && (previous.ready || previous.turnId !== input.turnId)) throw Object.assign(new Error("TURN_ALREADY_RUNNING"), { code: "TURN_ALREADY_RUNNING" });
|
|
22328
|
+
const record = { threadId: input.threadId, turnId: input.turnId, groupId: "", messageId: "", cancelled: false, task: Promise.resolve(), external: true, ready: false, cancelExecution: input.cancel };
|
|
22329
|
+
active.set(input.threadId, record);
|
|
22330
|
+
return {
|
|
22331
|
+
activate: function activate() {
|
|
22332
|
+
if (active.get(input.threadId) === record) {
|
|
22333
|
+
record.ready = true;
|
|
22334
|
+
kick();
|
|
22335
|
+
}
|
|
22336
|
+
},
|
|
22337
|
+
release: function release() {
|
|
22338
|
+
if (active.get(input.threadId) === record) {
|
|
22339
|
+
active.delete(input.threadId);
|
|
22340
|
+
kick();
|
|
22341
|
+
}
|
|
22342
|
+
}
|
|
22343
|
+
};
|
|
22344
|
+
}
|
|
22345
|
+
async function start() {
|
|
22346
|
+
if (running) return;
|
|
22347
|
+
stopped = false;
|
|
22348
|
+
running = true;
|
|
22349
|
+
await safeTick(true);
|
|
22350
|
+
}
|
|
22351
|
+
return {
|
|
22352
|
+
start,
|
|
22353
|
+
stop,
|
|
22354
|
+
kick,
|
|
22355
|
+
registerExecution,
|
|
22356
|
+
isRunning: function isRunning() {
|
|
22357
|
+
return running;
|
|
22358
|
+
},
|
|
22359
|
+
reconcile: function converge() {
|
|
22360
|
+
return delivery.reconcile({ staleMs, activeMessageIds: activeMessageIds() });
|
|
22361
|
+
}
|
|
22362
|
+
};
|
|
22363
|
+
}
|
|
22364
|
+
|
|
22365
|
+
// src/node/thread-handoff.ts
|
|
22366
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
22367
|
+
import fs34 from "node:fs";
|
|
22368
|
+
import path26 from "node:path";
|
|
22369
|
+
var HANDOFF_DIRECTORY = ".autopilot";
|
|
22370
|
+
function assertWithinRoot(root, candidate) {
|
|
22371
|
+
const relative = path26.relative(root, candidate);
|
|
22372
|
+
if (!relative || relative.startsWith(`..${path26.sep}`) || relative === ".." || path26.isAbsolute(relative)) {
|
|
22373
|
+
throw new Error("THREAD_HANDOFF_WRITE_FAILED");
|
|
22374
|
+
}
|
|
22375
|
+
}
|
|
22376
|
+
function sha2562(content) {
|
|
22377
|
+
return createHash8("sha256").update(content, "utf8").digest("hex");
|
|
22378
|
+
}
|
|
22379
|
+
function createNodeThreadHandoffWriter(options) {
|
|
22380
|
+
const workspaceRoot = path26.resolve(options.workspaceRoot);
|
|
22381
|
+
function resolveTarget(handoffId) {
|
|
22382
|
+
if (!/^[0-9a-f]{16,64}$/.test(handoffId)) throw new Error("THREAD_HANDOFF_WRITE_FAILED");
|
|
22383
|
+
const realRoot = fs34.realpathSync(workspaceRoot);
|
|
22384
|
+
const directory = path26.resolve(realRoot, HANDOFF_DIRECTORY);
|
|
22385
|
+
assertWithinRoot(realRoot, directory);
|
|
22386
|
+
const filePath = path26.join(directory, `thread-passdown-${handoffId}.md`);
|
|
22387
|
+
assertWithinRoot(realRoot, filePath);
|
|
22388
|
+
return { directory, filePath };
|
|
22389
|
+
}
|
|
22390
|
+
async function write(input) {
|
|
22391
|
+
const { directory, filePath } = resolveTarget(input.handoffId);
|
|
22392
|
+
const content = `# Handoff\uFF1A${input.title}
|
|
22393
|
+
|
|
22394
|
+
${input.markdown}
|
|
22395
|
+
`;
|
|
22396
|
+
fs34.mkdirSync(directory, { recursive: true });
|
|
22397
|
+
const realDirectory = fs34.realpathSync(directory);
|
|
22398
|
+
assertWithinRoot(fs34.realpathSync(workspaceRoot), realDirectory);
|
|
22399
|
+
await withAsyncFileLock(filePath, function writeLocked() {
|
|
22400
|
+
if (fs34.existsSync(filePath)) {
|
|
22401
|
+
const existing = fs34.readFileSync(filePath, "utf8");
|
|
22402
|
+
if (existing !== content) throw new Error("THREAD_HANDOFF_CONFLICT");
|
|
22403
|
+
return;
|
|
22404
|
+
}
|
|
22405
|
+
atomicReplace(filePath, content);
|
|
22406
|
+
});
|
|
22407
|
+
const written = fs34.readFileSync(filePath, "utf8");
|
|
22408
|
+
if (written !== content) throw new Error("THREAD_HANDOFF_CONFLICT");
|
|
22409
|
+
return {
|
|
22410
|
+
handoffId: input.handoffId,
|
|
22411
|
+
relativePath: `${HANDOFF_DIRECTORY}/thread-passdown-${input.handoffId}.md`,
|
|
22412
|
+
sha256: sha2562(content)
|
|
22413
|
+
};
|
|
22414
|
+
}
|
|
22415
|
+
return { write };
|
|
22416
|
+
}
|
|
22417
|
+
|
|
22418
|
+
// src/node/host-identity.ts
|
|
22419
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
22420
|
+
var LOCAL_HUMAN_PRINCIPAL_ID = "web-local-user";
|
|
22421
|
+
function createNodeStateRootId(stateRoot) {
|
|
22422
|
+
return createHash9("sha256").update(stateRoot).digest("hex");
|
|
22423
|
+
}
|
|
21147
22424
|
export {
|
|
21148
22425
|
CHAT_ATTACHMENT_TTL_MS,
|
|
21149
22426
|
DEFAULT_COMPACT_TARGET_RATIO,
|
|
21150
22427
|
DEFAULT_COMPACT_TRIGGER_RATIO,
|
|
21151
22428
|
DEFAULT_CONTEXT_WINDOW_TOKENS,
|
|
22429
|
+
LOCAL_HUMAN_PRINCIPAL_ID,
|
|
21152
22430
|
NODE_CHAT_KNOWLEDGE_SPACE_ID,
|
|
21153
22431
|
NODE_STATE_SCHEMA_VERSION,
|
|
21154
22432
|
NODE_WORKSPACE_ID_VERSION,
|
|
@@ -21180,11 +22458,15 @@ export {
|
|
|
21180
22458
|
createNodeRagRuntime,
|
|
21181
22459
|
createNodeRuntimePorts,
|
|
21182
22460
|
createNodeSandboxPort,
|
|
22461
|
+
createNodeSessionImageStore,
|
|
21183
22462
|
createNodeSessionResourceStore,
|
|
21184
22463
|
createNodeSessionStore,
|
|
21185
22464
|
createNodeSettingsLoader,
|
|
21186
22465
|
createNodeSettingsWriter,
|
|
22466
|
+
createNodeStateRootId,
|
|
21187
22467
|
createNodeStateSchemaManager,
|
|
22468
|
+
createNodeThreadHandoffWriter,
|
|
22469
|
+
createNodeThreadRunner,
|
|
21188
22470
|
createNodeTranscriptStore,
|
|
21189
22471
|
createNodeTrustPolicy,
|
|
21190
22472
|
createNodeTrustStore,
|