@autopilot-agent/adapters 0.2.0 → 0.4.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 +11 -5
- package/dist/index.d.ts +9 -1
- package/dist/index.js +2024 -528
- package/dist/index.mjs +1996 -514
- package/dist/node/create-node-chat-capability-loader.d.ts +1 -0
- package/dist/node/desktop-status-protocol.d.ts +62 -0
- package/dist/node/file-utils.d.ts +10 -0
- package/dist/node/host-identity.d.ts +2 -0
- package/dist/node/node-errors.d.ts +13 -2
- package/dist/node/runtime-owner.d.ts +1 -0
- package/dist/node/settings/node-user-settings-service.d.ts +11 -1
- 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 +57 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -34,9 +34,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
34
34
|
));
|
|
35
35
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
36
36
|
|
|
37
|
-
// node_modules/boolbase/index.js
|
|
37
|
+
// ../../node_modules/boolbase/index.js
|
|
38
38
|
var require_boolbase = __commonJS({
|
|
39
|
-
"node_modules/boolbase/index.js"(exports2, module2) {
|
|
39
|
+
"../../node_modules/boolbase/index.js"(exports2, module2) {
|
|
40
40
|
module2.exports = {
|
|
41
41
|
trueFunc: function trueFunc() {
|
|
42
42
|
return true;
|
|
@@ -48,9 +48,9 @@ var require_boolbase = __commonJS({
|
|
|
48
48
|
}
|
|
49
49
|
});
|
|
50
50
|
|
|
51
|
-
// node_modules/css-what/lib/commonjs/types.js
|
|
51
|
+
// ../../node_modules/css-what/lib/commonjs/types.js
|
|
52
52
|
var require_types = __commonJS({
|
|
53
|
-
"node_modules/css-what/lib/commonjs/types.js"(exports2) {
|
|
53
|
+
"../../node_modules/css-what/lib/commonjs/types.js"(exports2) {
|
|
54
54
|
"use strict";
|
|
55
55
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
56
56
|
exports2.AttributeAction = exports2.IgnoreCaseMode = exports2.SelectorType = void 0;
|
|
@@ -88,9 +88,9 @@ var require_types = __commonJS({
|
|
|
88
88
|
}
|
|
89
89
|
});
|
|
90
90
|
|
|
91
|
-
// node_modules/css-what/lib/commonjs/parse.js
|
|
91
|
+
// ../../node_modules/css-what/lib/commonjs/parse.js
|
|
92
92
|
var require_parse = __commonJS({
|
|
93
|
-
"node_modules/css-what/lib/commonjs/parse.js"(exports2) {
|
|
93
|
+
"../../node_modules/css-what/lib/commonjs/parse.js"(exports2) {
|
|
94
94
|
"use strict";
|
|
95
95
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
96
96
|
exports2.parse = exports2.isTraversal = void 0;
|
|
@@ -443,9 +443,9 @@ var require_parse = __commonJS({
|
|
|
443
443
|
}
|
|
444
444
|
});
|
|
445
445
|
|
|
446
|
-
// node_modules/css-what/lib/commonjs/stringify.js
|
|
446
|
+
// ../../node_modules/css-what/lib/commonjs/stringify.js
|
|
447
447
|
var require_stringify = __commonJS({
|
|
448
|
-
"node_modules/css-what/lib/commonjs/stringify.js"(exports2) {
|
|
448
|
+
"../../node_modules/css-what/lib/commonjs/stringify.js"(exports2) {
|
|
449
449
|
"use strict";
|
|
450
450
|
var __spreadArray = exports2 && exports2.__spreadArray || function(to, from, pack) {
|
|
451
451
|
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
@@ -567,9 +567,9 @@ var require_stringify = __commonJS({
|
|
|
567
567
|
}
|
|
568
568
|
});
|
|
569
569
|
|
|
570
|
-
// node_modules/css-what/lib/commonjs/index.js
|
|
570
|
+
// ../../node_modules/css-what/lib/commonjs/index.js
|
|
571
571
|
var require_commonjs = __commonJS({
|
|
572
|
-
"node_modules/css-what/lib/commonjs/index.js"(exports2) {
|
|
572
|
+
"../../node_modules/css-what/lib/commonjs/index.js"(exports2) {
|
|
573
573
|
"use strict";
|
|
574
574
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
575
575
|
if (k2 === void 0) k2 = k;
|
|
@@ -2139,6 +2139,11 @@ __export(index_exports, {
|
|
|
2139
2139
|
DEFAULT_COMPACT_TARGET_RATIO: () => DEFAULT_COMPACT_TARGET_RATIO,
|
|
2140
2140
|
DEFAULT_COMPACT_TRIGGER_RATIO: () => DEFAULT_COMPACT_TRIGGER_RATIO,
|
|
2141
2141
|
DEFAULT_CONTEXT_WINDOW_TOKENS: () => DEFAULT_CONTEXT_WINDOW_TOKENS,
|
|
2142
|
+
DESKTOP_STATUS_FRAME_BYTES: () => DESKTOP_STATUS_FRAME_BYTES,
|
|
2143
|
+
DESKTOP_STATUS_QUEUE_BYTES: () => DESKTOP_STATUS_QUEUE_BYTES,
|
|
2144
|
+
DESKTOP_STATUS_VERSION: () => DESKTOP_STATUS_VERSION,
|
|
2145
|
+
DesktopStatusLines: () => DesktopStatusLines,
|
|
2146
|
+
LOCAL_HUMAN_PRINCIPAL_ID: () => LOCAL_HUMAN_PRINCIPAL_ID,
|
|
2142
2147
|
NODE_CHAT_KNOWLEDGE_SPACE_ID: () => NODE_CHAT_KNOWLEDGE_SPACE_ID,
|
|
2143
2148
|
NODE_STATE_SCHEMA_VERSION: () => NODE_STATE_SCHEMA_VERSION,
|
|
2144
2149
|
NODE_WORKSPACE_ID_VERSION: () => NODE_WORKSPACE_ID_VERSION,
|
|
@@ -2170,11 +2175,15 @@ __export(index_exports, {
|
|
|
2170
2175
|
createNodeRagRuntime: () => createNodeRagRuntime,
|
|
2171
2176
|
createNodeRuntimePorts: () => createNodeRuntimePorts,
|
|
2172
2177
|
createNodeSandboxPort: () => createNodeSandboxPort,
|
|
2178
|
+
createNodeSessionImageStore: () => createNodeSessionImageStore,
|
|
2173
2179
|
createNodeSessionResourceStore: () => createNodeSessionResourceStore,
|
|
2174
2180
|
createNodeSessionStore: () => createNodeSessionStore,
|
|
2175
2181
|
createNodeSettingsLoader: () => createNodeSettingsLoader,
|
|
2176
2182
|
createNodeSettingsWriter: () => createNodeSettingsWriter,
|
|
2183
|
+
createNodeStateRootId: () => createNodeStateRootId,
|
|
2177
2184
|
createNodeStateSchemaManager: () => createNodeStateSchemaManager,
|
|
2185
|
+
createNodeThreadHandoffWriter: () => createNodeThreadHandoffWriter,
|
|
2186
|
+
createNodeThreadRunner: () => createNodeThreadRunner,
|
|
2178
2187
|
createNodeTranscriptStore: () => createNodeTranscriptStore,
|
|
2179
2188
|
createNodeTrustPolicy: () => createNodeTrustPolicy,
|
|
2180
2189
|
createNodeTrustStore: () => createNodeTrustStore,
|
|
@@ -2196,6 +2205,10 @@ __export(index_exports, {
|
|
|
2196
2205
|
getNodeStatePaths: () => getNodeStatePaths,
|
|
2197
2206
|
getNodeStateSchemaDiagnostic: () => getNodeStateSchemaDiagnostic,
|
|
2198
2207
|
initializeNodeStateRoot: () => initializeNodeStateRoot,
|
|
2208
|
+
isDesktopSessionStatus: () => isDesktopSessionStatus,
|
|
2209
|
+
isDesktopStatusFrame: () => isDesktopStatusFrame,
|
|
2210
|
+
isDesktopStatusId: () => isDesktopStatusId,
|
|
2211
|
+
isDesktopStatusReply: () => isDesktopStatusReply,
|
|
2199
2212
|
isSafeSettingsFile: () => isSafeSettingsFile,
|
|
2200
2213
|
loadMcpConfigFromWorkspace: () => loadMcpConfigFromWorkspace,
|
|
2201
2214
|
resolveNodeChatStatePaths: () => resolveNodeChatStatePaths,
|
|
@@ -2205,7 +2218,8 @@ __export(index_exports, {
|
|
|
2205
2218
|
resolveNodeTrustRoot: () => resolveNodeTrustRoot,
|
|
2206
2219
|
resolveNodeUserSettingsPath: () => resolveNodeUserSettingsPath,
|
|
2207
2220
|
retrieveNodeMemories: () => retrieveNodeMemories,
|
|
2208
|
-
serializePosixCommand: () => serializePosixCommand
|
|
2221
|
+
serializePosixCommand: () => serializePosixCommand,
|
|
2222
|
+
withNodeRuntimeOwner: () => withNodeRuntimeOwner
|
|
2209
2223
|
});
|
|
2210
2224
|
module.exports = __toCommonJS(index_exports);
|
|
2211
2225
|
|
|
@@ -2242,14 +2256,20 @@ var runtimeMessages = {
|
|
|
2242
2256
|
};
|
|
2243
2257
|
var NodeStateError = class extends Error {
|
|
2244
2258
|
/** 只使用固定错误码作为消息,恢复信息保存为不可枚举的私有字段。 */
|
|
2245
|
-
constructor(code, recovery) {
|
|
2259
|
+
constructor(code, recovery, storage) {
|
|
2246
2260
|
super(code);
|
|
2247
2261
|
this.code = code;
|
|
2248
2262
|
this.name = "NodeStateError";
|
|
2249
2263
|
this.#recovery = recovery ? { ...recovery } : void 0;
|
|
2264
|
+
this.#storage = storage ? { ...storage } : void 0;
|
|
2250
2265
|
}
|
|
2251
2266
|
#recovery;
|
|
2267
|
+
#storage;
|
|
2252
2268
|
/** 受信宿主显式取得恢复信息副本,不得将它投影到 HTTP 或模型事件。 */
|
|
2269
|
+
/** 受信CLI诊断显式读取,序列化错误不会暴露内部阶段。 */
|
|
2270
|
+
getStorageDiagnostic() {
|
|
2271
|
+
return this.#storage ? { ...this.#storage } : void 0;
|
|
2272
|
+
}
|
|
2253
2273
|
getRecoveryDiagnostic() {
|
|
2254
2274
|
return this.#recovery ? { ...this.#recovery } : void 0;
|
|
2255
2275
|
}
|
|
@@ -2265,19 +2285,19 @@ var NodeChatError = class extends Error {
|
|
|
2265
2285
|
function createNodeIdentityError(code) {
|
|
2266
2286
|
return new import_core.AgentRuntimeError(code, runtimeMessages[code]);
|
|
2267
2287
|
}
|
|
2268
|
-
function toNodeBoundaryError(error, fallback) {
|
|
2288
|
+
function toNodeBoundaryError(error, fallback, storage) {
|
|
2269
2289
|
if (error instanceof Error && "code" in error && typeof error.code === "string") {
|
|
2270
2290
|
if (error.name === "AgentRuntimeError" && Object.prototype.hasOwnProperty.call(runtimeMessages, error.code)) return createNodeIdentityError(error.code);
|
|
2271
2291
|
if (error.name === "NodeStateError" && stateCodes.includes(error.code)) {
|
|
2272
|
-
return new NodeStateError(error.code, error instanceof NodeStateError ? error.getRecoveryDiagnostic() : void 0);
|
|
2292
|
+
return new NodeStateError(error.code, error instanceof NodeStateError ? error.getRecoveryDiagnostic() : void 0, storage ?? (error instanceof NodeStateError ? error.getStorageDiagnostic() : void 0));
|
|
2273
2293
|
}
|
|
2274
2294
|
if (error.name === "NodeChatError" && chatCodes.includes(error.code)) return new NodeChatError(error.code);
|
|
2275
2295
|
}
|
|
2276
|
-
return stateCodes.includes(fallback) ? new NodeStateError(fallback) : new NodeChatError(fallback);
|
|
2296
|
+
return stateCodes.includes(fallback) ? new NodeStateError(fallback, void 0, storage) : new NodeChatError(fallback);
|
|
2277
2297
|
}
|
|
2278
2298
|
|
|
2279
2299
|
// src/node/create-node-runtime-ports.ts
|
|
2280
|
-
var
|
|
2300
|
+
var import_core17 = require("@autopilot-agent/core");
|
|
2281
2301
|
|
|
2282
2302
|
// src/node/capabilities/context-budget.ts
|
|
2283
2303
|
var DEFAULT_CONTEXT_WINDOW_TOKENS = 128e3;
|
|
@@ -5489,12 +5509,12 @@ function parseSkillFrontmatter(frontmatter) {
|
|
|
5489
5509
|
return void 0;
|
|
5490
5510
|
}
|
|
5491
5511
|
}
|
|
5492
|
-
function readSkillString(
|
|
5493
|
-
const value =
|
|
5512
|
+
function readSkillString(fields2, key2) {
|
|
5513
|
+
const value = fields2[key2];
|
|
5494
5514
|
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
5495
5515
|
}
|
|
5496
|
-
function readSkillBoolean(
|
|
5497
|
-
const value =
|
|
5516
|
+
function readSkillBoolean(fields2, key2) {
|
|
5517
|
+
const value = fields2[key2];
|
|
5498
5518
|
if (typeof value === "boolean") return value;
|
|
5499
5519
|
if (typeof value !== "string") return void 0;
|
|
5500
5520
|
const normalized = value.trim().toLocaleLowerCase();
|
|
@@ -5502,8 +5522,8 @@ function readSkillBoolean(fields, key2) {
|
|
|
5502
5522
|
if (["false", "no", "off", "0"].includes(normalized)) return false;
|
|
5503
5523
|
return void 0;
|
|
5504
5524
|
}
|
|
5505
|
-
function readSkillTools(
|
|
5506
|
-
const value =
|
|
5525
|
+
function readSkillTools(fields2) {
|
|
5526
|
+
const value = fields2["allowed-tools"];
|
|
5507
5527
|
if (Array.isArray(value) && value.every(function isToolName(item) {
|
|
5508
5528
|
return typeof item === "string" && item.trim();
|
|
5509
5529
|
})) {
|
|
@@ -5517,9 +5537,9 @@ function readSkillTools(fields) {
|
|
|
5517
5537
|
return item.trim();
|
|
5518
5538
|
}).filter(Boolean);
|
|
5519
5539
|
}
|
|
5520
|
-
function readSkillDescription(
|
|
5521
|
-
const explicit = readSkillString(
|
|
5522
|
-
const whenToUse = readSkillString(
|
|
5540
|
+
function readSkillDescription(fields2, markdown) {
|
|
5541
|
+
const explicit = readSkillString(fields2, "description");
|
|
5542
|
+
const whenToUse = readSkillString(fields2, "when_to_use") ?? readSkillString(fields2, "when-to-use");
|
|
5523
5543
|
const description = explicit ?? markdown.trim().split(/\r?\n\s*\r?\n/u).find(function firstParagraph(paragraph) {
|
|
5524
5544
|
return paragraph.trim();
|
|
5525
5545
|
})?.trim();
|
|
@@ -5541,18 +5561,18 @@ function parseSkill(filePath, source, root) {
|
|
|
5541
5561
|
const content = import_node_fs3.default.readFileSync(filePath, "utf8");
|
|
5542
5562
|
const match = /^---\r?\n([\s\S]{0,4096}?)\r?\n---\r?\n/.exec(content);
|
|
5543
5563
|
if (!match) return void 0;
|
|
5544
|
-
const
|
|
5545
|
-
if (!
|
|
5564
|
+
const fields2 = parseSkillFrontmatter(match[1]);
|
|
5565
|
+
if (!fields2) return void 0;
|
|
5546
5566
|
const name = import_node_path3.default.basename(import_node_path3.default.dirname(filePath));
|
|
5547
|
-
const description = readSkillDescription(
|
|
5567
|
+
const description = readSkillDescription(fields2, content.slice(match[0].length));
|
|
5548
5568
|
if (!/^[a-z0-9-]{1,64}$/.test(name) || !description) return void 0;
|
|
5549
|
-
const declaredName = readSkillString(
|
|
5569
|
+
const declaredName = readSkillString(fields2, "name");
|
|
5550
5570
|
const displayName = declaredName && declaredName.length <= 64 ? declaredName : name;
|
|
5551
|
-
const modelInvocable = !(readSkillBoolean(
|
|
5552
|
-
const userInvocable = readSkillBoolean(
|
|
5553
|
-
const argumentHint = readSkillString(
|
|
5554
|
-
const whenToUse = readSkillString(
|
|
5555
|
-
const allowedTools = readSkillTools(
|
|
5571
|
+
const modelInvocable = !(readSkillBoolean(fields2, "disable-model-invocation") ?? false);
|
|
5572
|
+
const userInvocable = readSkillBoolean(fields2, "user-invocable") ?? true;
|
|
5573
|
+
const argumentHint = readSkillString(fields2, "argument-hint") ?? readSkillString(fields2, "dash-hint");
|
|
5574
|
+
const whenToUse = readSkillString(fields2, "when_to_use") ?? readSkillString(fields2, "when-to-use");
|
|
5575
|
+
const allowedTools = readSkillTools(fields2);
|
|
5556
5576
|
const canonical = import_node_fs3.default.realpathSync.native(filePath);
|
|
5557
5577
|
const contentHash = import_node_crypto2.default.createHash("sha256").update(content).digest("hex");
|
|
5558
5578
|
const skillId = `${source}:${import_node_crypto2.default.createHash("sha256").update(canonical).digest("hex").slice(0, 16)}:${contentHash.slice(0, 16)}`;
|
|
@@ -8010,7 +8030,7 @@ var Parser = class {
|
|
|
8010
8030
|
}
|
|
8011
8031
|
};
|
|
8012
8032
|
|
|
8013
|
-
// ../../node_modules/
|
|
8033
|
+
// ../../node_modules/domelementtype/lib/esm/index.js
|
|
8014
8034
|
var esm_exports = {};
|
|
8015
8035
|
__export(esm_exports, {
|
|
8016
8036
|
CDATA: () => CDATA,
|
|
@@ -8026,16 +8046,16 @@ __export(esm_exports, {
|
|
|
8026
8046
|
isTag: () => isTag
|
|
8027
8047
|
});
|
|
8028
8048
|
var ElementType;
|
|
8029
|
-
(function(
|
|
8030
|
-
|
|
8031
|
-
|
|
8032
|
-
|
|
8033
|
-
|
|
8034
|
-
|
|
8035
|
-
|
|
8036
|
-
|
|
8037
|
-
|
|
8038
|
-
|
|
8049
|
+
(function(ElementType2) {
|
|
8050
|
+
ElementType2["Root"] = "root";
|
|
8051
|
+
ElementType2["Text"] = "text";
|
|
8052
|
+
ElementType2["Directive"] = "directive";
|
|
8053
|
+
ElementType2["Comment"] = "comment";
|
|
8054
|
+
ElementType2["Script"] = "script";
|
|
8055
|
+
ElementType2["Style"] = "style";
|
|
8056
|
+
ElementType2["Tag"] = "tag";
|
|
8057
|
+
ElementType2["CDATA"] = "cdata";
|
|
8058
|
+
ElementType2["Doctype"] = "doctype";
|
|
8039
8059
|
})(ElementType || (ElementType = {}));
|
|
8040
8060
|
function isTag(elem) {
|
|
8041
8061
|
return elem.type === ElementType.Tag || elem.type === ElementType.Script || elem.type === ElementType.Style;
|
|
@@ -11008,8 +11028,8 @@ var Comment3 = class _Comment extends CharacterData {
|
|
|
11008
11028
|
};
|
|
11009
11029
|
|
|
11010
11030
|
// node_modules/domutils/lib/esm/index.js
|
|
11011
|
-
var
|
|
11012
|
-
__export(
|
|
11031
|
+
var esm_exports4 = {};
|
|
11032
|
+
__export(esm_exports4, {
|
|
11013
11033
|
DocumentPosition: () => DocumentPosition2,
|
|
11014
11034
|
append: () => append3,
|
|
11015
11035
|
appendChild: () => appendChild2,
|
|
@@ -11040,7 +11060,7 @@ __export(esm_exports5, {
|
|
|
11040
11060
|
isCDATA: () => isCDATA2,
|
|
11041
11061
|
isComment: () => isComment2,
|
|
11042
11062
|
isDocument: () => isDocument2,
|
|
11043
|
-
isTag: () =>
|
|
11063
|
+
isTag: () => isTag3,
|
|
11044
11064
|
isText: () => isText2,
|
|
11045
11065
|
nextElementSibling: () => nextElementSibling3,
|
|
11046
11066
|
prepend: () => prepend2,
|
|
@@ -11054,47 +11074,21 @@ __export(esm_exports5, {
|
|
|
11054
11074
|
uniqueSort: () => uniqueSort2
|
|
11055
11075
|
});
|
|
11056
11076
|
|
|
11057
|
-
// node_modules/domelementtype/lib/esm/index.js
|
|
11058
|
-
var ElementType2;
|
|
11059
|
-
(function(ElementType3) {
|
|
11060
|
-
ElementType3["Root"] = "root";
|
|
11061
|
-
ElementType3["Text"] = "text";
|
|
11062
|
-
ElementType3["Directive"] = "directive";
|
|
11063
|
-
ElementType3["Comment"] = "comment";
|
|
11064
|
-
ElementType3["Script"] = "script";
|
|
11065
|
-
ElementType3["Style"] = "style";
|
|
11066
|
-
ElementType3["Tag"] = "tag";
|
|
11067
|
-
ElementType3["CDATA"] = "cdata";
|
|
11068
|
-
ElementType3["Doctype"] = "doctype";
|
|
11069
|
-
})(ElementType2 || (ElementType2 = {}));
|
|
11070
|
-
function isTag3(elem) {
|
|
11071
|
-
return elem.type === ElementType2.Tag || elem.type === ElementType2.Script || elem.type === ElementType2.Style;
|
|
11072
|
-
}
|
|
11073
|
-
var Root2 = ElementType2.Root;
|
|
11074
|
-
var Text3 = ElementType2.Text;
|
|
11075
|
-
var Directive2 = ElementType2.Directive;
|
|
11076
|
-
var Comment4 = ElementType2.Comment;
|
|
11077
|
-
var Script2 = ElementType2.Script;
|
|
11078
|
-
var Style2 = ElementType2.Style;
|
|
11079
|
-
var Tag2 = ElementType2.Tag;
|
|
11080
|
-
var CDATA3 = ElementType2.CDATA;
|
|
11081
|
-
var Doctype2 = ElementType2.Doctype;
|
|
11082
|
-
|
|
11083
11077
|
// node_modules/domhandler/lib/esm/node.js
|
|
11084
|
-
function
|
|
11085
|
-
return
|
|
11078
|
+
function isTag3(node) {
|
|
11079
|
+
return isTag(node);
|
|
11086
11080
|
}
|
|
11087
11081
|
function isCDATA2(node) {
|
|
11088
|
-
return node.type ===
|
|
11082
|
+
return node.type === ElementType.CDATA;
|
|
11089
11083
|
}
|
|
11090
11084
|
function isText2(node) {
|
|
11091
|
-
return node.type ===
|
|
11085
|
+
return node.type === ElementType.Text;
|
|
11092
11086
|
}
|
|
11093
11087
|
function isComment2(node) {
|
|
11094
|
-
return node.type ===
|
|
11088
|
+
return node.type === ElementType.Comment;
|
|
11095
11089
|
}
|
|
11096
11090
|
function isDocument2(node) {
|
|
11097
|
-
return node.type ===
|
|
11091
|
+
return node.type === ElementType.Root;
|
|
11098
11092
|
}
|
|
11099
11093
|
function hasChildren2(node) {
|
|
11100
11094
|
return Object.prototype.hasOwnProperty.call(node, "children");
|
|
@@ -11781,21 +11775,21 @@ function render2(node, options = {}) {
|
|
|
11781
11775
|
var esm_default2 = render2;
|
|
11782
11776
|
function renderNode2(node, options) {
|
|
11783
11777
|
switch (node.type) {
|
|
11784
|
-
case
|
|
11778
|
+
case Root:
|
|
11785
11779
|
return render2(node.children, options);
|
|
11786
11780
|
// @ts-expect-error We don't use `Doctype` yet
|
|
11787
|
-
case
|
|
11788
|
-
case
|
|
11781
|
+
case Doctype:
|
|
11782
|
+
case Directive:
|
|
11789
11783
|
return renderDirective2(node);
|
|
11790
|
-
case
|
|
11784
|
+
case Comment:
|
|
11791
11785
|
return renderComment2(node);
|
|
11792
|
-
case
|
|
11786
|
+
case CDATA:
|
|
11793
11787
|
return renderCdata2(node);
|
|
11794
|
-
case
|
|
11795
|
-
case
|
|
11796
|
-
case
|
|
11788
|
+
case Script:
|
|
11789
|
+
case Style:
|
|
11790
|
+
case Tag:
|
|
11797
11791
|
return renderTag2(node, options);
|
|
11798
|
-
case
|
|
11792
|
+
case Text:
|
|
11799
11793
|
return renderText2(node, options);
|
|
11800
11794
|
}
|
|
11801
11795
|
}
|
|
@@ -11876,7 +11870,7 @@ function getInnerHTML2(node, options) {
|
|
|
11876
11870
|
function getText2(node) {
|
|
11877
11871
|
if (Array.isArray(node))
|
|
11878
11872
|
return node.map(getText2).join("");
|
|
11879
|
-
if (
|
|
11873
|
+
if (isTag3(node))
|
|
11880
11874
|
return node.name === "br" ? "\n" : getText2(node.children);
|
|
11881
11875
|
if (isCDATA2(node))
|
|
11882
11876
|
return getText2(node.children);
|
|
@@ -11897,7 +11891,7 @@ function textContent2(node) {
|
|
|
11897
11891
|
function innerText2(node) {
|
|
11898
11892
|
if (Array.isArray(node))
|
|
11899
11893
|
return node.map(innerText2).join("");
|
|
11900
|
-
if (hasChildren2(node) && (node.type ===
|
|
11894
|
+
if (hasChildren2(node) && (node.type === ElementType.Tag || isCDATA2(node))) {
|
|
11901
11895
|
return innerText2(node.children);
|
|
11902
11896
|
}
|
|
11903
11897
|
if (isText2(node))
|
|
@@ -11940,13 +11934,13 @@ function getName2(elem) {
|
|
|
11940
11934
|
}
|
|
11941
11935
|
function nextElementSibling3(elem) {
|
|
11942
11936
|
let { next } = elem;
|
|
11943
|
-
while (next !== null && !
|
|
11937
|
+
while (next !== null && !isTag3(next))
|
|
11944
11938
|
({ next } = next);
|
|
11945
11939
|
return next;
|
|
11946
11940
|
}
|
|
11947
11941
|
function prevElementSibling2(elem) {
|
|
11948
11942
|
let { prev } = elem;
|
|
11949
|
-
while (prev !== null && !
|
|
11943
|
+
while (prev !== null && !isTag3(prev))
|
|
11950
11944
|
({ prev } = prev);
|
|
11951
11945
|
return prev;
|
|
11952
11946
|
}
|
|
@@ -12078,7 +12072,7 @@ function findOne2(test, nodes, recurse = true) {
|
|
|
12078
12072
|
const searchedNodes = Array.isArray(nodes) ? nodes : [nodes];
|
|
12079
12073
|
for (let i = 0; i < searchedNodes.length; i++) {
|
|
12080
12074
|
const node = searchedNodes[i];
|
|
12081
|
-
if (
|
|
12075
|
+
if (isTag3(node) && test(node)) {
|
|
12082
12076
|
return node;
|
|
12083
12077
|
}
|
|
12084
12078
|
if (recurse && hasChildren2(node) && node.children.length > 0) {
|
|
@@ -12090,7 +12084,7 @@ function findOne2(test, nodes, recurse = true) {
|
|
|
12090
12084
|
return null;
|
|
12091
12085
|
}
|
|
12092
12086
|
function existsOne2(test, nodes) {
|
|
12093
|
-
return (Array.isArray(nodes) ? nodes : [nodes]).some((node) =>
|
|
12087
|
+
return (Array.isArray(nodes) ? nodes : [nodes]).some((node) => isTag3(node) && test(node) || hasChildren2(node) && existsOne2(test, node.children));
|
|
12094
12088
|
}
|
|
12095
12089
|
function findAll2(test, nodes) {
|
|
12096
12090
|
const result = [];
|
|
@@ -12106,7 +12100,7 @@ function findAll2(test, nodes) {
|
|
|
12106
12100
|
continue;
|
|
12107
12101
|
}
|
|
12108
12102
|
const elem = nodeStack[0][indexStack[0]++];
|
|
12109
|
-
if (
|
|
12103
|
+
if (isTag3(elem) && test(elem))
|
|
12110
12104
|
result.push(elem);
|
|
12111
12105
|
if (hasChildren2(elem) && elem.children.length > 0) {
|
|
12112
12106
|
indexStack.unshift(0);
|
|
@@ -12119,11 +12113,11 @@ function findAll2(test, nodes) {
|
|
|
12119
12113
|
var Checks2 = {
|
|
12120
12114
|
tag_name(name) {
|
|
12121
12115
|
if (typeof name === "function") {
|
|
12122
|
-
return (elem) =>
|
|
12116
|
+
return (elem) => isTag3(elem) && name(elem.name);
|
|
12123
12117
|
} else if (name === "*") {
|
|
12124
|
-
return
|
|
12118
|
+
return isTag3;
|
|
12125
12119
|
}
|
|
12126
|
-
return (elem) =>
|
|
12120
|
+
return (elem) => isTag3(elem) && elem.name === name;
|
|
12127
12121
|
},
|
|
12128
12122
|
tag_type(type2) {
|
|
12129
12123
|
if (typeof type2 === "function") {
|
|
@@ -12140,9 +12134,9 @@ var Checks2 = {
|
|
|
12140
12134
|
};
|
|
12141
12135
|
function getAttribCheck2(attrib, value) {
|
|
12142
12136
|
if (typeof value === "function") {
|
|
12143
|
-
return (elem) =>
|
|
12137
|
+
return (elem) => isTag3(elem) && value(elem.attribs[attrib]);
|
|
12144
12138
|
}
|
|
12145
|
-
return (elem) =>
|
|
12139
|
+
return (elem) => isTag3(elem) && elem.attribs[attrib] === value;
|
|
12146
12140
|
}
|
|
12147
12141
|
function combineFuncs2(a, b) {
|
|
12148
12142
|
return (elem) => a(elem) || b(elem);
|
|
@@ -12629,7 +12623,7 @@ var attributeRules = {
|
|
|
12629
12623
|
// node_modules/css-select/lib/esm/pseudo-selectors/index.js
|
|
12630
12624
|
var import_css_what2 = __toESM(require_commonjs(), 1);
|
|
12631
12625
|
|
|
12632
|
-
// node_modules/nth-check/lib/esm/parse.js
|
|
12626
|
+
// ../../node_modules/nth-check/lib/esm/parse.js
|
|
12633
12627
|
var whitespace = /* @__PURE__ */ new Set([9, 10, 12, 13, 32]);
|
|
12634
12628
|
var ZERO = "0".charCodeAt(0);
|
|
12635
12629
|
var NINE = "9".charCodeAt(0);
|
|
@@ -12686,7 +12680,7 @@ function parse(formula) {
|
|
|
12686
12680
|
}
|
|
12687
12681
|
}
|
|
12688
12682
|
|
|
12689
|
-
// node_modules/nth-check/lib/esm/compile.js
|
|
12683
|
+
// ../../node_modules/nth-check/lib/esm/compile.js
|
|
12690
12684
|
var import_boolbase2 = __toESM(require_boolbase(), 1);
|
|
12691
12685
|
function compile(parsed) {
|
|
12692
12686
|
const a = parsed[0];
|
|
@@ -12704,7 +12698,7 @@ function compile(parsed) {
|
|
|
12704
12698
|
return a > 1 ? (index) => index >= b && index % absA === bMod : (index) => index <= b && index % absA === bMod;
|
|
12705
12699
|
}
|
|
12706
12700
|
|
|
12707
|
-
// node_modules/nth-check/lib/esm/index.js
|
|
12701
|
+
// ../../node_modules/nth-check/lib/esm/index.js
|
|
12708
12702
|
function nthCheck(formula) {
|
|
12709
12703
|
return compile(parse(formula));
|
|
12710
12704
|
}
|
|
@@ -13265,13 +13259,13 @@ function reduceRules(a, b) {
|
|
|
13265
13259
|
// node_modules/css-select/lib/esm/index.js
|
|
13266
13260
|
var defaultEquals = (a, b) => a === b;
|
|
13267
13261
|
var defaultOptions = {
|
|
13268
|
-
adapter:
|
|
13262
|
+
adapter: esm_exports4,
|
|
13269
13263
|
equals: defaultEquals
|
|
13270
13264
|
};
|
|
13271
13265
|
function convertOptionFormats(options) {
|
|
13272
13266
|
var _a4, _b, _c, _d;
|
|
13273
13267
|
const opts = options !== null && options !== void 0 ? options : defaultOptions;
|
|
13274
|
-
(_a4 = opts.adapter) !== null && _a4 !== void 0 ? _a4 : opts.adapter =
|
|
13268
|
+
(_a4 = opts.adapter) !== null && _a4 !== void 0 ? _a4 : opts.adapter = esm_exports4;
|
|
13275
13269
|
(_b = opts.equals) !== null && _b !== void 0 ? _b : opts.equals = (_d = (_c = opts.adapter) === null || _c === void 0 ? void 0 : _c.equals) !== null && _d !== void 0 ? _d : defaultEquals;
|
|
13276
13270
|
return opts;
|
|
13277
13271
|
}
|
|
@@ -13318,9 +13312,9 @@ function is2(elem, query2, options) {
|
|
|
13318
13312
|
|
|
13319
13313
|
// node_modules/linkedom/esm/shared/matches.js
|
|
13320
13314
|
var { isArray } = Array;
|
|
13321
|
-
var
|
|
13315
|
+
var isTag4 = ({ nodeType }) => nodeType === ELEMENT_NODE;
|
|
13322
13316
|
var existsOne3 = (test, elements) => elements.some(
|
|
13323
|
-
(element) =>
|
|
13317
|
+
(element) => isTag4(element) && (test(element) || existsOne3(test, getChildren3(element)))
|
|
13324
13318
|
);
|
|
13325
13319
|
var getAttributeValue3 = (element, name) => name === "class" ? element.classList.value : element.getAttribute(name);
|
|
13326
13320
|
var getChildren3 = ({ childNodes }) => childNodes;
|
|
@@ -13336,7 +13330,7 @@ var getSiblings3 = (element) => {
|
|
|
13336
13330
|
var getText3 = (node) => {
|
|
13337
13331
|
if (isArray(node))
|
|
13338
13332
|
return node.map(getText3).join("");
|
|
13339
|
-
if (
|
|
13333
|
+
if (isTag4(node))
|
|
13340
13334
|
return getText3(getChildren3(node));
|
|
13341
13335
|
if (node.nodeType === TEXT_NODE)
|
|
13342
13336
|
return node.data;
|
|
@@ -13363,7 +13357,7 @@ var removeSubsets3 = (nodes) => {
|
|
|
13363
13357
|
var findAll3 = (test, nodes) => {
|
|
13364
13358
|
const matches3 = [];
|
|
13365
13359
|
for (const node of nodes) {
|
|
13366
|
-
if (
|
|
13360
|
+
if (isTag4(node)) {
|
|
13367
13361
|
if (test(node))
|
|
13368
13362
|
matches3.push(node);
|
|
13369
13363
|
matches3.push(...findAll3(test, getChildren3(node)));
|
|
@@ -13378,7 +13372,7 @@ var findOne3 = (test, nodes) => {
|
|
|
13378
13372
|
return null;
|
|
13379
13373
|
};
|
|
13380
13374
|
var adapter = {
|
|
13381
|
-
isTag:
|
|
13375
|
+
isTag: isTag4,
|
|
13382
13376
|
existsOne: existsOne3,
|
|
13383
13377
|
getAttributeValue: getAttributeValue3,
|
|
13384
13378
|
getChildren: getChildren3,
|
|
@@ -13411,7 +13405,7 @@ var matches = (element, selectors) => is2(
|
|
|
13411
13405
|
);
|
|
13412
13406
|
|
|
13413
13407
|
// node_modules/linkedom/esm/interface/text.js
|
|
13414
|
-
var
|
|
13408
|
+
var Text4 = class _Text extends CharacterData {
|
|
13415
13409
|
constructor(ownerDocument, data = "") {
|
|
13416
13410
|
super(ownerDocument, "#text", TEXT_NODE, data);
|
|
13417
13411
|
}
|
|
@@ -13450,7 +13444,7 @@ var insert = (parentNode, child, nodes) => {
|
|
|
13450
13444
|
const { ownerDocument } = parentNode;
|
|
13451
13445
|
for (const node of nodes)
|
|
13452
13446
|
parentNode.insertBefore(
|
|
13453
|
-
isNode(node) ? node : new
|
|
13447
|
+
isNode(node) ? node : new Text4(ownerDocument, node),
|
|
13454
13448
|
child
|
|
13455
13449
|
);
|
|
13456
13450
|
};
|
|
@@ -14261,7 +14255,7 @@ var Element3 = class extends ParentNode {
|
|
|
14261
14255
|
set textContent(text) {
|
|
14262
14256
|
this.replaceChildren();
|
|
14263
14257
|
if (text != null && text !== "")
|
|
14264
|
-
this.appendChild(new
|
|
14258
|
+
this.appendChild(new Text4(this.ownerDocument, text));
|
|
14265
14259
|
}
|
|
14266
14260
|
get innerHTML() {
|
|
14267
14261
|
return getInnerHtml(this);
|
|
@@ -14635,11 +14629,11 @@ function CharacterData2() {
|
|
|
14635
14629
|
}
|
|
14636
14630
|
setPrototypeOf(CharacterData2, CharacterData);
|
|
14637
14631
|
CharacterData2.prototype = CharacterData.prototype;
|
|
14638
|
-
function
|
|
14632
|
+
function Comment5() {
|
|
14639
14633
|
illegalConstructor();
|
|
14640
14634
|
}
|
|
14641
|
-
setPrototypeOf(
|
|
14642
|
-
|
|
14635
|
+
setPrototypeOf(Comment5, Comment3);
|
|
14636
|
+
Comment5.prototype = Comment3.prototype;
|
|
14643
14637
|
function DocumentFragment2() {
|
|
14644
14638
|
illegalConstructor();
|
|
14645
14639
|
}
|
|
@@ -14665,11 +14659,11 @@ function ShadowRoot2() {
|
|
|
14665
14659
|
}
|
|
14666
14660
|
setPrototypeOf(ShadowRoot2, ShadowRoot);
|
|
14667
14661
|
ShadowRoot2.prototype = ShadowRoot.prototype;
|
|
14668
|
-
function
|
|
14662
|
+
function Text5() {
|
|
14669
14663
|
illegalConstructor();
|
|
14670
14664
|
}
|
|
14671
|
-
setPrototypeOf(
|
|
14672
|
-
|
|
14665
|
+
setPrototypeOf(Text5, Text4);
|
|
14666
|
+
Text5.prototype = Text4.prototype;
|
|
14673
14667
|
function SVGElement2() {
|
|
14674
14668
|
illegalConstructor();
|
|
14675
14669
|
}
|
|
@@ -14679,13 +14673,13 @@ var Facades = {
|
|
|
14679
14673
|
Attr: Attr2,
|
|
14680
14674
|
CDATASection: CDATASection2,
|
|
14681
14675
|
CharacterData: CharacterData2,
|
|
14682
|
-
Comment:
|
|
14676
|
+
Comment: Comment5,
|
|
14683
14677
|
DocumentFragment: DocumentFragment2,
|
|
14684
14678
|
DocumentType: DocumentType2,
|
|
14685
14679
|
Element: Element4,
|
|
14686
14680
|
Node: Node3,
|
|
14687
14681
|
ShadowRoot: ShadowRoot2,
|
|
14688
|
-
Text:
|
|
14682
|
+
Text: Text5,
|
|
14689
14683
|
SVGElement: SVGElement2
|
|
14690
14684
|
};
|
|
14691
14685
|
|
|
@@ -16701,7 +16695,7 @@ var Document3 = class extends NonElementParentNode {
|
|
|
16701
16695
|
return range;
|
|
16702
16696
|
}
|
|
16703
16697
|
createTextNode(textContent3) {
|
|
16704
|
-
return new
|
|
16698
|
+
return new Text4(this, textContent3);
|
|
16705
16699
|
}
|
|
16706
16700
|
createTreeWalker(root, whatToShow = -1) {
|
|
16707
16701
|
return new TreeWalker(root, whatToShow);
|
|
@@ -17050,13 +17044,13 @@ async function validatePublicWebUrl(rawUrl, options = {}) {
|
|
|
17050
17044
|
if (value.length > 2e3) throw new Error("URL_TOO_LONG");
|
|
17051
17045
|
url = new URL(value);
|
|
17052
17046
|
} catch {
|
|
17053
|
-
throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u65E0\u6548");
|
|
17047
|
+
throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u65E0\u6548", void 0, "url_not_allowed");
|
|
17054
17048
|
}
|
|
17055
17049
|
if (url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password || !url.hostname) {
|
|
17056
|
-
throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE");
|
|
17050
|
+
throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE", void 0, "url_not_allowed");
|
|
17057
17051
|
}
|
|
17058
17052
|
const hostname = normalizeHostname(url.hostname).toLowerCase();
|
|
17059
|
-
if (isBlockedHostname(hostname)) throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE");
|
|
17053
|
+
if (isBlockedHostname(hostname)) throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE", void 0, "url_not_allowed");
|
|
17060
17054
|
let addresses;
|
|
17061
17055
|
const literalFamily = (0, import_node_net.isIP)(hostname);
|
|
17062
17056
|
if (literalFamily === 4 || literalFamily === 6) {
|
|
@@ -17066,14 +17060,14 @@ async function validatePublicWebUrl(rawUrl, options = {}) {
|
|
|
17066
17060
|
addresses = await (options.resolveDns ?? resolveWebFetchDns)(hostname, options.signal);
|
|
17067
17061
|
} catch (error) {
|
|
17068
17062
|
if (options.signal?.aborted || error instanceof Error && error.name === "AbortError") throw createAbortError();
|
|
17069
|
-
throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u89E3\u6790\u5931\u8D25");
|
|
17063
|
+
throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u89E3\u6790\u5931\u8D25", void 0, "dns_failed");
|
|
17070
17064
|
}
|
|
17071
17065
|
}
|
|
17072
|
-
if (addresses.length === 0) throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u89E3\u6790\u5931\u8D25");
|
|
17066
|
+
if (addresses.length === 0) throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u89E3\u6790\u5931\u8D25", void 0, "dns_failed");
|
|
17073
17067
|
const unique = /* @__PURE__ */ new Map();
|
|
17074
17068
|
for (const record of addresses) {
|
|
17075
17069
|
if (!isPublicWebAddress(record.address, record.family)) {
|
|
17076
|
-
throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE");
|
|
17070
|
+
throw new import_core6.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE", void 0, "non_public_address");
|
|
17077
17071
|
}
|
|
17078
17072
|
unique.set(`${record.family}:${record.address}`, { address: record.address, family: record.family });
|
|
17079
17073
|
}
|
|
@@ -17282,7 +17276,7 @@ function createSafeWebFetchCapability(options = {}) {
|
|
|
17282
17276
|
/** 读取明确 URL;跨域目标和剩余跳数只交给 Core,在审批后续接。 */
|
|
17283
17277
|
async fetch(input) {
|
|
17284
17278
|
if (input.redirectsRemaining !== void 0 && (!Number.isInteger(input.redirectsRemaining) || input.redirectsRemaining < 0 || input.redirectsRemaining > MAX_REDIRECTS)) {
|
|
17285
|
-
throw new import_core7.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u9884\u7B97\u65E0\u6548");
|
|
17279
|
+
throw new import_core7.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u9884\u7B97\u65E0\u6548", void 0, "redirect_rejected");
|
|
17286
17280
|
}
|
|
17287
17281
|
const original = await validatePublicWebUrl(input.url, { resolveDns, signal: input.signal });
|
|
17288
17282
|
let current = original;
|
|
@@ -17295,19 +17289,19 @@ function createSafeWebFetchCapability(options = {}) {
|
|
|
17295
17289
|
const location = readHeader(response.headers, "location");
|
|
17296
17290
|
if (!location || redirectCount >= redirectLimit) {
|
|
17297
17291
|
response.abort();
|
|
17298
|
-
throw new import_core7.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u65E0\u6548\u6216\u8D85\u8FC7\u4E0A\u9650");
|
|
17292
|
+
throw new import_core7.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u65E0\u6548\u6216\u8D85\u8FC7\u4E0A\u9650", void 0, "redirect_rejected");
|
|
17299
17293
|
}
|
|
17300
17294
|
let redirectUrl;
|
|
17301
17295
|
try {
|
|
17302
17296
|
redirectUrl = new URL(location, current.url);
|
|
17303
17297
|
} catch {
|
|
17304
17298
|
response.abort();
|
|
17305
|
-
throw new import_core7.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u5730\u5740\u65E0\u6548");
|
|
17299
|
+
throw new import_core7.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u5730\u5740\u65E0\u6548", void 0, "redirect_rejected");
|
|
17306
17300
|
}
|
|
17307
17301
|
if (redirectUrl.hostname.toLowerCase() !== current.url.hostname.toLowerCase()) {
|
|
17308
17302
|
response.abort();
|
|
17309
17303
|
if (!["http:", "https:"].includes(redirectUrl.protocol) || redirectUrl.username || redirectUrl.password) {
|
|
17310
|
-
throw new import_core7.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u5730\u5740\u65E0\u6548");
|
|
17304
|
+
throw new import_core7.WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u5730\u5740\u65E0\u6548", void 0, "redirect_rejected");
|
|
17311
17305
|
}
|
|
17312
17306
|
throw new import_core7.WebFetchCapabilityError("WEB_REDIRECT_REQUIRES_APPROVAL", "\u7F51\u9875\u91CD\u5B9A\u5411\u9700\u8981\u65B0\u7684\u57DF\u540D\u5BA1\u6279", {
|
|
17313
17307
|
url: redirectUrl.toString(),
|
|
@@ -17409,7 +17403,7 @@ function hostExecutionCapabilityReport() {
|
|
|
17409
17403
|
installed: false,
|
|
17410
17404
|
provisioned: false,
|
|
17411
17405
|
diagnostics: [
|
|
17412
|
-
"Windows \u5BBF\u4E3B\u6267\u884C\u6A21\u5F0F\uFF1A\u8FDB\u7A0B\u6C99\u7BB1\u5DF2\u505C\u7528\uFF0C\
|
|
17406
|
+
"Windows \u5BBF\u4E3B\u6267\u884C\u6A21\u5F0F\uFF1A\u8FDB\u7A0B\u6C99\u7BB1\u5DF2\u505C\u7528\uFF0C\u8C03\u7528\u6309\u6743\u9650\u6A21\u5F0F\u4E0E\u98CE\u9669\u5206\u6D41\uFF0C\u5728\u5BBF\u4E3B\u4EE5\u5F53\u524D\u7528\u6237\u6743\u9650\u76F4\u63A5\u6267\u884C"
|
|
17413
17407
|
]
|
|
17414
17408
|
};
|
|
17415
17409
|
}
|
|
@@ -17453,7 +17447,7 @@ function loadSrtRuntimeSurface() {
|
|
|
17453
17447
|
}
|
|
17454
17448
|
|
|
17455
17449
|
// src/node/sandbox/node-sandbox-port.ts
|
|
17456
|
-
var
|
|
17450
|
+
var import_node_path9 = __toESM(require("node:path"));
|
|
17457
17451
|
|
|
17458
17452
|
// src/node/file-mutation-locks.ts
|
|
17459
17453
|
var import_node_os2 = __toESM(require("node:os"));
|
|
@@ -17465,6 +17459,16 @@ var import_node_fs5 = __toESM(require("node:fs"));
|
|
|
17465
17459
|
var import_promises2 = __toESM(require("node:fs/promises"));
|
|
17466
17460
|
var import_node_crypto3 = require("node:crypto");
|
|
17467
17461
|
var import_node_path4 = __toESM(require("node:path"));
|
|
17462
|
+
var fileDiagnostics = /* @__PURE__ */ new WeakMap();
|
|
17463
|
+
function getFileOperationDiagnostic(error) {
|
|
17464
|
+
return error && typeof error === "object" ? fileDiagnostics.get(error) : void 0;
|
|
17465
|
+
}
|
|
17466
|
+
function rememberFileFailure(error, diagnostic) {
|
|
17467
|
+
if (!error || typeof error !== "object") return;
|
|
17468
|
+
const code = error.code;
|
|
17469
|
+
const osCode = ["EACCES", "EPERM", "ENOENT", "EEXIST", "ENOSPC", "EIO", "EMFILE", "ENFILE", "EBUSY", "EROFS", "ENOTDIR", "ETIMEDOUT"].includes(code ?? "") ? code : void 0;
|
|
17470
|
+
fileDiagnostics.set(error, { ...diagnostic, ...osCode ? { osCode } : {} });
|
|
17471
|
+
}
|
|
17468
17472
|
var fileLocks = /* @__PURE__ */ new Map();
|
|
17469
17473
|
var PROCESS_LOCK_RETRY_MS = 10;
|
|
17470
17474
|
var PROCESS_LOCK_TIMEOUT_MS = 3e4;
|
|
@@ -17557,15 +17561,31 @@ async function acquireProcessLock(filePath, requireExitedOwner = false) {
|
|
|
17557
17561
|
}
|
|
17558
17562
|
}
|
|
17559
17563
|
}
|
|
17560
|
-
function
|
|
17564
|
+
async function removeOwnedProcessLock(lockPath, ownerId) {
|
|
17565
|
+
const startedAt = Date.now();
|
|
17566
|
+
while (true) {
|
|
17567
|
+
try {
|
|
17568
|
+
const metadata = JSON.parse(await import_promises2.default.readFile(lockPath, "utf8"));
|
|
17569
|
+
if (metadata.ownerId !== ownerId) return;
|
|
17570
|
+
await import_promises2.default.unlink(lockPath);
|
|
17571
|
+
return;
|
|
17572
|
+
} catch (error) {
|
|
17573
|
+
const code = error.code;
|
|
17574
|
+
if (code === "ENOENT") return;
|
|
17575
|
+
if ((code === "EPERM" || code === "EACCES" || code === "EBUSY") && Date.now() - startedAt < PROCESS_LOCK_TIMEOUT_MS) {
|
|
17576
|
+
await waitForProcessLock();
|
|
17577
|
+
continue;
|
|
17578
|
+
}
|
|
17579
|
+
rememberFileFailure(error, { phase: "cleanup", cleanupFailed: true });
|
|
17580
|
+
throw error;
|
|
17581
|
+
}
|
|
17582
|
+
}
|
|
17583
|
+
}
|
|
17584
|
+
async function releaseProcessLock(handle) {
|
|
17561
17585
|
try {
|
|
17562
17586
|
import_node_fs5.default.closeSync(handle.descriptor);
|
|
17563
17587
|
} finally {
|
|
17564
|
-
|
|
17565
|
-
const metadata = JSON.parse(import_node_fs5.default.readFileSync(handle.lockPath, "utf8"));
|
|
17566
|
-
if (metadata.ownerId === handle.ownerId) import_node_fs5.default.unlinkSync(handle.lockPath);
|
|
17567
|
-
} catch {
|
|
17568
|
-
}
|
|
17588
|
+
await removeOwnedProcessLock(handle.lockPath, handle.ownerId);
|
|
17569
17589
|
}
|
|
17570
17590
|
}
|
|
17571
17591
|
async function withFileLock(filePath, operation, options) {
|
|
@@ -17579,11 +17599,18 @@ async function withFileLock(filePath, operation, options) {
|
|
|
17579
17599
|
fileLocks.set(key2, queued);
|
|
17580
17600
|
try {
|
|
17581
17601
|
await previous;
|
|
17582
|
-
const
|
|
17602
|
+
const startedAt = Date.now();
|
|
17603
|
+
let handle;
|
|
17604
|
+
try {
|
|
17605
|
+
handle = await acquireProcessLock(key2, options?.requireExitedOwner);
|
|
17606
|
+
} catch (error) {
|
|
17607
|
+
rememberFileFailure(error, { phase: "lock", lockWaitMs: Date.now() - startedAt });
|
|
17608
|
+
throw error;
|
|
17609
|
+
}
|
|
17583
17610
|
try {
|
|
17584
17611
|
return await operation();
|
|
17585
17612
|
} finally {
|
|
17586
|
-
releaseProcessLock(handle);
|
|
17613
|
+
await releaseProcessLock(handle);
|
|
17587
17614
|
}
|
|
17588
17615
|
} finally {
|
|
17589
17616
|
release();
|
|
@@ -17623,11 +17650,7 @@ async function releaseAsyncProcessLock(handle) {
|
|
|
17623
17650
|
try {
|
|
17624
17651
|
await handle.descriptor.close();
|
|
17625
17652
|
} finally {
|
|
17626
|
-
|
|
17627
|
-
const metadata = JSON.parse(await import_promises2.default.readFile(handle.lockPath, "utf8"));
|
|
17628
|
-
if (metadata.ownerId === handle.ownerId) await import_promises2.default.unlink(handle.lockPath);
|
|
17629
|
-
} catch {
|
|
17630
|
-
}
|
|
17653
|
+
await removeOwnedProcessLock(handle.lockPath, handle.ownerId);
|
|
17631
17654
|
}
|
|
17632
17655
|
}
|
|
17633
17656
|
async function withAsyncFileLock(filePath, operation) {
|
|
@@ -17658,11 +17681,59 @@ function ensureParentDirectory(filePath) {
|
|
|
17658
17681
|
function atomicReplace(filePath, content) {
|
|
17659
17682
|
ensureParentDirectory(filePath);
|
|
17660
17683
|
const temporaryPath = `${filePath}.${process.pid}.${(0, import_node_crypto3.randomUUID)()}.tmp`;
|
|
17684
|
+
let phase = "temporary_write";
|
|
17685
|
+
let failure;
|
|
17661
17686
|
try {
|
|
17662
17687
|
import_node_fs5.default.writeFileSync(temporaryPath, content, { encoding: "utf8", flag: "wx" });
|
|
17688
|
+
phase = "rename";
|
|
17663
17689
|
import_node_fs5.default.renameSync(temporaryPath, filePath);
|
|
17690
|
+
} catch (error) {
|
|
17691
|
+
failure = error;
|
|
17692
|
+
rememberFileFailure(error, { phase });
|
|
17693
|
+
throw error;
|
|
17664
17694
|
} finally {
|
|
17665
|
-
|
|
17695
|
+
try {
|
|
17696
|
+
if (import_node_fs5.default.existsSync(temporaryPath)) import_node_fs5.default.unlinkSync(temporaryPath);
|
|
17697
|
+
} catch (error) {
|
|
17698
|
+
if (failure) rememberFileFailure(failure, { ...getFileOperationDiagnostic(failure), cleanupFailed: true });
|
|
17699
|
+
else {
|
|
17700
|
+
rememberFileFailure(error, { phase: "cleanup" });
|
|
17701
|
+
throw error;
|
|
17702
|
+
}
|
|
17703
|
+
}
|
|
17704
|
+
}
|
|
17705
|
+
}
|
|
17706
|
+
async function replaceSessionFile(filePath, content) {
|
|
17707
|
+
if (process.platform !== "win32") return atomicReplace(filePath, content);
|
|
17708
|
+
ensureParentDirectory(filePath);
|
|
17709
|
+
const temporaryPath = `${filePath}.${process.pid}.${(0, import_node_crypto3.randomUUID)()}.tmp`;
|
|
17710
|
+
const delays = [20, 40, 80, 160];
|
|
17711
|
+
let attempts = 0;
|
|
17712
|
+
const started = performance.now();
|
|
17713
|
+
try {
|
|
17714
|
+
await import_promises2.default.writeFile(temporaryPath, content, { encoding: "utf8", flag: "wx" });
|
|
17715
|
+
for (; ; ) {
|
|
17716
|
+
attempts++;
|
|
17717
|
+
try {
|
|
17718
|
+
await import_promises2.default.rename(temporaryPath, filePath);
|
|
17719
|
+
return;
|
|
17720
|
+
} catch (error) {
|
|
17721
|
+
const delay = delays[attempts - 1];
|
|
17722
|
+
if (!delay || !["EBUSY", "EPERM", "EACCES"].includes(error.code ?? "")) throw error;
|
|
17723
|
+
await new Promise(function backoff(resolve) {
|
|
17724
|
+
setTimeout(resolve, delay);
|
|
17725
|
+
});
|
|
17726
|
+
}
|
|
17727
|
+
}
|
|
17728
|
+
} catch (error) {
|
|
17729
|
+
let cleanupFailed = false;
|
|
17730
|
+
try {
|
|
17731
|
+
await import_promises2.default.rm(temporaryPath, { force: true });
|
|
17732
|
+
} catch {
|
|
17733
|
+
cleanupFailed = true;
|
|
17734
|
+
}
|
|
17735
|
+
rememberFileFailure(error, { phase: attempts ? "rename" : "temporary_write", attempts, elapsedMs: Math.round(performance.now() - started), cleanupFailed });
|
|
17736
|
+
throw error;
|
|
17666
17737
|
}
|
|
17667
17738
|
}
|
|
17668
17739
|
function safeFilePath(directory, key2, extension) {
|
|
@@ -17738,22 +17809,37 @@ async function withNodeFileMutationLocks(canonicalTargets, operation) {
|
|
|
17738
17809
|
}
|
|
17739
17810
|
|
|
17740
17811
|
// src/node/state-root.ts
|
|
17741
|
-
var
|
|
17742
|
-
var
|
|
17812
|
+
var import_node_fs8 = __toESM(require("node:fs"));
|
|
17813
|
+
var import_node_crypto7 = require("node:crypto");
|
|
17743
17814
|
var import_node_os3 = __toESM(require("node:os"));
|
|
17744
|
-
var
|
|
17815
|
+
var import_node_path8 = __toESM(require("node:path"));
|
|
17745
17816
|
|
|
17746
17817
|
// src/node/state-schema-manager.ts
|
|
17747
17818
|
var import_node_fs6 = __toESM(require("node:fs"));
|
|
17748
17819
|
var import_node_path6 = __toESM(require("node:path"));
|
|
17749
17820
|
var import_node_crypto5 = require("node:crypto");
|
|
17821
|
+
function hasExitedLockOwner(file) {
|
|
17822
|
+
try {
|
|
17823
|
+
const metadata = JSON.parse(import_node_fs6.default.readFileSync(file, "utf8"));
|
|
17824
|
+
if (!Number.isSafeInteger(metadata?.pid) || metadata.pid <= 0) return false;
|
|
17825
|
+
try {
|
|
17826
|
+
process.kill(metadata.pid, 0);
|
|
17827
|
+
} catch (error) {
|
|
17828
|
+
return error.code === "ESRCH";
|
|
17829
|
+
}
|
|
17830
|
+
return false;
|
|
17831
|
+
} catch {
|
|
17832
|
+
return false;
|
|
17833
|
+
}
|
|
17834
|
+
}
|
|
17750
17835
|
function assertPlainStateTree(root) {
|
|
17751
17836
|
const entry = import_node_fs6.default.lstatSync(root);
|
|
17752
17837
|
if (entry.isSymbolicLink() || !entry.isDirectory() && !entry.isFile()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17753
17838
|
if (!entry.isDirectory()) return;
|
|
17754
17839
|
for (const name of import_node_fs6.default.readdirSync(root)) {
|
|
17755
|
-
|
|
17756
|
-
assertPlainStateTree(
|
|
17840
|
+
const child = import_node_path6.default.join(root, name);
|
|
17841
|
+
assertPlainStateTree(child);
|
|
17842
|
+
if (name.endsWith(".lock") && !hasExitedLockOwner(child)) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17757
17843
|
}
|
|
17758
17844
|
}
|
|
17759
17845
|
function acquireSchemaLock(root) {
|
|
@@ -17816,6 +17902,14 @@ function createBackupPath(root, fromVersion, toVersion) {
|
|
|
17816
17902
|
function backupStateRoot(root, fromVersion, toVersion) {
|
|
17817
17903
|
if (!hasDurableState(root)) return void 0;
|
|
17818
17904
|
assertPlainStateTree(root);
|
|
17905
|
+
const leases = import_node_path6.default.join(root, "leases");
|
|
17906
|
+
if (import_node_fs6.default.existsSync(leases)) {
|
|
17907
|
+
for (const file of import_node_fs6.default.readdirSync(leases)) {
|
|
17908
|
+
if (!file.endsWith(".json")) continue;
|
|
17909
|
+
const record = JSON.parse(import_node_fs6.default.readFileSync(import_node_path6.default.join(leases, file), "utf8"));
|
|
17910
|
+
if (Number.isFinite(record?.lease?.heartbeatAt) && Date.now() - record.lease.heartbeatAt <= 45e3) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17911
|
+
}
|
|
17912
|
+
}
|
|
17819
17913
|
const backupPath = createBackupPath(root, fromVersion, toVersion);
|
|
17820
17914
|
const backupRoot = import_node_path6.default.dirname(backupPath);
|
|
17821
17915
|
if (import_node_fs6.default.existsSync(backupRoot) && import_node_fs6.default.lstatSync(backupRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
@@ -17901,6 +17995,11 @@ function createNodeStateSchemaManager(options) {
|
|
|
17901
17995
|
if (!Number.isInteger(fromVersion) || !Number.isInteger(toVersion)) {
|
|
17902
17996
|
throw new NodeStateError("STATE_SCHEMA_VERSION_INVALID");
|
|
17903
17997
|
}
|
|
17998
|
+
for (let version = fromVersion; version < toVersion; version++) {
|
|
17999
|
+
if (!options.migrations.some(function adjacent(step) {
|
|
18000
|
+
return step.fromVersion === version && step.toVersion === version + 1;
|
|
18001
|
+
})) throw new NodeStateError("STATE_SCHEMA_MIGRATION_MISSING");
|
|
18002
|
+
}
|
|
17904
18003
|
const backupPath = backup(fromVersion, toVersion);
|
|
17905
18004
|
try {
|
|
17906
18005
|
if (import_node_fs6.default.existsSync(root)) import_node_fs6.default.cpSync(root, stagingRoot, { recursive: true, errorOnExist: true });
|
|
@@ -17951,7 +18050,14 @@ function normalizeNodeSession(value, id) {
|
|
|
17951
18050
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
17952
18051
|
const session = value;
|
|
17953
18052
|
if (session.id !== id || !Number.isFinite(session.createdAt) || !Number.isFinite(session.updatedAt)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
17954
|
-
const
|
|
18053
|
+
const source = session.creationSource;
|
|
18054
|
+
const managed = session.managedExecution;
|
|
18055
|
+
if (managed !== void 0 && (!managed || managed.threadPolicy !== "disabled" || typeof managed.hostId !== "string" || !/^[\w-]{1,128}$/.test(managed.hostId) || typeof managed.requestId !== "string" || !/^[\w-]{1,128}$/.test(managed.requestId) || session.productMode !== "work" || session.persistenceMode !== "durable")) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18056
|
+
if (source !== void 0) {
|
|
18057
|
+
const actor = source?.actor;
|
|
18058
|
+
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");
|
|
18059
|
+
}
|
|
18060
|
+
const mode = session.productMode;
|
|
17955
18061
|
if (mode === "chat") {
|
|
17956
18062
|
if (session.projectId !== void 0 || !["none", "web", "rag"].includes(session.chatRetrievalMode ?? "")) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17957
18063
|
} else if (mode !== "work" || session.chatRetrievalMode !== void 0 || typeof session.projectId !== "string" || !session.projectId.trim()) {
|
|
@@ -17960,13 +18066,63 @@ function normalizeNodeSession(value, id) {
|
|
|
17960
18066
|
return { ...session, productMode: mode };
|
|
17961
18067
|
}
|
|
17962
18068
|
function assertNodeSessionIdentity(previous, next) {
|
|
18069
|
+
if (JSON.stringify(previous.managedExecution) !== JSON.stringify(next.managedExecution)) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
18070
|
+
if (JSON.stringify(previous.collaborationAllowedTools) !== JSON.stringify(next.collaborationAllowedTools)) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
18071
|
+
if (JSON.stringify(previous.creationSource) !== JSON.stringify(next.creationSource)) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
18072
|
+
if (previous.collaborationCreationId !== next.collaborationCreationId) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17963
18073
|
if (previous.workContextVersion !== next.workContextVersion) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17964
18074
|
if (previous.productMode !== next.productMode || previous.projectId !== next.projectId) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17965
18075
|
if (previous.chatRetrievalMode !== next.chatRetrievalMode) throw createNodeIdentityError("CHAT_RETRIEVAL_MODE_LOCKED");
|
|
17966
18076
|
}
|
|
17967
18077
|
|
|
18078
|
+
// src/node/state-upgrade.ts
|
|
18079
|
+
var import_node_fs7 = __toESM(require("node:fs"));
|
|
18080
|
+
var import_node_path7 = __toESM(require("node:path"));
|
|
18081
|
+
var import_node_crypto6 = require("node:crypto");
|
|
18082
|
+
function upgradeSessionIdentity(root, allowLegacyWork) {
|
|
18083
|
+
const directory = import_node_path7.default.join(root, "sessions");
|
|
18084
|
+
if (!import_node_fs7.default.existsSync(directory)) return;
|
|
18085
|
+
for (const file of import_node_fs7.default.readdirSync(directory)) {
|
|
18086
|
+
if (!file.endsWith(".json")) continue;
|
|
18087
|
+
const target = import_node_path7.default.join(directory, file);
|
|
18088
|
+
let value;
|
|
18089
|
+
try {
|
|
18090
|
+
value = JSON.parse(import_node_fs7.default.readFileSync(target, "utf8"));
|
|
18091
|
+
} catch {
|
|
18092
|
+
throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18093
|
+
}
|
|
18094
|
+
const missingMode = value && typeof value === "object" && value.productMode === void 0;
|
|
18095
|
+
if (missingMode && allowLegacyWork) value.productMode = "work";
|
|
18096
|
+
const session = normalizeNodeSession(value, file.slice(0, -5));
|
|
18097
|
+
if (missingMode && allowLegacyWork) import_node_fs7.default.writeFileSync(target, JSON.stringify(session, null, 2), "utf8");
|
|
18098
|
+
}
|
|
18099
|
+
}
|
|
18100
|
+
function upgradeThreadCreationSources(root) {
|
|
18101
|
+
upgradeSessionIdentity(root, false);
|
|
18102
|
+
const groups = import_node_path7.default.join(root, "threads", "groups");
|
|
18103
|
+
if (!import_node_fs7.default.existsSync(groups)) return;
|
|
18104
|
+
for (const groupId of import_node_fs7.default.readdirSync(groups)) {
|
|
18105
|
+
const file = import_node_path7.default.join(groups, groupId, "control.json");
|
|
18106
|
+
if (!import_node_fs7.default.existsSync(file)) continue;
|
|
18107
|
+
const control = JSON.parse(import_node_fs7.default.readFileSync(file, "utf8"));
|
|
18108
|
+
if (control.group?.groupId !== groupId || !Array.isArray(control.creates)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18109
|
+
for (const intent of control.creates) {
|
|
18110
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(intent.threadId)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18111
|
+
const target = import_node_path7.default.join(root, "sessions", `${intent.threadId}.json`);
|
|
18112
|
+
if (!import_node_fs7.default.existsSync(target)) continue;
|
|
18113
|
+
const session = normalizeNodeSession(JSON.parse(import_node_fs7.default.readFileSync(target, "utf8")), intent.threadId);
|
|
18114
|
+
const creationId = (0, import_node_crypto6.createHash)("sha256").update(JSON.stringify([groupId, intent.actorKey, intent.requestId])).digest("hex");
|
|
18115
|
+
if (session.collaborationCreationId !== creationId || session.projectId !== control.group.projectId) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18116
|
+
const source = { actor: intent.from, requestId: intent.requestId };
|
|
18117
|
+
const next = normalizeNodeSession({ ...session, creationSource: source }, session.id);
|
|
18118
|
+
if (session.creationSource !== void 0 && JSON.stringify(session.creationSource) !== JSON.stringify(source)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18119
|
+
if (session.creationSource === void 0) import_node_fs7.default.writeFileSync(target, JSON.stringify(next, null, 2), "utf8");
|
|
18120
|
+
}
|
|
18121
|
+
}
|
|
18122
|
+
}
|
|
18123
|
+
|
|
17968
18124
|
// src/node/state-root.ts
|
|
17969
|
-
var NODE_STATE_SCHEMA_VERSION =
|
|
18125
|
+
var NODE_STATE_SCHEMA_VERSION = 8;
|
|
17970
18126
|
var NODE_WORKSPACE_ID_VERSION = 1;
|
|
17971
18127
|
var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
17972
18128
|
fromVersion: 0,
|
|
@@ -17977,47 +18133,47 @@ var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
|
17977
18133
|
fromVersion: 1,
|
|
17978
18134
|
toVersion: 2,
|
|
17979
18135
|
migrate(stagingRoot) {
|
|
17980
|
-
|
|
18136
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "jobs"), { recursive: true });
|
|
17981
18137
|
}
|
|
17982
18138
|
}, {
|
|
17983
18139
|
fromVersion: 2,
|
|
17984
18140
|
toVersion: 3,
|
|
17985
18141
|
migrate(stagingRoot) {
|
|
17986
|
-
|
|
17987
|
-
|
|
17988
|
-
|
|
17989
|
-
|
|
18142
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "mutations"), { recursive: true });
|
|
18143
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "mutation-blobs"), { recursive: true });
|
|
18144
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "mutation-locks"), { recursive: true });
|
|
18145
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "undo-transactions"), { recursive: true });
|
|
17990
18146
|
}
|
|
17991
18147
|
}, {
|
|
17992
18148
|
fromVersion: 3,
|
|
17993
18149
|
toVersion: 4,
|
|
17994
18150
|
migrate(stagingRoot) {
|
|
17995
|
-
|
|
18151
|
+
import_node_fs8.default.mkdirSync(import_node_path8.default.join(stagingRoot, "questions"), { recursive: true });
|
|
17996
18152
|
}
|
|
17997
18153
|
}, {
|
|
17998
18154
|
fromVersion: 4,
|
|
17999
18155
|
toVersion: 5,
|
|
18000
18156
|
/** 仅在迁移副本补写产品身份;缺失归属只能采用唯一已有 Project,不能猜工作区。 */
|
|
18001
18157
|
migrate(stagingRoot) {
|
|
18002
|
-
const sessions =
|
|
18003
|
-
if (!
|
|
18004
|
-
const projects =
|
|
18005
|
-
const candidates =
|
|
18158
|
+
const sessions = import_node_path8.default.join(stagingRoot, "sessions");
|
|
18159
|
+
if (!import_node_fs8.default.existsSync(sessions)) return;
|
|
18160
|
+
const projects = import_node_path8.default.join(stagingRoot, "projects");
|
|
18161
|
+
const candidates = import_node_fs8.default.existsSync(projects) ? import_node_fs8.default.readdirSync(projects).filter(
|
|
18006
18162
|
/** 只检查现有 Project 记录,不创建新的工作区身份。 */
|
|
18007
18163
|
function projectFile(file) {
|
|
18008
18164
|
return file.endsWith(".json");
|
|
18009
18165
|
}
|
|
18010
18166
|
) : [];
|
|
18011
|
-
for (const file of
|
|
18167
|
+
for (const file of import_node_fs8.default.readdirSync(sessions)) {
|
|
18012
18168
|
if (!file.endsWith(".json")) continue;
|
|
18013
|
-
const target =
|
|
18014
|
-
const value = JSON.parse(
|
|
18169
|
+
const target = import_node_path8.default.join(sessions, file);
|
|
18170
|
+
const value = JSON.parse(import_node_fs8.default.readFileSync(target, "utf8"));
|
|
18015
18171
|
if (value && value.productMode === void 0 && value.projectId === void 0 && candidates.length === 1) {
|
|
18016
|
-
const project = JSON.parse(
|
|
18172
|
+
const project = JSON.parse(import_node_fs8.default.readFileSync(import_node_path8.default.join(projects, candidates[0]), "utf8"));
|
|
18017
18173
|
if (project.id === candidates[0].slice(0, -5) && typeof project.workspaceRoot === "string" && project.workspaceRoot) value.projectId = project.id;
|
|
18018
18174
|
}
|
|
18019
18175
|
const session = normalizeNodeSession(value, file.slice(0, -5));
|
|
18020
|
-
|
|
18176
|
+
import_node_fs8.default.writeFileSync(target, JSON.stringify(session, null, 2), "utf8");
|
|
18021
18177
|
}
|
|
18022
18178
|
}
|
|
18023
18179
|
}, {
|
|
@@ -18025,70 +18181,87 @@ var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
|
18025
18181
|
toVersion: 6,
|
|
18026
18182
|
migrate() {
|
|
18027
18183
|
}
|
|
18184
|
+
}, {
|
|
18185
|
+
fromVersion: 6,
|
|
18186
|
+
toVersion: 7,
|
|
18187
|
+
/** v7 严格校验产品身份;旧 Work 缺省值在副本中显式落盘。 */
|
|
18188
|
+
migrate(stagingRoot) {
|
|
18189
|
+
upgradeSessionIdentity(stagingRoot, true);
|
|
18190
|
+
}
|
|
18191
|
+
}, {
|
|
18192
|
+
fromVersion: 7,
|
|
18193
|
+
toVersion: 8,
|
|
18194
|
+
/** 新来源只从已有持久意图恢复;旧进展仍保留为无任务归属的会话进展。 */
|
|
18195
|
+
migrate(stagingRoot) {
|
|
18196
|
+
upgradeThreadCreationSources(stagingRoot);
|
|
18197
|
+
}
|
|
18028
18198
|
}];
|
|
18029
18199
|
function canonicalizeNodePath(candidate, baseDirectory = process.cwd()) {
|
|
18030
|
-
const resolved =
|
|
18200
|
+
const resolved = import_node_path8.default.resolve(baseDirectory, candidate);
|
|
18031
18201
|
try {
|
|
18032
|
-
return
|
|
18202
|
+
return import_node_fs8.default.realpathSync.native(resolved);
|
|
18033
18203
|
} catch {
|
|
18034
18204
|
return resolved;
|
|
18035
18205
|
}
|
|
18036
18206
|
}
|
|
18037
18207
|
function createNodeWorkspaceId(workspaceRoot, baseDirectory) {
|
|
18038
18208
|
const canonicalRoot = canonicalizeNodePath(workspaceRoot, baseDirectory);
|
|
18039
|
-
const digest2 = (0,
|
|
18209
|
+
const digest2 = (0, import_node_crypto7.createHash)("sha256").update(canonicalRoot).digest("hex").slice(0, 24);
|
|
18040
18210
|
return `v${NODE_WORKSPACE_ID_VERSION}-${digest2}`;
|
|
18041
18211
|
}
|
|
18042
18212
|
function resolveNodeGlobalStateRoot(options = {}) {
|
|
18043
18213
|
const baseDirectory = options.cwd ?? process.cwd();
|
|
18044
|
-
const defaultRoot = process.env.LOCALAPPDATA ?
|
|
18214
|
+
const defaultRoot = process.env.LOCALAPPDATA ? import_node_path8.default.join(process.env.LOCALAPPDATA, "autopilot-agent") : import_node_path8.default.join(import_node_os3.default.homedir(), ".autopilot-agent");
|
|
18045
18215
|
return canonicalizeNodePath(options.globalStateRoot ?? defaultRoot, baseDirectory);
|
|
18046
18216
|
}
|
|
18047
18217
|
function resolveNodeStateRoot(options = {}) {
|
|
18048
18218
|
const baseDirectory = options.cwd ?? process.cwd();
|
|
18049
18219
|
if (options.stateRoot) return canonicalizeNodePath(options.stateRoot, baseDirectory);
|
|
18050
18220
|
const workspaceRoot = options.workspaceRoot ?? baseDirectory;
|
|
18051
|
-
return
|
|
18221
|
+
return import_node_path8.default.join(resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: baseDirectory }), "workspaces", createNodeWorkspaceId(workspaceRoot, baseDirectory));
|
|
18052
18222
|
}
|
|
18053
18223
|
function resolveNodeTrustRoot(options) {
|
|
18054
18224
|
const stateRoot = canonicalizeNodePath(options.stateRoot);
|
|
18055
|
-
return canonicalizeNodePath(options.trustRoot ??
|
|
18225
|
+
return canonicalizeNodePath(options.trustRoot ?? import_node_path8.default.resolve(stateRoot, "..", "agent"));
|
|
18056
18226
|
}
|
|
18057
18227
|
function getNodeStatePaths(stateRoot) {
|
|
18058
18228
|
const root = canonicalizeNodePath(stateRoot);
|
|
18059
18229
|
return {
|
|
18060
18230
|
root,
|
|
18061
|
-
schemaFile:
|
|
18062
|
-
sessionsDir:
|
|
18063
|
-
checkpointsDir:
|
|
18064
|
-
transcriptsDir:
|
|
18065
|
-
projectsDir:
|
|
18066
|
-
turnsDir:
|
|
18067
|
-
approvalsDir:
|
|
18068
|
-
inboxDir:
|
|
18069
|
-
leasesDir:
|
|
18070
|
-
jobsDir:
|
|
18071
|
-
mutationsDir:
|
|
18072
|
-
mutationBlobsDir:
|
|
18073
|
-
mutationLocksDir:
|
|
18074
|
-
undoTransactionsDir:
|
|
18075
|
-
questionsDir:
|
|
18231
|
+
schemaFile: import_node_path8.default.join(root, "schema.json"),
|
|
18232
|
+
sessionsDir: import_node_path8.default.join(root, "sessions"),
|
|
18233
|
+
checkpointsDir: import_node_path8.default.join(root, "checkpoints"),
|
|
18234
|
+
transcriptsDir: import_node_path8.default.join(root, "transcripts"),
|
|
18235
|
+
projectsDir: import_node_path8.default.join(root, "projects"),
|
|
18236
|
+
turnsDir: import_node_path8.default.join(root, "turns"),
|
|
18237
|
+
approvalsDir: import_node_path8.default.join(root, "approvals"),
|
|
18238
|
+
inboxDir: import_node_path8.default.join(root, "inbox"),
|
|
18239
|
+
leasesDir: import_node_path8.default.join(root, "leases"),
|
|
18240
|
+
jobsDir: import_node_path8.default.join(root, "jobs"),
|
|
18241
|
+
mutationsDir: import_node_path8.default.join(root, "mutations"),
|
|
18242
|
+
mutationBlobsDir: import_node_path8.default.join(root, "mutation-blobs"),
|
|
18243
|
+
mutationLocksDir: import_node_path8.default.join(root, "mutation-locks"),
|
|
18244
|
+
undoTransactionsDir: import_node_path8.default.join(root, "undo-transactions"),
|
|
18245
|
+
questionsDir: import_node_path8.default.join(root, "questions")
|
|
18076
18246
|
};
|
|
18077
18247
|
}
|
|
18078
18248
|
function assertNodeStateSchema(stateRoot) {
|
|
18079
18249
|
const paths = getNodeStatePaths(stateRoot);
|
|
18080
|
-
if (!
|
|
18081
|
-
createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations:
|
|
18250
|
+
if (!import_node_fs8.default.existsSync(paths.schemaFile)) throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
18251
|
+
createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: [] }).verify();
|
|
18082
18252
|
}
|
|
18083
18253
|
function ensureNodeStateRoot(stateRoot) {
|
|
18084
18254
|
return initializeNodeStateRoot(stateRoot);
|
|
18085
18255
|
}
|
|
18086
18256
|
function initializeNodeStateRoot(stateRoot) {
|
|
18087
18257
|
try {
|
|
18088
|
-
if (
|
|
18258
|
+
if (import_node_fs8.default.existsSync(stateRoot) && import_node_fs8.default.lstatSync(stateRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
18089
18259
|
const paths = getNodeStatePaths(stateRoot);
|
|
18260
|
+
const recovering = import_node_fs8.default.existsSync(`${paths.root}.schema-original`);
|
|
18261
|
+
if (!recovering && !import_node_fs8.default.existsSync(paths.schemaFile) && import_node_fs8.default.existsSync(paths.root) && import_node_fs8.default.readdirSync(paths.root).length !== 0) throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
18090
18262
|
const manager = createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS });
|
|
18091
18263
|
manager.migrate();
|
|
18264
|
+
assertNodeStateSchema(paths.root);
|
|
18092
18265
|
return paths;
|
|
18093
18266
|
} catch (error) {
|
|
18094
18267
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
@@ -18103,11 +18276,11 @@ function getNodeStateCorruptionDiagnostics(stateRoot) {
|
|
|
18103
18276
|
const directories = [paths.approvalsDir, paths.checkpointsDir, paths.inboxDir, paths.transcriptsDir, paths.questionsDir];
|
|
18104
18277
|
const diagnostics = [];
|
|
18105
18278
|
for (const directory of directories) {
|
|
18106
|
-
if (!
|
|
18107
|
-
for (const entry of
|
|
18108
|
-
const filePath =
|
|
18279
|
+
if (!import_node_fs8.default.existsSync(directory)) continue;
|
|
18280
|
+
for (const entry of import_node_fs8.default.readdirSync(directory).filter((file) => file.endsWith(".jsonl"))) {
|
|
18281
|
+
const filePath = import_node_path8.default.join(directory, entry);
|
|
18109
18282
|
const result = readJsonLines(filePath);
|
|
18110
|
-
for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file:
|
|
18283
|
+
for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file: import_node_path8.default.relative(paths.root, filePath) });
|
|
18111
18284
|
}
|
|
18112
18285
|
}
|
|
18113
18286
|
return diagnostics;
|
|
@@ -18160,9 +18333,9 @@ function createNodeSandboxPort(options) {
|
|
|
18160
18333
|
return result;
|
|
18161
18334
|
}
|
|
18162
18335
|
function protectAuthority(policy) {
|
|
18163
|
-
const settingsRoot =
|
|
18336
|
+
const settingsRoot = import_node_path9.default.join(options.workspaceRoot, ".autopilot");
|
|
18164
18337
|
const writes = [getNodeFileMutationLockRoot(), ...["settings.json", "settings.local.json", "mcp.json"].map(function settingsPath(file) {
|
|
18165
|
-
return
|
|
18338
|
+
return import_node_path9.default.join(settingsRoot, file);
|
|
18166
18339
|
})];
|
|
18167
18340
|
const state = options.stateRoot ? [options.stateRoot, canonicalizeNodePath(options.stateRoot)] : [];
|
|
18168
18341
|
return { ...policy, deniedRead: [.../* @__PURE__ */ new Set([...policy.deniedRead, ...state])], deniedWrite: [.../* @__PURE__ */ new Set([...policy.deniedWrite, ...state, ...writes, ...writes.map(function canonical(candidate) {
|
|
@@ -18357,20 +18530,20 @@ function describePlatform() {
|
|
|
18357
18530
|
}
|
|
18358
18531
|
|
|
18359
18532
|
// src/node/workspace-adapter.ts
|
|
18360
|
-
var
|
|
18361
|
-
var
|
|
18533
|
+
var import_node_fs9 = __toESM(require("node:fs"));
|
|
18534
|
+
var import_node_path10 = __toESM(require("node:path"));
|
|
18362
18535
|
function findWorkspaceRoot(startDirectory) {
|
|
18363
18536
|
let current = canonicalizeNodePath(startDirectory);
|
|
18364
18537
|
while (true) {
|
|
18365
|
-
const manifestPath =
|
|
18366
|
-
if (
|
|
18538
|
+
const manifestPath = import_node_path10.default.join(current, "package.json");
|
|
18539
|
+
if (import_node_fs9.default.existsSync(manifestPath)) {
|
|
18367
18540
|
try {
|
|
18368
|
-
const manifest = JSON.parse(
|
|
18541
|
+
const manifest = JSON.parse(import_node_fs9.default.readFileSync(manifestPath, "utf8"));
|
|
18369
18542
|
if (manifest.workspaces) return canonicalizeNodePath(current);
|
|
18370
18543
|
} catch {
|
|
18371
18544
|
}
|
|
18372
18545
|
}
|
|
18373
|
-
const parent =
|
|
18546
|
+
const parent = import_node_path10.default.dirname(current);
|
|
18374
18547
|
if (parent === current) throw new Error("\u65E0\u6CD5\u5B9A\u4F4D Agent \u5DE5\u4F5C\u533A\uFF1B\u8BF7\u8BBE\u7F6E AGENT_WORKSPACE_ROOT");
|
|
18375
18548
|
current = parent;
|
|
18376
18549
|
}
|
|
@@ -18389,20 +18562,20 @@ function createNodeWorkspaceAdapter(options = {}) {
|
|
|
18389
18562
|
const root = canonicalizeWorkspaceRoot(workspaceRoot);
|
|
18390
18563
|
const markers = [];
|
|
18391
18564
|
for (const marker of ["AGENTS.md", ".autopilot", ".claude"]) {
|
|
18392
|
-
if (
|
|
18565
|
+
if (import_node_fs9.default.existsSync(import_node_path10.default.join(root, marker))) markers.push(marker);
|
|
18393
18566
|
}
|
|
18394
18567
|
return {
|
|
18395
18568
|
root,
|
|
18396
18569
|
hasTrustMarker: markers.length > 0,
|
|
18397
18570
|
trustMarkers: markers,
|
|
18398
|
-
displayName:
|
|
18571
|
+
displayName: import_node_path10.default.basename(root)
|
|
18399
18572
|
};
|
|
18400
18573
|
}
|
|
18401
18574
|
return { resolveWorkspaceRoot, canonicalizeWorkspaceRoot, getWorkspaceInfo };
|
|
18402
18575
|
}
|
|
18403
18576
|
|
|
18404
18577
|
// src/node/stores/node-approval-store.ts
|
|
18405
|
-
var
|
|
18578
|
+
var import_node_fs10 = __toESM(require("node:fs"));
|
|
18406
18579
|
var import_core10 = require("@autopilot-agent/core");
|
|
18407
18580
|
function createNodeApprovalStore(options) {
|
|
18408
18581
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
@@ -18410,7 +18583,7 @@ function createNodeApprovalStore(options) {
|
|
|
18410
18583
|
const grantsFile = `${paths.approvalsDir}/grants.jsonl`;
|
|
18411
18584
|
function ensureDir() {
|
|
18412
18585
|
const state = ensureNodeStateRoot(paths.root);
|
|
18413
|
-
|
|
18586
|
+
import_node_fs10.default.mkdirSync(state.approvalsDir, { recursive: true });
|
|
18414
18587
|
}
|
|
18415
18588
|
return {
|
|
18416
18589
|
/** 待审批私有身份复用 decisions.jsonl;记录类型不与真实 decision 混淆。 */
|
|
@@ -18657,15 +18830,15 @@ function createNodeApprovalStore(options) {
|
|
|
18657
18830
|
}
|
|
18658
18831
|
|
|
18659
18832
|
// src/node/settings/node-external-permission-projector.ts
|
|
18660
|
-
var
|
|
18833
|
+
var import_node_fs13 = __toESM(require("node:fs"));
|
|
18661
18834
|
var import_node_os6 = __toESM(require("node:os"));
|
|
18662
18835
|
var import_core12 = require("@autopilot-agent/core");
|
|
18663
18836
|
var import_core13 = require("@autopilot-agent/core");
|
|
18664
18837
|
|
|
18665
18838
|
// src/node/settings/user-config-directory.ts
|
|
18666
|
-
var
|
|
18839
|
+
var import_node_fs11 = __toESM(require("node:fs"));
|
|
18667
18840
|
var import_node_os4 = __toESM(require("node:os"));
|
|
18668
|
-
var
|
|
18841
|
+
var import_node_path11 = __toESM(require("node:path"));
|
|
18669
18842
|
var UserConfigDirectoryError = class extends Error {
|
|
18670
18843
|
constructor(code) {
|
|
18671
18844
|
super(code);
|
|
@@ -18682,20 +18855,20 @@ function resolveUserHome(homeDirectory) {
|
|
|
18682
18855
|
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18683
18856
|
}
|
|
18684
18857
|
}
|
|
18685
|
-
if (!candidate || !
|
|
18686
|
-
return
|
|
18858
|
+
if (!candidate || !import_node_path11.default.isAbsolute(candidate)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18859
|
+
return import_node_path11.default.resolve(candidate);
|
|
18687
18860
|
}
|
|
18688
18861
|
function readEntry(entryPath) {
|
|
18689
18862
|
try {
|
|
18690
|
-
return
|
|
18863
|
+
return import_node_fs11.default.lstatSync(entryPath);
|
|
18691
18864
|
} catch (error) {
|
|
18692
18865
|
if (error.code === "ENOENT") return void 0;
|
|
18693
18866
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18694
18867
|
}
|
|
18695
18868
|
}
|
|
18696
18869
|
function isWithinHome(homeDirectory, configDirectory) {
|
|
18697
|
-
const relative =
|
|
18698
|
-
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${
|
|
18870
|
+
const relative = import_node_path11.default.relative(homeDirectory, configDirectory);
|
|
18871
|
+
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${import_node_path11.default.sep}`) && !import_node_path11.default.isAbsolute(relative);
|
|
18699
18872
|
}
|
|
18700
18873
|
function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
18701
18874
|
const entry = readEntry(configDirectory);
|
|
@@ -18703,8 +18876,8 @@ function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
|
18703
18876
|
if (entry.isSymbolicLink()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
18704
18877
|
if (!entry.isDirectory()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_NOT_DIRECTORY");
|
|
18705
18878
|
try {
|
|
18706
|
-
const canonicalHome =
|
|
18707
|
-
const canonicalConfigDirectory =
|
|
18879
|
+
const canonicalHome = import_node_fs11.default.realpathSync.native(homeDirectory);
|
|
18880
|
+
const canonicalConfigDirectory = import_node_fs11.default.realpathSync.native(configDirectory);
|
|
18708
18881
|
if (!isWithinHome(canonicalHome, canonicalConfigDirectory)) {
|
|
18709
18882
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
18710
18883
|
}
|
|
@@ -18715,12 +18888,12 @@ function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
|
18715
18888
|
}
|
|
18716
18889
|
function ensureUserConfigDirectory(options = {}) {
|
|
18717
18890
|
const homeDirectory = resolveUserHome(options.homeDirectory);
|
|
18718
|
-
const configDirectory =
|
|
18891
|
+
const configDirectory = import_node_path11.default.join(homeDirectory, ".autopilot");
|
|
18719
18892
|
const existing = readEntry(configDirectory);
|
|
18720
18893
|
if (existing) assertSafeConfigDirectory(homeDirectory, configDirectory);
|
|
18721
18894
|
else {
|
|
18722
18895
|
try {
|
|
18723
|
-
|
|
18896
|
+
import_node_fs11.default.mkdirSync(configDirectory, { recursive: true, mode: 448 });
|
|
18724
18897
|
} catch {
|
|
18725
18898
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18726
18899
|
}
|
|
@@ -18730,11 +18903,11 @@ function ensureUserConfigDirectory(options = {}) {
|
|
|
18730
18903
|
}
|
|
18731
18904
|
|
|
18732
18905
|
// src/node/settings/node-settings-loader.ts
|
|
18733
|
-
var
|
|
18906
|
+
var import_node_fs12 = __toESM(require("node:fs"));
|
|
18734
18907
|
var import_node_os5 = __toESM(require("node:os"));
|
|
18735
|
-
var
|
|
18908
|
+
var import_node_path12 = __toESM(require("node:path"));
|
|
18736
18909
|
var import_core11 = require("@autopilot-agent/core");
|
|
18737
|
-
function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi =
|
|
18910
|
+
function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = import_node_path12.default) {
|
|
18738
18911
|
try {
|
|
18739
18912
|
const home = homeDirectory ?? import_node_os5.default.homedir();
|
|
18740
18913
|
if (!pathApi.isAbsolute(home)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
@@ -18743,7 +18916,7 @@ function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = import_no
|
|
|
18743
18916
|
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18744
18917
|
}
|
|
18745
18918
|
}
|
|
18746
|
-
function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = import_node_os5.default.homedir(), pathApi =
|
|
18919
|
+
function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = import_node_os5.default.homedir(), pathApi = import_node_path12.default) {
|
|
18747
18920
|
const root = pathApi.resolve(workspaceRoot);
|
|
18748
18921
|
return {
|
|
18749
18922
|
user: pathApi.join(homeDirectory, ".autopilot", "settings.json"),
|
|
@@ -18753,14 +18926,14 @@ function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = import_node_os5
|
|
|
18753
18926
|
}
|
|
18754
18927
|
function isSafeSettingsFile(filePath) {
|
|
18755
18928
|
try {
|
|
18756
|
-
const file =
|
|
18757
|
-
const configDirectory =
|
|
18758
|
-
const directory =
|
|
18929
|
+
const file = import_node_fs12.default.lstatSync(filePath);
|
|
18930
|
+
const configDirectory = import_node_path12.default.dirname(filePath);
|
|
18931
|
+
const directory = import_node_fs12.default.lstatSync(configDirectory);
|
|
18759
18932
|
if (!file.isFile() || file.isSymbolicLink() || !directory.isDirectory() || directory.isSymbolicLink()) return false;
|
|
18760
|
-
const canonicalDirectory =
|
|
18761
|
-
const canonicalFile =
|
|
18762
|
-
const relative =
|
|
18763
|
-
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${
|
|
18933
|
+
const canonicalDirectory = import_node_fs12.default.realpathSync.native(configDirectory);
|
|
18934
|
+
const canonicalFile = import_node_fs12.default.realpathSync.native(filePath);
|
|
18935
|
+
const relative = import_node_path12.default.relative(canonicalDirectory, canonicalFile);
|
|
18936
|
+
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${import_node_path12.default.sep}`) && !import_node_path12.default.isAbsolute(relative);
|
|
18764
18937
|
} catch (error) {
|
|
18765
18938
|
return error.code === "ENOENT";
|
|
18766
18939
|
}
|
|
@@ -18768,9 +18941,9 @@ function isSafeSettingsFile(filePath) {
|
|
|
18768
18941
|
function createNodeSettingsLoader(options = {}) {
|
|
18769
18942
|
const debounceMs = options.debounceMs ?? 100;
|
|
18770
18943
|
function readSource(scope, filePath) {
|
|
18771
|
-
if (!
|
|
18944
|
+
if (!import_node_fs12.default.existsSync(filePath)) {
|
|
18772
18945
|
try {
|
|
18773
|
-
if (
|
|
18946
|
+
if (import_node_fs12.default.lstatSync(filePath).isSymbolicLink()) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
18774
18947
|
} catch {
|
|
18775
18948
|
return void 0;
|
|
18776
18949
|
}
|
|
@@ -18778,7 +18951,7 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18778
18951
|
}
|
|
18779
18952
|
if (!isSafeSettingsFile(filePath)) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
18780
18953
|
try {
|
|
18781
|
-
return { scope, value: JSON.parse(
|
|
18954
|
+
return { scope, value: JSON.parse(import_node_fs12.default.readFileSync(filePath, "utf8")), diagnostics: [] };
|
|
18782
18955
|
} catch {
|
|
18783
18956
|
return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_JSON_INVALID" }] };
|
|
18784
18957
|
}
|
|
@@ -18814,18 +18987,18 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18814
18987
|
function installWatchers() {
|
|
18815
18988
|
for (const watcher of watchers) watcher.close();
|
|
18816
18989
|
const uniqueDirectories = [...new Set(watched.flatMap(function collectWatchDirectories(filePath) {
|
|
18817
|
-
const directory =
|
|
18818
|
-
return [directory,
|
|
18990
|
+
const directory = import_node_path12.default.dirname(filePath);
|
|
18991
|
+
return [directory, import_node_path12.default.dirname(directory)];
|
|
18819
18992
|
}))].filter(
|
|
18820
18993
|
/** 不把用户配置目录的链接目标注册为监听面;父目录仍能观察链接被替换。 */
|
|
18821
18994
|
function safeWatchDirectory(directory) {
|
|
18822
|
-
return
|
|
18995
|
+
return import_node_fs12.default.existsSync(directory) && import_node_fs12.default.lstatSync(directory).isDirectory() && !import_node_fs12.default.lstatSync(directory).isSymbolicLink();
|
|
18823
18996
|
}
|
|
18824
18997
|
);
|
|
18825
18998
|
watchers = uniqueDirectories.flatMap(function watchParent(directory) {
|
|
18826
18999
|
try {
|
|
18827
|
-
const watcher =
|
|
18828
|
-
if (!fileName || !watched.some((target) =>
|
|
19000
|
+
const watcher = import_node_fs12.default.watch(directory, function reloadOnTargetFile(_eventType, fileName) {
|
|
19001
|
+
if (!fileName || !watched.some((target) => import_node_path12.default.basename(target) === fileName.toString() || import_node_path12.default.basename(import_node_path12.default.dirname(target)) === fileName.toString())) return;
|
|
18829
19002
|
if (timer) clearTimeout(timer);
|
|
18830
19003
|
timer = setTimeout(function reloadAfterDebounce() {
|
|
18831
19004
|
reload();
|
|
@@ -18854,16 +19027,16 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18854
19027
|
function readScopeValue(filePath, strict = false) {
|
|
18855
19028
|
if (strict) {
|
|
18856
19029
|
try {
|
|
18857
|
-
|
|
19030
|
+
import_node_fs13.default.lstatSync(filePath);
|
|
18858
19031
|
} catch (error) {
|
|
18859
19032
|
if (error.code === "ENOENT") return {};
|
|
18860
19033
|
throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
|
|
18861
19034
|
}
|
|
18862
19035
|
if (!isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
|
|
18863
|
-
} else if (!
|
|
19036
|
+
} else if (!import_node_fs13.default.existsSync(filePath) || !isSafeSettingsFile(filePath)) return {};
|
|
18864
19037
|
let content;
|
|
18865
19038
|
try {
|
|
18866
|
-
content =
|
|
19039
|
+
content = import_node_fs13.default.readFileSync(filePath, "utf8");
|
|
18867
19040
|
} catch {
|
|
18868
19041
|
if (strict) throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
|
|
18869
19042
|
return {};
|
|
@@ -18908,8 +19081,8 @@ function createNodeExternalPermissionProjector(options = {}) {
|
|
|
18908
19081
|
const resolved = (0, import_core12.resolveAutopilotSettings)([{ scope: "local", value: updated }]);
|
|
18909
19082
|
if (resolved.permissions.restricted === true) throw new Error("EXTERNAL_RULE_PERMISSIONS_UNSAFE");
|
|
18910
19083
|
if (next.length === 0 && Object.keys(permissions).length === 1) delete updated.permissions;
|
|
18911
|
-
if (
|
|
18912
|
-
|
|
19084
|
+
if (import_node_fs13.default.existsSync(filePath) && !isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
|
|
19085
|
+
import_node_fs13.default.mkdirSync(resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory ?? import_node_os6.default.homedir()).local.replace(/[/\\]settings\.local\.json$/u, ""), { recursive: true });
|
|
18913
19086
|
atomicReplace(filePath, `${JSON.stringify(updated, null, 2)}
|
|
18914
19087
|
`);
|
|
18915
19088
|
});
|
|
@@ -18928,16 +19101,16 @@ function createNodeExternalPermissionProjector(options = {}) {
|
|
|
18928
19101
|
}
|
|
18929
19102
|
|
|
18930
19103
|
// src/node/host-mutation-protection.ts
|
|
18931
|
-
var
|
|
19104
|
+
var import_node_path13 = __toESM(require("node:path"));
|
|
18932
19105
|
function createNodeHostMutationProtection(options) {
|
|
18933
|
-
const stateRoot =
|
|
18934
|
-
const trustFile =
|
|
19106
|
+
const stateRoot = import_node_path13.default.resolve(options.stateRoot);
|
|
19107
|
+
const trustFile = import_node_path13.default.join(resolveNodeTrustRoot(options), "trust.json");
|
|
18935
19108
|
const fixedTargets = [
|
|
18936
19109
|
{ path: getNodeFileMutationLockRoot(), scope: "directory" },
|
|
18937
19110
|
{ path: stateRoot, scope: "directory" },
|
|
18938
19111
|
{ path: canonicalizeNodePath(stateRoot), scope: "directory" },
|
|
18939
19112
|
{ path: trustFile, scope: "file" },
|
|
18940
|
-
...options.userSettingsPath ? [{ path:
|
|
19113
|
+
...options.userSettingsPath ? [{ path: import_node_path13.default.resolve(options.userSettingsPath), scope: "file" }] : []
|
|
18941
19114
|
];
|
|
18942
19115
|
return {
|
|
18943
19116
|
/** 权限配置路径复用真实User/Project/Local resolver,每次保留原路径与canonical判定。 */
|
|
@@ -18953,47 +19126,120 @@ function createNodeHostMutationProtection(options) {
|
|
|
18953
19126
|
}
|
|
18954
19127
|
|
|
18955
19128
|
// src/node/stores/node-checkpoint-store.ts
|
|
18956
|
-
var
|
|
19129
|
+
var import_node_fs14 = __toESM(require("node:fs"));
|
|
19130
|
+
var import_node_path14 = __toESM(require("node:path"));
|
|
19131
|
+
var import_node_readline = require("node:readline");
|
|
18957
19132
|
function createNodeCheckpointStore(options) {
|
|
18958
19133
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19134
|
+
const latestCache = /* @__PURE__ */ new Map();
|
|
19135
|
+
let cacheBytes = 0;
|
|
19136
|
+
function signature(target) {
|
|
19137
|
+
try {
|
|
19138
|
+
const stat = import_node_fs14.default.statSync(target, { bigint: true });
|
|
19139
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.birthtimeNs}`;
|
|
19140
|
+
} catch (error) {
|
|
19141
|
+
if (error.code === "ENOENT") return "missing";
|
|
19142
|
+
throw error;
|
|
19143
|
+
}
|
|
19144
|
+
}
|
|
19145
|
+
function invalidate(key2) {
|
|
19146
|
+
const previous = latestCache.get(key2);
|
|
19147
|
+
if (previous) cacheBytes -= previous.bytes;
|
|
19148
|
+
latestCache.delete(key2);
|
|
19149
|
+
}
|
|
19150
|
+
function invalidateSession(sessionId) {
|
|
19151
|
+
for (const key2 of latestCache.keys()) if (JSON.parse(key2)[0] === sessionId) invalidate(key2);
|
|
19152
|
+
}
|
|
18959
19153
|
function ensureDir() {
|
|
18960
19154
|
const state = ensureNodeStateRoot(paths.root);
|
|
18961
|
-
|
|
19155
|
+
import_node_fs14.default.mkdirSync(state.checkpointsDir, { recursive: true });
|
|
18962
19156
|
}
|
|
18963
19157
|
function filePath(sessionId) {
|
|
18964
19158
|
return safeFilePath(paths.checkpointsDir, sessionId, ".jsonl");
|
|
18965
19159
|
}
|
|
18966
|
-
function
|
|
18967
|
-
const
|
|
18968
|
-
|
|
18969
|
-
|
|
18970
|
-
|
|
18971
|
-
|
|
18972
|
-
|
|
18973
|
-
|
|
18974
|
-
|
|
19160
|
+
async function readCheckpoint(sessionId, turnId) {
|
|
19161
|
+
const target = filePath(sessionId);
|
|
19162
|
+
const key2 = JSON.stringify([sessionId, turnId ?? null]);
|
|
19163
|
+
try {
|
|
19164
|
+
const before2 = signature(target);
|
|
19165
|
+
const cached = latestCache.get(key2);
|
|
19166
|
+
if (cached?.signature === before2) {
|
|
19167
|
+
latestCache.delete(key2);
|
|
19168
|
+
latestCache.set(key2, cached);
|
|
19169
|
+
return structuredClone(cached.checkpoint);
|
|
19170
|
+
}
|
|
19171
|
+
invalidate(key2);
|
|
19172
|
+
let checkpoint = null;
|
|
19173
|
+
let bytes = 0;
|
|
19174
|
+
const corrupted = [];
|
|
19175
|
+
if (before2 !== "missing") {
|
|
19176
|
+
let failRead2 = function(error) {
|
|
19177
|
+
readError = error;
|
|
19178
|
+
lines.close();
|
|
19179
|
+
};
|
|
19180
|
+
var failRead = failRead2;
|
|
19181
|
+
const input = import_node_fs14.default.createReadStream(target, { encoding: "utf8", highWaterMark: 64 * 1024 });
|
|
19182
|
+
const lines = (0, import_node_readline.createInterface)({ input, crlfDelay: Infinity });
|
|
19183
|
+
let readError;
|
|
19184
|
+
input.on("error", failRead2);
|
|
19185
|
+
let lineNumber = 0;
|
|
19186
|
+
try {
|
|
19187
|
+
for await (const line of lines) {
|
|
19188
|
+
lineNumber++;
|
|
19189
|
+
if (!line) continue;
|
|
19190
|
+
try {
|
|
19191
|
+
const value = JSON.parse(line);
|
|
19192
|
+
if (!turnId || value?.turnId === turnId) {
|
|
19193
|
+
checkpoint = value;
|
|
19194
|
+
bytes = Buffer.byteLength(line, "utf8");
|
|
19195
|
+
}
|
|
19196
|
+
} catch {
|
|
19197
|
+
corrupted.push(lineNumber);
|
|
19198
|
+
}
|
|
19199
|
+
await new Promise(function yieldParsing(resolve) {
|
|
19200
|
+
setImmediate(resolve);
|
|
19201
|
+
});
|
|
19202
|
+
}
|
|
19203
|
+
if (readError) throw readError;
|
|
19204
|
+
} finally {
|
|
19205
|
+
lines.close();
|
|
19206
|
+
input.destroy();
|
|
19207
|
+
input.off("error", failRead2);
|
|
19208
|
+
}
|
|
19209
|
+
}
|
|
19210
|
+
if (corrupted.length) console.warn(`[DURABLE_JSONL_CORRUPTED] file=${import_node_path14.default.basename(target)} records=${corrupted.length} lines=${corrupted.join(",")}`);
|
|
19211
|
+
if (!corrupted.length && before2 === signature(target) && bytes <= 8 * 1024 * 1024) {
|
|
19212
|
+
while (latestCache.size >= 8 || cacheBytes + bytes > 8 * 1024 * 1024) invalidate(latestCache.keys().next().value);
|
|
19213
|
+
latestCache.set(key2, { signature: before2, checkpoint, bytes });
|
|
19214
|
+
cacheBytes += bytes;
|
|
19215
|
+
return structuredClone(checkpoint);
|
|
19216
|
+
}
|
|
19217
|
+
return checkpoint;
|
|
19218
|
+
} catch (error) {
|
|
19219
|
+
invalidate(key2);
|
|
19220
|
+
throw error;
|
|
18975
19221
|
}
|
|
18976
|
-
return null;
|
|
18977
19222
|
}
|
|
18978
19223
|
return {
|
|
18979
19224
|
async getLatest(sessionId) {
|
|
18980
19225
|
ensureDir();
|
|
18981
|
-
return withFileLock(filePath(sessionId), () =>
|
|
19226
|
+
return withFileLock(filePath(sessionId), () => readCheckpoint(sessionId));
|
|
18982
19227
|
},
|
|
18983
19228
|
async getByTurn(sessionId, turnId) {
|
|
18984
19229
|
ensureDir();
|
|
18985
|
-
return withFileLock(filePath(sessionId), () =>
|
|
19230
|
+
return withFileLock(filePath(sessionId), () => readCheckpoint(sessionId, turnId));
|
|
18986
19231
|
},
|
|
18987
19232
|
async save(sessionId, checkpoint) {
|
|
18988
19233
|
ensureDir();
|
|
18989
19234
|
await withFileLock(filePath(sessionId), () => {
|
|
19235
|
+
invalidateSession(sessionId);
|
|
18990
19236
|
appendJsonLine(filePath(sessionId), JSON.stringify(checkpoint));
|
|
18991
19237
|
});
|
|
18992
19238
|
},
|
|
18993
19239
|
async recoverStale(sessionId, now, staleAfterMs) {
|
|
18994
19240
|
ensureDir();
|
|
18995
|
-
return withFileLock(filePath(sessionId), ()
|
|
18996
|
-
const latest =
|
|
19241
|
+
return withFileLock(filePath(sessionId), async function recover() {
|
|
19242
|
+
const latest = await readCheckpoint(sessionId);
|
|
18997
19243
|
if (!latest) return null;
|
|
18998
19244
|
if (latest.status !== "running" || !latest.lease || now - latest.lease.heartbeatAt <= staleAfterMs) return latest;
|
|
18999
19245
|
const recovered = {
|
|
@@ -19001,6 +19247,7 @@ function createNodeCheckpointStore(options) {
|
|
|
19001
19247
|
status: "interrupted_recoverable",
|
|
19002
19248
|
interruptionReason: "stale_lease"
|
|
19003
19249
|
};
|
|
19250
|
+
invalidateSession(sessionId);
|
|
19004
19251
|
appendJsonLine(filePath(sessionId), JSON.stringify(recovered));
|
|
19005
19252
|
return recovered;
|
|
19006
19253
|
});
|
|
@@ -19009,7 +19256,8 @@ function createNodeCheckpointStore(options) {
|
|
|
19009
19256
|
ensureDir();
|
|
19010
19257
|
const target = filePath(sessionId);
|
|
19011
19258
|
await withFileLock(target, () => {
|
|
19012
|
-
|
|
19259
|
+
invalidateSession(sessionId);
|
|
19260
|
+
if (import_node_fs14.default.existsSync(target)) import_node_fs14.default.unlinkSync(target);
|
|
19013
19261
|
});
|
|
19014
19262
|
}
|
|
19015
19263
|
};
|
|
@@ -19025,13 +19273,14 @@ function createNodeEventSink(_options) {
|
|
|
19025
19273
|
}
|
|
19026
19274
|
|
|
19027
19275
|
// src/node/stores/node-input-inbox.ts
|
|
19028
|
-
var
|
|
19029
|
-
var
|
|
19276
|
+
var import_node_crypto8 = require("node:crypto");
|
|
19277
|
+
var import_node_fs15 = __toESM(require("node:fs"));
|
|
19278
|
+
var import_core14 = require("@autopilot-agent/core");
|
|
19030
19279
|
function createNodeInputInbox(options) {
|
|
19031
19280
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19032
19281
|
function ensureDir() {
|
|
19033
19282
|
const state = ensureNodeStateRoot(paths.root);
|
|
19034
|
-
|
|
19283
|
+
import_node_fs15.default.mkdirSync(state.inboxDir, { recursive: true });
|
|
19035
19284
|
}
|
|
19036
19285
|
function filePath(sessionId) {
|
|
19037
19286
|
return safeFilePath(paths.inboxDir, sessionId, ".jsonl");
|
|
@@ -19054,10 +19303,13 @@ function createNodeInputInbox(options) {
|
|
|
19054
19303
|
const inputs = readInbox(input.sessionId);
|
|
19055
19304
|
if (input.clientMessageId) {
|
|
19056
19305
|
const existing = inputs.find((candidate) => candidate.clientMessageId === input.clientMessageId);
|
|
19057
|
-
if (existing)
|
|
19306
|
+
if (existing) {
|
|
19307
|
+
if (existing.content !== input.content || (0, import_core14.inboxOriginKey)(existing.origin) !== (0, import_core14.inboxOriginKey)(input.origin)) throw new Error("INBOX_INPUT_CONFLICT");
|
|
19308
|
+
return existing;
|
|
19309
|
+
}
|
|
19058
19310
|
}
|
|
19059
19311
|
const inboxInput = {
|
|
19060
|
-
inputId: (0,
|
|
19312
|
+
inputId: (0, import_node_crypto8.randomUUID)(),
|
|
19061
19313
|
sessionId: input.sessionId,
|
|
19062
19314
|
turnId: input.turnId,
|
|
19063
19315
|
delivery: input.delivery,
|
|
@@ -19066,6 +19318,7 @@ function createNodeInputInbox(options) {
|
|
|
19066
19318
|
clientMessageId: input.clientMessageId,
|
|
19067
19319
|
attachments: input.attachments ?? [],
|
|
19068
19320
|
selectedSkills: input.selectedSkills ?? [],
|
|
19321
|
+
origin: input.origin,
|
|
19069
19322
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
19070
19323
|
};
|
|
19071
19324
|
inputs.push(inboxInput);
|
|
@@ -19118,7 +19371,7 @@ function createNodeInputInbox(options) {
|
|
|
19118
19371
|
},
|
|
19119
19372
|
async cancel(inputId) {
|
|
19120
19373
|
ensureDir();
|
|
19121
|
-
const files =
|
|
19374
|
+
const files = import_node_fs15.default.readdirSync(paths.inboxDir).filter((file) => file.endsWith(".jsonl"));
|
|
19122
19375
|
for (const file of files) {
|
|
19123
19376
|
const sessionId = file.slice(0, -6);
|
|
19124
19377
|
const cancelled = await withFileLock(filePath(sessionId), () => {
|
|
@@ -19137,7 +19390,7 @@ function createNodeInputInbox(options) {
|
|
|
19137
19390
|
ensureDir();
|
|
19138
19391
|
const target = filePath(sessionId);
|
|
19139
19392
|
await withFileLock(target, () => {
|
|
19140
|
-
if (
|
|
19393
|
+
if (import_node_fs15.default.existsSync(target)) import_node_fs15.default.unlinkSync(target);
|
|
19141
19394
|
});
|
|
19142
19395
|
},
|
|
19143
19396
|
async waitForInput(_query) {
|
|
@@ -19146,21 +19399,21 @@ function createNodeInputInbox(options) {
|
|
|
19146
19399
|
}
|
|
19147
19400
|
|
|
19148
19401
|
// src/node/stores/node-project-store.ts
|
|
19149
|
-
var
|
|
19150
|
-
var
|
|
19402
|
+
var import_node_crypto9 = require("node:crypto");
|
|
19403
|
+
var import_node_fs16 = __toESM(require("node:fs"));
|
|
19151
19404
|
function createNodeProjectStore(options) {
|
|
19152
19405
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19153
19406
|
function ensureDir() {
|
|
19154
19407
|
const state = ensureNodeStateRoot(paths.root);
|
|
19155
|
-
|
|
19408
|
+
import_node_fs16.default.mkdirSync(state.projectsDir, { recursive: true });
|
|
19156
19409
|
}
|
|
19157
19410
|
function filePath(projectId) {
|
|
19158
19411
|
return safeFilePath(paths.projectsDir, projectId, ".json");
|
|
19159
19412
|
}
|
|
19160
19413
|
return {
|
|
19161
19414
|
async get(id) {
|
|
19162
|
-
|
|
19163
|
-
return
|
|
19415
|
+
assertNodeStateSchema(paths.root);
|
|
19416
|
+
return readJsonFile(filePath(id));
|
|
19164
19417
|
},
|
|
19165
19418
|
async save(project) {
|
|
19166
19419
|
ensureDir();
|
|
@@ -19169,9 +19422,10 @@ function createNodeProjectStore(options) {
|
|
|
19169
19422
|
});
|
|
19170
19423
|
},
|
|
19171
19424
|
async list() {
|
|
19172
|
-
|
|
19425
|
+
assertNodeStateSchema(paths.root);
|
|
19173
19426
|
const projects = [];
|
|
19174
|
-
|
|
19427
|
+
if (!import_node_fs16.default.existsSync(paths.projectsDir)) return projects;
|
|
19428
|
+
for (const file of import_node_fs16.default.readdirSync(paths.projectsDir).filter((entry) => entry.endsWith(".json"))) {
|
|
19175
19429
|
const project = readJsonFile(filePath(file.slice(0, -5)));
|
|
19176
19430
|
if (project) projects.push(project);
|
|
19177
19431
|
}
|
|
@@ -19180,7 +19434,7 @@ function createNodeProjectStore(options) {
|
|
|
19180
19434
|
async create(input) {
|
|
19181
19435
|
const now = Date.now();
|
|
19182
19436
|
const project = {
|
|
19183
|
-
id: (0,
|
|
19437
|
+
id: (0, import_node_crypto9.randomUUID)(),
|
|
19184
19438
|
name: input.name,
|
|
19185
19439
|
workspaceRoot: input.workspaceRoot,
|
|
19186
19440
|
description: input.description,
|
|
@@ -19196,40 +19450,42 @@ function createNodeProjectStore(options) {
|
|
|
19196
19450
|
ensureDir();
|
|
19197
19451
|
const target = filePath(id);
|
|
19198
19452
|
return withFileLock(target, () => {
|
|
19199
|
-
if (!
|
|
19200
|
-
|
|
19453
|
+
if (!import_node_fs16.default.existsSync(target)) return false;
|
|
19454
|
+
import_node_fs16.default.unlinkSync(target);
|
|
19201
19455
|
return true;
|
|
19202
19456
|
});
|
|
19203
19457
|
}
|
|
19204
19458
|
};
|
|
19205
19459
|
}
|
|
19206
19460
|
|
|
19207
|
-
// src/node/stores/node-
|
|
19208
|
-
var
|
|
19461
|
+
// src/node/stores/node-thread-store.ts
|
|
19462
|
+
var import_core15 = require("@autopilot-agent/core");
|
|
19463
|
+
var import_node_fs18 = __toESM(require("node:fs"));
|
|
19464
|
+
var import_node_path16 = __toESM(require("node:path"));
|
|
19209
19465
|
|
|
19210
19466
|
// src/node/chat-state.ts
|
|
19211
|
-
var
|
|
19467
|
+
var import_node_fs17 = __toESM(require("node:fs"));
|
|
19212
19468
|
var import_node_os7 = __toESM(require("node:os"));
|
|
19213
|
-
var
|
|
19469
|
+
var import_node_path15 = __toESM(require("node:path"));
|
|
19214
19470
|
function resolveNodeChatStatePaths(options = {}) {
|
|
19215
19471
|
try {
|
|
19216
|
-
if (options.globalStateRoot !== void 0 && !
|
|
19472
|
+
if (options.globalStateRoot !== void 0 && !import_node_path15.default.isAbsolute(options.globalStateRoot)) throw new NodeChatError("CHAT_STATE_ROOT_INVALID");
|
|
19217
19473
|
const globalRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: import_node_os7.default.homedir() });
|
|
19218
|
-
const root =
|
|
19219
|
-
return { root, stateRoot:
|
|
19474
|
+
const root = import_node_path15.default.join(globalRoot, "chat");
|
|
19475
|
+
return { root, stateRoot: import_node_path15.default.join(root, "state"), attachmentsRoot: import_node_path15.default.join(root, "attachments"), knowledgeRoot: import_node_path15.default.join(root, "knowledge") };
|
|
19220
19476
|
} catch (error) {
|
|
19221
19477
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19222
19478
|
}
|
|
19223
19479
|
}
|
|
19224
19480
|
function assertSafeNodePath(root, target) {
|
|
19225
19481
|
try {
|
|
19226
|
-
const relative =
|
|
19227
|
-
if (relative === ".." || relative.startsWith(`..${
|
|
19482
|
+
const relative = import_node_path15.default.relative(root, target);
|
|
19483
|
+
if (relative === ".." || relative.startsWith(`..${import_node_path15.default.sep}`) || import_node_path15.default.isAbsolute(relative)) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19228
19484
|
let current = root;
|
|
19229
|
-
for (const segment of ["", ...relative.split(
|
|
19230
|
-
if (segment) current =
|
|
19485
|
+
for (const segment of ["", ...relative.split(import_node_path15.default.sep).filter(Boolean)]) {
|
|
19486
|
+
if (segment) current = import_node_path15.default.join(current, segment);
|
|
19231
19487
|
try {
|
|
19232
|
-
const entry =
|
|
19488
|
+
const entry = import_node_fs17.default.lstatSync(current);
|
|
19233
19489
|
if (entry.isSymbolicLink() || current !== target && !entry.isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19234
19490
|
} catch (error) {
|
|
19235
19491
|
if (error.code !== "ENOENT") throw error;
|
|
@@ -19243,88 +19499,526 @@ function assertSafeNodePath(root, target) {
|
|
|
19243
19499
|
function ensureChatDirectory(root, target) {
|
|
19244
19500
|
try {
|
|
19245
19501
|
assertSafeNodePath(root, target);
|
|
19246
|
-
|
|
19502
|
+
import_node_fs17.default.mkdirSync(target, { recursive: true, mode: 448 });
|
|
19247
19503
|
assertSafeNodePath(root, target);
|
|
19248
|
-
if (!
|
|
19504
|
+
if (!import_node_fs17.default.lstatSync(target).isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19249
19505
|
} catch (error) {
|
|
19250
19506
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19251
19507
|
}
|
|
19252
19508
|
}
|
|
19253
19509
|
function initializeNodeChatDirectories(paths) {
|
|
19254
|
-
ensureChatDirectory(
|
|
19510
|
+
ensureChatDirectory(import_node_path15.default.dirname(paths.root), paths.root);
|
|
19255
19511
|
ensureChatDirectory(paths.root, paths.stateRoot);
|
|
19256
19512
|
ensureChatDirectory(paths.root, paths.attachmentsRoot);
|
|
19257
19513
|
}
|
|
19258
19514
|
|
|
19259
|
-
// src/node/stores/node-
|
|
19260
|
-
function
|
|
19261
|
-
const
|
|
19262
|
-
const
|
|
19263
|
-
|
|
19264
|
-
|
|
19265
|
-
|
|
19266
|
-
|
|
19515
|
+
// src/node/stores/node-thread-store.ts
|
|
19516
|
+
function createNodeThreadStore(stateRoot) {
|
|
19517
|
+
const groups = import_node_path16.default.join(stateRoot, "threads", "groups");
|
|
19518
|
+
const controlCache = /* @__PURE__ */ new Map();
|
|
19519
|
+
let controlCacheBytes = 0;
|
|
19520
|
+
function controlSignature(target) {
|
|
19521
|
+
const stat = import_node_fs18.default.statSync(target, { bigint: true });
|
|
19522
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.birthtimeNs}`;
|
|
19267
19523
|
}
|
|
19268
|
-
function
|
|
19269
|
-
|
|
19270
|
-
|
|
19271
|
-
return target;
|
|
19524
|
+
function forgetControl(target) {
|
|
19525
|
+
controlCacheBytes -= controlCache.get(target)?.bytes ?? 0;
|
|
19526
|
+
controlCache.delete(target);
|
|
19272
19527
|
}
|
|
19273
|
-
function
|
|
19274
|
-
const
|
|
19275
|
-
if (!import_node_fs17.default.existsSync(target)) return null;
|
|
19528
|
+
function assertTargetRoot() {
|
|
19529
|
+
const manifest = import_node_path16.default.join(stateRoot, "schema.json");
|
|
19276
19530
|
let value;
|
|
19277
|
-
const content = import_node_fs17.default.readFileSync(target, "utf8");
|
|
19278
19531
|
try {
|
|
19279
|
-
|
|
19532
|
+
if (import_node_fs18.default.lstatSync(stateRoot).isSymbolicLink() || import_node_fs18.default.lstatSync(manifest).isSymbolicLink()) throw new Error("unsafe");
|
|
19533
|
+
value = JSON.parse(import_node_fs18.default.readFileSync(manifest, "utf8"));
|
|
19280
19534
|
} catch {
|
|
19281
|
-
throw new
|
|
19535
|
+
throw new Error("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
19282
19536
|
}
|
|
19283
|
-
|
|
19284
|
-
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19285
|
-
if (value.productMode === void 0) atomicReplace(target, JSON.stringify(session, null, 2));
|
|
19286
|
-
return session;
|
|
19537
|
+
if (!value || typeof value !== "object" || value.schemaVersion !== 8) throw new Error("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
19287
19538
|
}
|
|
19288
|
-
|
|
19289
|
-
|
|
19290
|
-
|
|
19539
|
+
function controlPath(groupId) {
|
|
19540
|
+
const target = import_node_path16.default.join(safeFilePath(groups, groupId, ""), "control.json");
|
|
19541
|
+
assertSafeNodePath(stateRoot, target);
|
|
19542
|
+
return target;
|
|
19543
|
+
}
|
|
19544
|
+
function assertInteractionControls(control) {
|
|
19545
|
+
if (control.controls !== void 0 && !Array.isArray(control.controls)) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19546
|
+
for (const intent of control.controls ?? []) {
|
|
19547
|
+
if (intent?.kind !== "continue_interaction") continue;
|
|
19548
|
+
if (intent.failureDiagnostic !== void 0 && (!(0, import_core15.sanitizeContinuationFailure)(intent.failureDiagnostic) || Object.keys(intent.failureDiagnostic).some(function invalid(key2) {
|
|
19549
|
+
return !Object.prototype.hasOwnProperty.call((0, import_core15.sanitizeContinuationFailure)(intent.failureDiagnostic), key2) || intent.failureDiagnostic[key2] !== (0, import_core15.sanitizeContinuationFailure)(intent.failureDiagnostic)[key2];
|
|
19550
|
+
}))) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19551
|
+
const ids = [intent.controlId, intent.threadId, intent.expectedTurnId, intent.approvalId ?? intent.requestId];
|
|
19552
|
+
if (ids.some(function invalid(id) {
|
|
19553
|
+
return typeof id !== "string" || !id || id.length > 200 || /[\\/\x00-\x1f]/u.test(id);
|
|
19554
|
+
}) || 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");
|
|
19555
|
+
}
|
|
19556
|
+
}
|
|
19557
|
+
function read(groupId) {
|
|
19558
|
+
const target = controlPath(groupId);
|
|
19559
|
+
try {
|
|
19560
|
+
const before2 = controlSignature(target);
|
|
19561
|
+
const cached = controlCache.get(target);
|
|
19562
|
+
if (cached?.signature === before2) {
|
|
19563
|
+
controlCache.delete(target);
|
|
19564
|
+
controlCache.set(target, cached);
|
|
19565
|
+
return structuredClone(cached.value);
|
|
19566
|
+
}
|
|
19567
|
+
forgetControl(target);
|
|
19568
|
+
const text = import_node_fs18.default.readFileSync(target, "utf8");
|
|
19569
|
+
let value;
|
|
19291
19570
|
try {
|
|
19292
|
-
|
|
19293
|
-
|
|
19294
|
-
|
|
19295
|
-
|
|
19296
|
-
|
|
19297
|
-
|
|
19298
|
-
|
|
19571
|
+
value = JSON.parse(text);
|
|
19572
|
+
} catch {
|
|
19573
|
+
throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19574
|
+
}
|
|
19575
|
+
if (!value || value.group?.groupId !== groupId || !Number.isSafeInteger(value.revision) || value.revision < 0) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19576
|
+
assertInteractionControls(value);
|
|
19577
|
+
const bytes = Buffer.byteLength(text, "utf8");
|
|
19578
|
+
if (bytes <= 8 * 1024 * 1024 && before2 === controlSignature(target)) {
|
|
19579
|
+
while (controlCache.size >= 128 || controlCacheBytes + bytes > 8 * 1024 * 1024) forgetControl(controlCache.keys().next().value);
|
|
19580
|
+
controlCache.set(target, { signature: before2, value, bytes });
|
|
19581
|
+
controlCacheBytes += bytes;
|
|
19582
|
+
return structuredClone(value);
|
|
19583
|
+
}
|
|
19584
|
+
return value;
|
|
19585
|
+
} catch (error) {
|
|
19586
|
+
forgetControl(target);
|
|
19587
|
+
if (error.code === "ENOENT") return null;
|
|
19588
|
+
throw error;
|
|
19589
|
+
}
|
|
19590
|
+
}
|
|
19591
|
+
function messagePath(groupId, threadId, seq2) {
|
|
19592
|
+
if (!Number.isSafeInteger(seq2) || seq2 < 1) throw new Error("THREAD_CURSOR_INVALID");
|
|
19593
|
+
const dir = import_node_path16.default.join(safeFilePath(groups, groupId, ""), "messages");
|
|
19594
|
+
const threadDir = safeFilePath(dir, threadId, "");
|
|
19595
|
+
const target = safeFilePath(threadDir, String(seq2), ".json");
|
|
19596
|
+
assertSafeNodePath(stateRoot, target);
|
|
19597
|
+
return target;
|
|
19598
|
+
}
|
|
19599
|
+
function readMessage(groupId, threadId, seq2) {
|
|
19600
|
+
let value;
|
|
19601
|
+
try {
|
|
19602
|
+
value = JSON.parse(import_node_fs18.default.readFileSync(messagePath(groupId, threadId, seq2), "utf8"));
|
|
19603
|
+
} catch (error) {
|
|
19604
|
+
if (error.code === "ENOENT") return null;
|
|
19605
|
+
throw new Error("THREAD_MESSAGE_CORRUPTED");
|
|
19606
|
+
}
|
|
19607
|
+
if (!value || value.groupId !== groupId || value.toThreadId !== threadId || value.deliverySeq !== seq2) throw new Error("THREAD_MESSAGE_CORRUPTED");
|
|
19608
|
+
return value;
|
|
19609
|
+
}
|
|
19610
|
+
function eventPath(groupId, seq2) {
|
|
19611
|
+
if (!Number.isSafeInteger(seq2) || seq2 < 1) throw new Error("THREAD_CURSOR_INVALID");
|
|
19612
|
+
const dir = import_node_path16.default.join(safeFilePath(groups, groupId, ""), "events");
|
|
19613
|
+
const target = safeFilePath(dir, String(seq2), ".json");
|
|
19614
|
+
assertSafeNodePath(stateRoot, target);
|
|
19615
|
+
return target;
|
|
19616
|
+
}
|
|
19617
|
+
function readEvent(groupId, seq2) {
|
|
19618
|
+
let value;
|
|
19619
|
+
try {
|
|
19620
|
+
value = JSON.parse(import_node_fs18.default.readFileSync(eventPath(groupId, seq2), "utf8"));
|
|
19621
|
+
} catch (error) {
|
|
19622
|
+
if (error.code === "ENOENT") return null;
|
|
19623
|
+
throw new Error("THREAD_EVENT_CORRUPTED");
|
|
19624
|
+
}
|
|
19625
|
+
if (!value || value.groupId !== groupId || value.groupSeq !== seq2) throw new Error("THREAD_EVENT_CORRUPTED");
|
|
19626
|
+
return value;
|
|
19627
|
+
}
|
|
19628
|
+
function readRequest(id) {
|
|
19629
|
+
const target = safeFilePath(import_node_path16.default.join(stateRoot, "threads", "requests"), id, ".json");
|
|
19630
|
+
assertSafeNodePath(stateRoot, target);
|
|
19631
|
+
try {
|
|
19632
|
+
return JSON.parse(import_node_fs18.default.readFileSync(target, "utf8"));
|
|
19633
|
+
} catch (error) {
|
|
19634
|
+
if (error.code === "ENOENT") return null;
|
|
19635
|
+
throw new Error("THREAD_REQUEST_CORRUPTED");
|
|
19636
|
+
}
|
|
19637
|
+
}
|
|
19638
|
+
return {
|
|
19639
|
+
/** 只读检查,和预留中的最终检查共同处理并发。 */
|
|
19640
|
+
async verifyRequest(id, groupId, payloadDigest) {
|
|
19641
|
+
assertTargetRoot();
|
|
19642
|
+
const prior = readRequest(id);
|
|
19643
|
+
if (prior && (prior.groupId !== groupId || prior.payloadDigest !== payloadDigest)) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19299
19644
|
},
|
|
19300
|
-
/**
|
|
19301
|
-
async
|
|
19302
|
-
|
|
19303
|
-
|
|
19304
|
-
|
|
19305
|
-
|
|
19306
|
-
|
|
19307
|
-
|
|
19308
|
-
|
|
19645
|
+
/** 请求身份独立于组,跨进程锁内持久预留,冲突不得重绑。 */
|
|
19646
|
+
async reserveRequest(id, groupId, payloadDigest) {
|
|
19647
|
+
assertTargetRoot();
|
|
19648
|
+
const target = safeFilePath(import_node_path16.default.join(stateRoot, "threads", "requests"), id, ".json");
|
|
19649
|
+
assertSafeNodePath(stateRoot, target);
|
|
19650
|
+
await withFileLock(target, function reserveLocked() {
|
|
19651
|
+
if (import_node_fs18.default.existsSync(target)) {
|
|
19652
|
+
let prior;
|
|
19653
|
+
try {
|
|
19654
|
+
prior = JSON.parse(import_node_fs18.default.readFileSync(target, "utf8"));
|
|
19655
|
+
} catch {
|
|
19656
|
+
throw new Error("THREAD_REQUEST_CORRUPTED");
|
|
19657
|
+
}
|
|
19658
|
+
if (prior.groupId !== groupId || prior.payloadDigest !== payloadDigest) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19659
|
+
return;
|
|
19309
19660
|
}
|
|
19310
|
-
|
|
19311
|
-
}
|
|
19312
|
-
|
|
19661
|
+
atomicReplace(target, JSON.stringify({ groupId, payloadDigest }));
|
|
19662
|
+
}, { requireExitedOwner: true });
|
|
19663
|
+
},
|
|
19664
|
+
/** 同序号重放幂等,不同事件冲突。 */
|
|
19665
|
+
async writeEvent(event) {
|
|
19666
|
+
assertTargetRoot();
|
|
19667
|
+
const target = eventPath(event.groupId, event.groupSeq);
|
|
19668
|
+
const serialized = JSON.stringify(event);
|
|
19669
|
+
if (Buffer.byteLength(serialized, "utf8") > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
19670
|
+
await withFileLock(target, function writeEventLocked() {
|
|
19671
|
+
const previous = readEvent(event.groupId, event.groupSeq);
|
|
19672
|
+
if (previous && JSON.stringify(previous) !== serialized) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19673
|
+
if (!previous) atomicReplace(target, serialized);
|
|
19674
|
+
}, { requireExitedOwner: true });
|
|
19675
|
+
},
|
|
19676
|
+
/** 查询不创建锁或目录。 */
|
|
19677
|
+
async readEvent(groupId, seq2) {
|
|
19678
|
+
assertTargetRoot();
|
|
19679
|
+
return readEvent(groupId, seq2);
|
|
19680
|
+
},
|
|
19681
|
+
/** 短期 Session 锁只覆盖元数据变更与删除,不覆盖 Turn 执行。 */
|
|
19682
|
+
async withSessionLock(threadId, operation) {
|
|
19683
|
+
assertTargetRoot();
|
|
19684
|
+
const target = safeFilePath(import_node_path16.default.join(stateRoot, "threads", "session-locks"), threadId, "");
|
|
19685
|
+
assertSafeNodePath(stateRoot, target);
|
|
19686
|
+
return withFileLock(target, operation, { requireExitedOwner: true });
|
|
19687
|
+
},
|
|
19688
|
+
/** 检查全部组控制记录;损坏记录明确报错,不遗漏受管引用。 */
|
|
19689
|
+
async hasMembership(threadId) {
|
|
19690
|
+
assertTargetRoot();
|
|
19691
|
+
if (!import_node_fs18.default.existsSync(groups)) return false;
|
|
19692
|
+
for (const groupId of import_node_fs18.default.readdirSync(groups)) {
|
|
19693
|
+
const control = read(groupId);
|
|
19694
|
+
if (!control) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19695
|
+
if (control.members.some(function member(item) {
|
|
19696
|
+
return item.threadId === threadId;
|
|
19697
|
+
}) || control.creates.some(function intent(item) {
|
|
19698
|
+
return item.threadId === threadId || item.parentThreadId === threadId;
|
|
19699
|
+
})) return true;
|
|
19700
|
+
}
|
|
19701
|
+
return false;
|
|
19702
|
+
},
|
|
19703
|
+
/** 目标格式与稳定身份校验后按消息锁幂等写入。 */
|
|
19704
|
+
async writeMessage(message) {
|
|
19705
|
+
assertTargetRoot();
|
|
19706
|
+
const target = messagePath(message.groupId, message.toThreadId, message.deliverySeq);
|
|
19707
|
+
const serialized = JSON.stringify(message);
|
|
19708
|
+
if (Buffer.byteLength(serialized, "utf8") > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
19709
|
+
await withFileLock(target, function writeLocked() {
|
|
19710
|
+
const prior = readMessage(message.groupId, message.toThreadId, message.deliverySeq);
|
|
19711
|
+
if (prior && JSON.stringify(prior) !== serialized) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19712
|
+
if (!prior) atomicReplace(target, serialized);
|
|
19713
|
+
}, { requireExitedOwner: true });
|
|
19714
|
+
},
|
|
19715
|
+
/** 按序号读取,不创建目录或锁文件。 */
|
|
19716
|
+
async readMessage(groupId, threadId, seq2) {
|
|
19717
|
+
assertTargetRoot();
|
|
19718
|
+
return readMessage(groupId, threadId, seq2);
|
|
19719
|
+
},
|
|
19720
|
+
/** 查询不触发状态根初始化或执行恢复。 */
|
|
19721
|
+
async readControl(groupId) {
|
|
19722
|
+
assertTargetRoot();
|
|
19723
|
+
return read(groupId);
|
|
19724
|
+
},
|
|
19725
|
+
/** 只列出已有 control.json 的组,半初始化目录不冒充可执行目标。 */
|
|
19726
|
+
async listGroups() {
|
|
19727
|
+
assertTargetRoot();
|
|
19728
|
+
if (!import_node_fs18.default.existsSync(groups)) return [];
|
|
19729
|
+
return import_node_fs18.default.readdirSync(groups).filter(function hasControl(name) {
|
|
19730
|
+
return import_node_fs18.default.existsSync(controlPath(name));
|
|
19731
|
+
}).sort();
|
|
19732
|
+
},
|
|
19733
|
+
/**
|
|
19734
|
+
* 本进程内的文件变化唤醒;watchFile 只做 stat 轮询,不创建锁或文件。
|
|
19735
|
+
* 跨进程写入同样会改变 mtime,因此订阅不依赖同一进程的 CAS 回调。
|
|
19736
|
+
*/
|
|
19737
|
+
subscribe(groupId, listener) {
|
|
19738
|
+
const target = controlPath(groupId);
|
|
19739
|
+
const onChange = function changed() {
|
|
19740
|
+
try {
|
|
19741
|
+
listener();
|
|
19742
|
+
} catch {
|
|
19743
|
+
}
|
|
19744
|
+
};
|
|
19745
|
+
import_node_fs18.default.watchFile(target, { interval: 200, persistent: false }, onChange);
|
|
19746
|
+
return () => {
|
|
19747
|
+
import_node_fs18.default.unwatchFile(target, onChange);
|
|
19748
|
+
};
|
|
19749
|
+
},
|
|
19750
|
+
/** 加锁后重新读取和校验版本,原子替换而不跨 Session 持锁执行。 */
|
|
19751
|
+
async compareAndSetControl(groupId, expectedRevision, value) {
|
|
19752
|
+
assertTargetRoot();
|
|
19753
|
+
if (value.group.groupId !== groupId || value.revision !== (expectedRevision === null ? 0 : expectedRevision + 1)) throw new Error("THREAD_CONTROL_INVALID");
|
|
19754
|
+
assertInteractionControls(value);
|
|
19755
|
+
const serialized = JSON.stringify(value);
|
|
19756
|
+
if (Buffer.byteLength(serialized, "utf8") > 4 * 1024 * 1024) throw new Error("THREAD_STORAGE_FULL");
|
|
19757
|
+
return withFileLock(controlPath(groupId), function updateUnderLock() {
|
|
19758
|
+
const current = read(groupId);
|
|
19759
|
+
if (expectedRevision === null ? current !== null : current?.revision !== expectedRevision) return false;
|
|
19760
|
+
atomicReplace(controlPath(groupId), serialized);
|
|
19761
|
+
return true;
|
|
19762
|
+
}, { requireExitedOwner: true });
|
|
19763
|
+
}
|
|
19764
|
+
};
|
|
19765
|
+
}
|
|
19766
|
+
|
|
19767
|
+
// src/node/stores/node-session-store.ts
|
|
19768
|
+
var import_node_fs20 = __toESM(require("node:fs"));
|
|
19769
|
+
|
|
19770
|
+
// src/node/stores/session-directory.ts
|
|
19771
|
+
var import_node_fs19 = __toESM(require("node:fs"));
|
|
19772
|
+
var DIRECTORY_FIELDS = /* @__PURE__ */ new Set(["id", "title", "productMode", "projectId", "chatRetrievalMode", "createdAt", "updatedAt", "status", "activeTurnId"]);
|
|
19773
|
+
async function readSessionDirectoryRecord(filePath, id) {
|
|
19774
|
+
const fields2 = {};
|
|
19775
|
+
const stack = [];
|
|
19776
|
+
let root = false;
|
|
19777
|
+
let finished = false;
|
|
19778
|
+
let token;
|
|
19779
|
+
let text = "";
|
|
19780
|
+
let capture = false;
|
|
19781
|
+
let keyToken = false;
|
|
19782
|
+
let target;
|
|
19783
|
+
let escaped = false;
|
|
19784
|
+
let unicode = 0;
|
|
19785
|
+
function invalid() {
|
|
19786
|
+
throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
19787
|
+
}
|
|
19788
|
+
function beginValue() {
|
|
19789
|
+
if (!stack.length) {
|
|
19790
|
+
if (root) invalid();
|
|
19791
|
+
root = true;
|
|
19792
|
+
return void 0;
|
|
19793
|
+
}
|
|
19794
|
+
const frame = stack[stack.length - 1];
|
|
19795
|
+
if (frame.expect !== "value" && frame.expect !== "valueOrEnd") invalid();
|
|
19796
|
+
frame.expect = "commaOrEnd";
|
|
19797
|
+
return stack.length === 1 && frame.kind === "object" && frame.key && DIRECTORY_FIELDS.has(frame.key) ? frame.key : void 0;
|
|
19798
|
+
}
|
|
19799
|
+
function finishToken() {
|
|
19800
|
+
if (keyToken) {
|
|
19801
|
+
const frame = stack[stack.length - 1];
|
|
19802
|
+
frame.key = stack.length === 1 ? JSON.parse(text) : void 0;
|
|
19803
|
+
frame.expect = "colon";
|
|
19804
|
+
} else if (target) fields2[target] = JSON.parse(text);
|
|
19805
|
+
token = void 0;
|
|
19806
|
+
text = "";
|
|
19807
|
+
target = void 0;
|
|
19808
|
+
}
|
|
19809
|
+
const stream = import_node_fs19.default.createReadStream(filePath, { encoding: "utf8", highWaterMark: 16 * 1024 });
|
|
19810
|
+
for await (const chunk of stream) {
|
|
19811
|
+
for (const character of chunk) {
|
|
19812
|
+
if (token === "string") {
|
|
19813
|
+
if (capture) text += character;
|
|
19814
|
+
if (unicode) {
|
|
19815
|
+
if (!/[0-9a-f]/iu.test(character)) invalid();
|
|
19816
|
+
unicode--;
|
|
19817
|
+
continue;
|
|
19818
|
+
}
|
|
19819
|
+
if (escaped) {
|
|
19820
|
+
if (character === "u") unicode = 4;
|
|
19821
|
+
else if (!/["\\/bfnrt]/u.test(character)) invalid();
|
|
19822
|
+
escaped = false;
|
|
19823
|
+
continue;
|
|
19824
|
+
}
|
|
19825
|
+
if (character === "\\") {
|
|
19826
|
+
escaped = true;
|
|
19827
|
+
continue;
|
|
19828
|
+
}
|
|
19829
|
+
if (character === '"') {
|
|
19830
|
+
finishToken();
|
|
19831
|
+
continue;
|
|
19832
|
+
}
|
|
19833
|
+
if (character.charCodeAt(0) < 32) invalid();
|
|
19834
|
+
continue;
|
|
19835
|
+
}
|
|
19836
|
+
if (token === "primitive") {
|
|
19837
|
+
if (!/[ \t\r\n,}\]]/u.test(character)) {
|
|
19838
|
+
text += character;
|
|
19839
|
+
if (text.length > 128) invalid();
|
|
19840
|
+
continue;
|
|
19841
|
+
}
|
|
19842
|
+
if (!/^(?:null|true|false|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)$/u.test(text)) invalid();
|
|
19843
|
+
finishToken();
|
|
19844
|
+
}
|
|
19845
|
+
if (/[ \t\r\n]/u.test(character)) continue;
|
|
19846
|
+
if (finished) invalid();
|
|
19847
|
+
const frame = stack[stack.length - 1];
|
|
19848
|
+
if (character === '"') {
|
|
19849
|
+
keyToken = frame?.kind === "object" && (frame.expect === "key" || frame.expect === "keyOrEnd");
|
|
19850
|
+
target = keyToken ? void 0 : beginValue();
|
|
19851
|
+
capture = keyToken ? stack.length === 1 : target !== void 0;
|
|
19852
|
+
text = capture ? '"' : "";
|
|
19853
|
+
token = "string";
|
|
19854
|
+
continue;
|
|
19855
|
+
}
|
|
19856
|
+
if (character === "{" || character === "[") {
|
|
19857
|
+
const topLevel = !root;
|
|
19858
|
+
if (topLevel && character !== "{") invalid();
|
|
19859
|
+
beginValue();
|
|
19860
|
+
if (stack.length >= 128) invalid();
|
|
19861
|
+
stack.push({ kind: character === "{" ? "object" : "array", expect: character === "{" ? "keyOrEnd" : "valueOrEnd" });
|
|
19862
|
+
continue;
|
|
19863
|
+
}
|
|
19864
|
+
if (character === "}" || character === "]") {
|
|
19865
|
+
if (!frame || frame.kind !== (character === "}" ? "object" : "array") || !["commaOrEnd", character === "}" ? "keyOrEnd" : "valueOrEnd"].includes(frame.expect)) invalid();
|
|
19866
|
+
stack.pop();
|
|
19867
|
+
if (!stack.length) finished = true;
|
|
19868
|
+
continue;
|
|
19869
|
+
}
|
|
19870
|
+
if (character === ":") {
|
|
19871
|
+
if (frame?.expect !== "colon") invalid();
|
|
19872
|
+
frame.expect = "value";
|
|
19873
|
+
continue;
|
|
19874
|
+
}
|
|
19875
|
+
if (character === ",") {
|
|
19876
|
+
if (frame?.expect !== "commaOrEnd") invalid();
|
|
19877
|
+
frame.expect = frame.kind === "object" ? "key" : "value";
|
|
19878
|
+
continue;
|
|
19879
|
+
}
|
|
19880
|
+
target = beginValue();
|
|
19881
|
+
keyToken = false;
|
|
19882
|
+
capture = true;
|
|
19883
|
+
text = character;
|
|
19884
|
+
token = "primitive";
|
|
19885
|
+
}
|
|
19886
|
+
}
|
|
19887
|
+
if (!finished || token || stack.length) invalid();
|
|
19888
|
+
if (fields2.title !== void 0 && typeof fields2.title !== "string") invalid();
|
|
19889
|
+
return normalizeNodeSession(fields2, id);
|
|
19890
|
+
}
|
|
19891
|
+
|
|
19892
|
+
// src/node/stores/node-session-store.ts
|
|
19893
|
+
function createNodeSessionStore(options) {
|
|
19894
|
+
const paths = getNodeStatePaths(options.stateRoot);
|
|
19895
|
+
const productMode = options.productMode ?? "work";
|
|
19896
|
+
function ensureDir() {
|
|
19897
|
+
const state = ensureNodeStateRoot(options.stateRoot);
|
|
19898
|
+
assertSafeNodePath(state.root, state.sessionsDir);
|
|
19899
|
+
import_node_fs20.default.mkdirSync(state.sessionsDir, { recursive: true });
|
|
19900
|
+
}
|
|
19901
|
+
function filePath(sessionId) {
|
|
19902
|
+
const target = safeFilePath(paths.sessionsDir, sessionId, ".json");
|
|
19903
|
+
assertSafeNodePath(paths.root, target);
|
|
19904
|
+
return target;
|
|
19905
|
+
}
|
|
19906
|
+
function read(id) {
|
|
19907
|
+
const target = filePath(id);
|
|
19908
|
+
if (!import_node_fs20.default.existsSync(target)) return null;
|
|
19909
|
+
let value;
|
|
19910
|
+
const content = import_node_fs20.default.readFileSync(target, "utf8");
|
|
19911
|
+
try {
|
|
19912
|
+
value = JSON.parse(content);
|
|
19913
|
+
} catch {
|
|
19914
|
+
throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
19915
|
+
}
|
|
19916
|
+
const session = normalizeNodeSession(value, id);
|
|
19917
|
+
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19918
|
+
return session;
|
|
19919
|
+
}
|
|
19920
|
+
return {
|
|
19921
|
+
/** 在文件锁内校验并读取当前产品域的 Session。 */
|
|
19922
|
+
async get(id) {
|
|
19923
|
+
try {
|
|
19924
|
+
assertNodeStateSchema(paths.root);
|
|
19925
|
+
return read(id);
|
|
19926
|
+
} catch (error) {
|
|
19927
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19928
|
+
}
|
|
19929
|
+
},
|
|
19930
|
+
/** 单个关联目标也复用流式元数据边界,不读取完整Session正文。 */
|
|
19931
|
+
async getDirectoryEntry(id) {
|
|
19932
|
+
try {
|
|
19933
|
+
assertNodeStateSchema(paths.root);
|
|
19934
|
+
const target = filePath(id);
|
|
19935
|
+
if (!import_node_fs20.default.existsSync(target)) return null;
|
|
19936
|
+
const session = await readSessionDirectoryRecord(target, id);
|
|
19937
|
+
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19938
|
+
return session;
|
|
19939
|
+
} catch (error) {
|
|
19940
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19941
|
+
}
|
|
19942
|
+
},
|
|
19943
|
+
/** 逐项加锁读取,损坏记录不能从列表中无声消失。 */
|
|
19944
|
+
async list() {
|
|
19945
|
+
try {
|
|
19946
|
+
assertNodeStateSchema(paths.root);
|
|
19947
|
+
const sessions = [];
|
|
19948
|
+
if (!import_node_fs20.default.existsSync(paths.sessionsDir)) return sessions;
|
|
19949
|
+
for (const file of import_node_fs20.default.readdirSync(paths.sessionsDir)) {
|
|
19950
|
+
if (!file.endsWith(".json")) continue;
|
|
19951
|
+
const session = await this.get(file.slice(0, -5));
|
|
19952
|
+
if (session) sessions.push(session);
|
|
19953
|
+
}
|
|
19954
|
+
return sessions.sort((left, right) => right.updatedAt - left.updatedAt);
|
|
19955
|
+
} catch (error) {
|
|
19956
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19957
|
+
}
|
|
19958
|
+
},
|
|
19959
|
+
/** 每页只扫描limit个稳定UUID记录;流式跳过正文,不回退完整get/list。 */
|
|
19960
|
+
async listDirectoryPage(query2) {
|
|
19961
|
+
try {
|
|
19962
|
+
assertNodeStateSchema(paths.root);
|
|
19963
|
+
if (!Number.isInteger(query2.limit) || query2.limit < 1 || query2.limit > 100 || !query2.projectId.trim()) throw new Error("SESSION_CURSOR_INVALID");
|
|
19964
|
+
let after2 = "";
|
|
19965
|
+
if (query2.cursor) {
|
|
19966
|
+
try {
|
|
19967
|
+
const value = JSON.parse(Buffer.from(query2.cursor, "base64url").toString("utf8"));
|
|
19968
|
+
if (value.view !== "session-directory" || value.root !== paths.root || value.mode !== productMode || value.projectId !== query2.projectId || typeof value.after !== "string") throw new Error();
|
|
19969
|
+
after2 = value.after;
|
|
19970
|
+
} catch {
|
|
19971
|
+
throw new Error("SESSION_CURSOR_INVALID");
|
|
19972
|
+
}
|
|
19973
|
+
}
|
|
19974
|
+
const names = import_node_fs20.default.existsSync(paths.sessionsDir) ? import_node_fs20.default.readdirSync(paths.sessionsDir).filter(function session(file) {
|
|
19975
|
+
return file.endsWith(".json") && file.slice(0, -5) > after2;
|
|
19976
|
+
}).sort() : [];
|
|
19977
|
+
const items = [];
|
|
19978
|
+
for (const name of names.slice(0, query2.limit)) {
|
|
19979
|
+
after2 = name.slice(0, -5);
|
|
19980
|
+
const session = await readSessionDirectoryRecord(filePath(after2), after2);
|
|
19981
|
+
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19982
|
+
if (session.projectId === query2.projectId) items.push({ id: session.id, ...session.title !== void 0 ? { title: session.title } : {} });
|
|
19983
|
+
}
|
|
19984
|
+
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;
|
|
19985
|
+
return { items, ...nextCursor ? { nextCursor } : {} };
|
|
19986
|
+
} catch (error) {
|
|
19987
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19988
|
+
}
|
|
19989
|
+
},
|
|
19990
|
+
/** 跨进程锁内确认不存在再创建,防止并发覆盖已有 Session。 */
|
|
19991
|
+
async createIfAbsent(session) {
|
|
19992
|
+
try {
|
|
19993
|
+
ensureDir();
|
|
19994
|
+
const next = normalizeNodeSession(session, session.id);
|
|
19995
|
+
if (next.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19996
|
+
return await withFileLock(filePath(session.id), function createLocked() {
|
|
19997
|
+
if (read(session.id)) return false;
|
|
19998
|
+
atomicReplace(filePath(session.id), JSON.stringify(next, null, 2));
|
|
19999
|
+
return true;
|
|
20000
|
+
}, { requireExitedOwner: true });
|
|
20001
|
+
} catch (error) {
|
|
20002
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19313
20003
|
}
|
|
19314
20004
|
},
|
|
19315
20005
|
/** 在同一临界区比较持久化身份并原子替换,拒绝底层直接越权写入。 */
|
|
19316
20006
|
async save(session) {
|
|
20007
|
+
let phase = "prepare";
|
|
19317
20008
|
try {
|
|
19318
20009
|
ensureDir();
|
|
20010
|
+
phase = "identity";
|
|
19319
20011
|
const next = normalizeNodeSession(session, session.id);
|
|
19320
20012
|
if (next.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
20013
|
+
phase = "lock";
|
|
19321
20014
|
await withFileLock(filePath(session.id), function saveLocked() {
|
|
20015
|
+
phase = "identity";
|
|
19322
20016
|
const previous = read(session.id);
|
|
19323
20017
|
if (previous) assertNodeSessionIdentity(previous, next);
|
|
19324
|
-
|
|
20018
|
+
return replaceSessionFile(filePath(session.id), JSON.stringify(next, null, 2));
|
|
19325
20019
|
});
|
|
19326
20020
|
} catch (error) {
|
|
19327
|
-
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
20021
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE", { operation: "session_save", target: "session", phase, ...getFileOperationDiagnostic(error) });
|
|
19328
20022
|
}
|
|
19329
20023
|
},
|
|
19330
20024
|
/** 只删除当前产品域记录;外围资源仍由 SessionResourceStore 先行清理。 */
|
|
@@ -19334,7 +20028,7 @@ function createNodeSessionStore(options) {
|
|
|
19334
20028
|
const target = filePath(id);
|
|
19335
20029
|
return await withFileLock(target, function deleteLocked() {
|
|
19336
20030
|
if (!read(id)) return false;
|
|
19337
|
-
|
|
20031
|
+
import_node_fs20.default.unlinkSync(target);
|
|
19338
20032
|
return true;
|
|
19339
20033
|
});
|
|
19340
20034
|
} catch (error) {
|
|
@@ -19346,11 +20040,16 @@ function createNodeSessionStore(options) {
|
|
|
19346
20040
|
|
|
19347
20041
|
// src/node/stores/node-transcript-store.ts
|
|
19348
20042
|
var import_promises3 = __toESM(require("node:fs/promises"));
|
|
19349
|
-
var
|
|
20043
|
+
var import_node_path17 = __toESM(require("node:path"));
|
|
19350
20044
|
var transcriptIndexes = /* @__PURE__ */ new Map();
|
|
19351
20045
|
var transcriptRootInitializations = /* @__PURE__ */ new Map();
|
|
20046
|
+
function parseTranscriptFileIdentity(value) {
|
|
20047
|
+
if (typeof value === "string" && /^\d{1,20}$/.test(value)) return BigInt(value).toString();
|
|
20048
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return String(value);
|
|
20049
|
+
throw new Error("THREAD_CURSOR_INVALID");
|
|
20050
|
+
}
|
|
19352
20051
|
function getTranscriptIndex(filePath) {
|
|
19353
|
-
const key2 =
|
|
20052
|
+
const key2 = import_node_path17.default.resolve(filePath);
|
|
19354
20053
|
const existing = transcriptIndexes.get(key2);
|
|
19355
20054
|
if (existing) return existing;
|
|
19356
20055
|
const created = { initialized: false, offset: 0, pendingBytes: Buffer.alloc(0), endsWithNewline: true, keys: /* @__PURE__ */ new Set() };
|
|
@@ -19361,7 +20060,7 @@ function getEnvelopeKey(envelope) {
|
|
|
19361
20060
|
return `${envelope.sessionId}\0${envelope.turnId}\0${envelope.seq}`;
|
|
19362
20061
|
}
|
|
19363
20062
|
function ensureTranscriptDirectory(stateRoot) {
|
|
19364
|
-
const key2 =
|
|
20063
|
+
const key2 = import_node_path17.default.resolve(stateRoot);
|
|
19365
20064
|
const existing = transcriptRootInitializations.get(key2);
|
|
19366
20065
|
if (existing) return existing;
|
|
19367
20066
|
const initialization = Promise.resolve().then(async function initializeTranscriptDirectory() {
|
|
@@ -19383,7 +20082,7 @@ async function readTranscriptBuffer(filePath) {
|
|
|
19383
20082
|
}
|
|
19384
20083
|
}
|
|
19385
20084
|
function reportCorruptedLine(filePath) {
|
|
19386
|
-
console.warn(`[DURABLE_JSONL_CORRUPTED] file=${
|
|
20085
|
+
console.warn(`[DURABLE_JSONL_CORRUPTED] file=${import_node_path17.default.basename(filePath)} records=1 lines=unknown`);
|
|
19387
20086
|
}
|
|
19388
20087
|
function parseTranscriptLine(filePath, line, index, parsed) {
|
|
19389
20088
|
if (line.length === 0) return;
|
|
@@ -19447,26 +20146,28 @@ async function readTranscriptTail(filePath, offset) {
|
|
|
19447
20146
|
}
|
|
19448
20147
|
}
|
|
19449
20148
|
async function refreshTranscriptIndex(filePath, index) {
|
|
19450
|
-
if (!index.initialized) {
|
|
19451
|
-
rebuildTranscriptIndex(filePath, await readTranscriptBuffer(filePath), index);
|
|
19452
|
-
return;
|
|
19453
|
-
}
|
|
19454
20149
|
let stats;
|
|
19455
20150
|
try {
|
|
19456
|
-
stats = await import_promises3.default.stat(filePath);
|
|
20151
|
+
stats = await import_promises3.default.stat(filePath, { bigint: true });
|
|
19457
20152
|
} catch (error) {
|
|
19458
20153
|
if (error.code !== "ENOENT") throw error;
|
|
19459
20154
|
rebuildTranscriptIndex(filePath, Buffer.alloc(0), index);
|
|
20155
|
+
index.identity = void 0;
|
|
20156
|
+
index.signature = void 0;
|
|
19460
20157
|
return;
|
|
19461
20158
|
}
|
|
19462
|
-
|
|
20159
|
+
const identity = `${stats.dev}:${stats.ino}:${stats.birthtimeNs}`;
|
|
20160
|
+
const signature = `${identity}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
|
|
20161
|
+
const size = Number(stats.size);
|
|
20162
|
+
if (!index.initialized || index.identity !== identity || size < index.offset || size === index.offset && index.signature !== signature) {
|
|
19463
20163
|
rebuildTranscriptIndex(filePath, await readTranscriptBuffer(filePath), index);
|
|
19464
|
-
|
|
20164
|
+
} else if (size > index.offset) {
|
|
20165
|
+
const tail = await readTranscriptTail(filePath, index.offset);
|
|
20166
|
+
consumeTranscriptBytes(filePath, tail.bytes, index);
|
|
20167
|
+
index.offset = tail.size;
|
|
19465
20168
|
}
|
|
19466
|
-
|
|
19467
|
-
|
|
19468
|
-
consumeTranscriptBytes(filePath, tail.bytes, index);
|
|
19469
|
-
index.offset = tail.size;
|
|
20169
|
+
index.identity = identity;
|
|
20170
|
+
index.signature = signature;
|
|
19470
20171
|
}
|
|
19471
20172
|
async function appendTranscriptEnvelope(filePath, envelope) {
|
|
19472
20173
|
const index = getTranscriptIndex(filePath);
|
|
@@ -19483,6 +20184,9 @@ async function appendTranscriptEnvelope(filePath, envelope) {
|
|
|
19483
20184
|
index.endsWithNewline = true;
|
|
19484
20185
|
index.offset += bytes.length;
|
|
19485
20186
|
index.keys.add(key2);
|
|
20187
|
+
const stats = await import_promises3.default.stat(filePath, { bigint: true });
|
|
20188
|
+
index.identity = `${stats.dev}:${stats.ino}:${stats.birthtimeNs}`;
|
|
20189
|
+
index.signature = `${index.identity}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
|
|
19486
20190
|
});
|
|
19487
20191
|
}
|
|
19488
20192
|
function removeAdjacentDuplicateEnvelopes(parsed) {
|
|
@@ -19499,7 +20203,9 @@ function removeAdjacentDuplicateEnvelopes(parsed) {
|
|
|
19499
20203
|
function createNodeTranscriptStore(options) {
|
|
19500
20204
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19501
20205
|
function filePath(sessionId) {
|
|
19502
|
-
|
|
20206
|
+
const target = safeFilePath(paths.transcriptsDir, sessionId, ".jsonl");
|
|
20207
|
+
assertSafeNodePath(paths.root, target);
|
|
20208
|
+
return target;
|
|
19503
20209
|
}
|
|
19504
20210
|
return {
|
|
19505
20211
|
async append(sessionId, envelope) {
|
|
@@ -19514,6 +20220,88 @@ function createNodeTranscriptStore(options) {
|
|
|
19514
20220
|
return removeAdjacentDuplicateEnvelopes(rebuildTranscriptIndex(target, await readTranscriptBuffer(target), index));
|
|
19515
20221
|
});
|
|
19516
20222
|
},
|
|
20223
|
+
/** 从字节游标增量读取 JSONL,不初始化目录、不持有写锁。 */
|
|
20224
|
+
async readPage(sessionId, options2) {
|
|
20225
|
+
if (!Number.isInteger(options2.limit) || options2.limit < 1 || options2.limit > 100) throw new Error("THREAD_CURSOR_INVALID");
|
|
20226
|
+
assertNodeStateSchema(paths.root);
|
|
20227
|
+
let offset = 0;
|
|
20228
|
+
let identity;
|
|
20229
|
+
if (options2.cursor) {
|
|
20230
|
+
try {
|
|
20231
|
+
const data = JSON.parse(Buffer.from(options2.cursor, "base64url").toString("utf8"));
|
|
20232
|
+
if (data.sessionId !== sessionId || !Number.isSafeInteger(data.offset) || data.offset < 0) throw new Error();
|
|
20233
|
+
offset = data.offset;
|
|
20234
|
+
identity = { dev: parseTranscriptFileIdentity(data.dev), ino: parseTranscriptFileIdentity(data.ino), size: data.size, stamp: data.stamp };
|
|
20235
|
+
if (data.size !== void 0 && (!Number.isSafeInteger(data.size) || data.size < offset) || data.stamp !== void 0 && typeof data.stamp !== "string") throw new Error();
|
|
20236
|
+
} catch {
|
|
20237
|
+
throw new Error("THREAD_CURSOR_INVALID");
|
|
20238
|
+
}
|
|
20239
|
+
}
|
|
20240
|
+
let handle;
|
|
20241
|
+
try {
|
|
20242
|
+
handle = await import_promises3.default.open(filePath(sessionId), "r");
|
|
20243
|
+
} catch (error) {
|
|
20244
|
+
if (error.code === "ENOENT") {
|
|
20245
|
+
if (offset === 0) return { items: [] };
|
|
20246
|
+
throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20247
|
+
}
|
|
20248
|
+
throw error;
|
|
20249
|
+
}
|
|
20250
|
+
try {
|
|
20251
|
+
const stats = await handle.stat({ bigint: true });
|
|
20252
|
+
const size = Number(stats.size);
|
|
20253
|
+
const dev = stats.dev.toString();
|
|
20254
|
+
const ino = stats.ino.toString();
|
|
20255
|
+
if (!Number.isSafeInteger(size)) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20256
|
+
const stamp = `${stats.mtimeNs}:${stats.ctimeNs}:${stats.birthtimeNs}`;
|
|
20257
|
+
if (identity && (identity.dev !== dev || identity.ino !== ino || identity.size === size && identity.stamp !== void 0 && identity.stamp !== stamp)) throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20258
|
+
if (offset > size) throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20259
|
+
if (offset > 0) {
|
|
20260
|
+
const previous = Buffer.alloc(1);
|
|
20261
|
+
await handle.read(previous, 0, 1, offset - 1);
|
|
20262
|
+
if (previous[0] !== 10) throw new Error("THREAD_CURSOR_INVALID");
|
|
20263
|
+
}
|
|
20264
|
+
const items = [];
|
|
20265
|
+
let position = offset;
|
|
20266
|
+
let lineStart = offset;
|
|
20267
|
+
let pending = Buffer.alloc(0);
|
|
20268
|
+
const chunk = Buffer.alloc(16 * 1024);
|
|
20269
|
+
while (position < size && items.length < options2.limit) {
|
|
20270
|
+
const result = await handle.read(chunk, 0, Math.min(chunk.length, size - position), position);
|
|
20271
|
+
if (!result.bytesRead) break;
|
|
20272
|
+
let start = 0;
|
|
20273
|
+
for (let i = 0; i < result.bytesRead; i++) {
|
|
20274
|
+
if (chunk[i] !== 10) continue;
|
|
20275
|
+
const line = pending.length ? Buffer.concat([pending, chunk.subarray(start, i)]) : chunk.subarray(start, i);
|
|
20276
|
+
if (line.length > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20277
|
+
let item;
|
|
20278
|
+
try {
|
|
20279
|
+
item = JSON.parse(line.toString("utf8"));
|
|
20280
|
+
} catch {
|
|
20281
|
+
throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20282
|
+
}
|
|
20283
|
+
if (item.sessionId !== sessionId) throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20284
|
+
items.push(item);
|
|
20285
|
+
lineStart = position + i + 1;
|
|
20286
|
+
pending = Buffer.alloc(0);
|
|
20287
|
+
start = i + 1;
|
|
20288
|
+
if (items.length === options2.limit) break;
|
|
20289
|
+
}
|
|
20290
|
+
if (items.length === options2.limit) {
|
|
20291
|
+
position = lineStart;
|
|
20292
|
+
break;
|
|
20293
|
+
}
|
|
20294
|
+
pending = Buffer.concat([pending, chunk.subarray(start, result.bytesRead)]);
|
|
20295
|
+
if (pending.length > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20296
|
+
position += result.bytesRead;
|
|
20297
|
+
}
|
|
20298
|
+
if (position >= size && pending.length > 0) throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20299
|
+
const cursor = Buffer.from(JSON.stringify({ sessionId, offset: lineStart, dev, ino, size, stamp })).toString("base64url");
|
|
20300
|
+
return { items, cursor, ...lineStart < size ? { nextCursor: cursor } : {} };
|
|
20301
|
+
} finally {
|
|
20302
|
+
await handle.close();
|
|
20303
|
+
}
|
|
20304
|
+
},
|
|
19517
20305
|
async deleteBySession(sessionId) {
|
|
19518
20306
|
await ensureTranscriptDirectory(paths.root);
|
|
19519
20307
|
const target = filePath(sessionId);
|
|
@@ -19535,20 +20323,20 @@ function createNodeTranscriptStore(options) {
|
|
|
19535
20323
|
}
|
|
19536
20324
|
|
|
19537
20325
|
// src/node/stores/node-turn-store.ts
|
|
19538
|
-
var
|
|
20326
|
+
var import_node_fs21 = __toESM(require("node:fs"));
|
|
19539
20327
|
function createNodeTurnStore(options) {
|
|
19540
20328
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19541
20329
|
function ensureDir() {
|
|
19542
20330
|
const state = ensureNodeStateRoot(paths.root);
|
|
19543
|
-
|
|
20331
|
+
import_node_fs21.default.mkdirSync(state.turnsDir, { recursive: true });
|
|
19544
20332
|
}
|
|
19545
20333
|
function filePath(turnId) {
|
|
19546
20334
|
return safeFilePath(paths.turnsDir, turnId, ".json");
|
|
19547
20335
|
}
|
|
19548
20336
|
return {
|
|
19549
20337
|
async get(id) {
|
|
19550
|
-
|
|
19551
|
-
return
|
|
20338
|
+
assertNodeStateSchema(paths.root);
|
|
20339
|
+
return readJsonFile(filePath(id));
|
|
19552
20340
|
},
|
|
19553
20341
|
async save(turn) {
|
|
19554
20342
|
ensureDir();
|
|
@@ -19557,9 +20345,10 @@ function createNodeTurnStore(options) {
|
|
|
19557
20345
|
});
|
|
19558
20346
|
},
|
|
19559
20347
|
async list(sessionId) {
|
|
19560
|
-
|
|
20348
|
+
assertNodeStateSchema(paths.root);
|
|
19561
20349
|
const turns = [];
|
|
19562
|
-
|
|
20350
|
+
if (!import_node_fs21.default.existsSync(paths.turnsDir)) return turns;
|
|
20351
|
+
for (const file of import_node_fs21.default.readdirSync(paths.turnsDir).filter((entry) => entry.endsWith(".json"))) {
|
|
19563
20352
|
const turn = readJsonFile(filePath(file.slice(0, -5)));
|
|
19564
20353
|
if (turn?.sessionId === sessionId) turns.push(turn);
|
|
19565
20354
|
}
|
|
@@ -19576,7 +20365,7 @@ function createNodeTurnStore(options) {
|
|
|
19576
20365
|
for (const turn of turns) {
|
|
19577
20366
|
const target = filePath(turn.id);
|
|
19578
20367
|
await withFileLock(target, () => {
|
|
19579
|
-
if (
|
|
20368
|
+
if (import_node_fs21.default.existsSync(target)) import_node_fs21.default.unlinkSync(target);
|
|
19580
20369
|
});
|
|
19581
20370
|
}
|
|
19582
20371
|
}
|
|
@@ -19584,12 +20373,12 @@ function createNodeTurnStore(options) {
|
|
|
19584
20373
|
}
|
|
19585
20374
|
|
|
19586
20375
|
// src/node/stores/node-lease-store.ts
|
|
19587
|
-
var
|
|
20376
|
+
var import_node_fs22 = __toESM(require("node:fs"));
|
|
19588
20377
|
function createNodeLeaseStore(options) {
|
|
19589
20378
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19590
20379
|
function ensureDir() {
|
|
19591
20380
|
const state = ensureNodeStateRoot(paths.root);
|
|
19592
|
-
|
|
20381
|
+
import_node_fs22.default.mkdirSync(state.leasesDir, { recursive: true });
|
|
19593
20382
|
}
|
|
19594
20383
|
function filePath(sessionId) {
|
|
19595
20384
|
return safeFilePath(paths.leasesDir, sessionId, ".json");
|
|
@@ -19598,6 +20387,11 @@ function createNodeLeaseStore(options) {
|
|
|
19598
20387
|
return now - record.lease.heartbeatAt <= staleAfterMs;
|
|
19599
20388
|
}
|
|
19600
20389
|
return {
|
|
20390
|
+
/** 原子替换文件允许无锁只读;禁止在状态查询中初始化或迁移存储。 */
|
|
20391
|
+
async readCurrent(sessionId) {
|
|
20392
|
+
const current = readJsonFile(filePath(sessionId));
|
|
20393
|
+
return current ? { turnId: current.turnId, lease: { ...current.lease } } : null;
|
|
20394
|
+
},
|
|
19601
20395
|
async acquire(input) {
|
|
19602
20396
|
ensureDir();
|
|
19603
20397
|
const target = filePath(input.sessionId);
|
|
@@ -19626,7 +20420,7 @@ function createNodeLeaseStore(options) {
|
|
|
19626
20420
|
return withFileLock(target, () => {
|
|
19627
20421
|
const current = readJsonFile(target);
|
|
19628
20422
|
if (!current || current.lease.leaseId !== input.lease.leaseId || current.lease.ownerId !== input.lease.ownerId) return false;
|
|
19629
|
-
if (
|
|
20423
|
+
if (import_node_fs22.default.existsSync(target)) import_node_fs22.default.unlinkSync(target);
|
|
19630
20424
|
return true;
|
|
19631
20425
|
});
|
|
19632
20426
|
},
|
|
@@ -19634,7 +20428,7 @@ function createNodeLeaseStore(options) {
|
|
|
19634
20428
|
ensureDir();
|
|
19635
20429
|
const target = filePath(sessionId);
|
|
19636
20430
|
await withFileLock(target, () => {
|
|
19637
|
-
if (
|
|
20431
|
+
if (import_node_fs22.default.existsSync(target)) import_node_fs22.default.unlinkSync(target);
|
|
19638
20432
|
});
|
|
19639
20433
|
}
|
|
19640
20434
|
};
|
|
@@ -19649,26 +20443,26 @@ function createNodeClock() {
|
|
|
19649
20443
|
}
|
|
19650
20444
|
|
|
19651
20445
|
// src/node/stores/node-job-store.ts
|
|
19652
|
-
var
|
|
19653
|
-
var
|
|
20446
|
+
var import_node_fs23 = __toESM(require("node:fs"));
|
|
20447
|
+
var import_node_path18 = __toESM(require("node:path"));
|
|
19654
20448
|
function createNodeJobStore(options) {
|
|
19655
20449
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19656
20450
|
function ensureDir() {
|
|
19657
20451
|
const state = ensureNodeStateRoot(paths.root);
|
|
19658
|
-
|
|
20452
|
+
import_node_fs23.default.mkdirSync(state.jobsDir, { recursive: true });
|
|
19659
20453
|
}
|
|
19660
20454
|
function filePath(id) {
|
|
19661
20455
|
return safeFilePath(paths.jobsDir, id, ".json");
|
|
19662
20456
|
}
|
|
19663
20457
|
function sessionLockPath(sessionId) {
|
|
19664
|
-
return safeFilePath(
|
|
20458
|
+
return safeFilePath(import_node_path18.default.join(paths.jobsDir, ".session-locks"), sessionId, ".guard");
|
|
19665
20459
|
}
|
|
19666
20460
|
function sameOwner(first, second) {
|
|
19667
20461
|
return first?.runtimeInstanceId === second.runtimeInstanceId && first.hostProcessId === second.hostProcessId;
|
|
19668
20462
|
}
|
|
19669
20463
|
function readAll() {
|
|
19670
20464
|
ensureDir();
|
|
19671
|
-
return
|
|
20465
|
+
return import_node_fs23.default.readdirSync(paths.jobsDir).filter((file) => file.endsWith(".json")).flatMap((file) => {
|
|
19672
20466
|
const job = readJsonFile(filePath(file.slice(0, -5)));
|
|
19673
20467
|
return job ? [job] : [];
|
|
19674
20468
|
});
|
|
@@ -19681,7 +20475,7 @@ function createNodeJobStore(options) {
|
|
|
19681
20475
|
async create(job) {
|
|
19682
20476
|
ensureDir();
|
|
19683
20477
|
return withFileLock(filePath(job.id), function createIfMissing() {
|
|
19684
|
-
if (
|
|
20478
|
+
if (import_node_fs23.default.existsSync(filePath(job.id))) return false;
|
|
19685
20479
|
atomicReplace(filePath(job.id), JSON.stringify(job, null, 2));
|
|
19686
20480
|
return true;
|
|
19687
20481
|
});
|
|
@@ -19710,7 +20504,7 @@ function createNodeJobStore(options) {
|
|
|
19710
20504
|
for (const job of await this.listBySession(sessionId)) {
|
|
19711
20505
|
const target = filePath(job.id);
|
|
19712
20506
|
await withFileLock(target, () => {
|
|
19713
|
-
if (
|
|
20507
|
+
if (import_node_fs23.default.existsSync(target)) import_node_fs23.default.unlinkSync(target);
|
|
19714
20508
|
});
|
|
19715
20509
|
}
|
|
19716
20510
|
},
|
|
@@ -19738,43 +20532,43 @@ function createNodeJobOwnerProbe() {
|
|
|
19738
20532
|
}
|
|
19739
20533
|
|
|
19740
20534
|
// src/node/stores/node-file-mutation-store.ts
|
|
19741
|
-
var
|
|
19742
|
-
var
|
|
19743
|
-
var
|
|
20535
|
+
var import_node_crypto10 = require("node:crypto");
|
|
20536
|
+
var import_node_fs24 = __toESM(require("node:fs"));
|
|
20537
|
+
var import_node_path19 = __toESM(require("node:path"));
|
|
19744
20538
|
var MAX_FILE_SNAPSHOT_BYTES = 512 * 1024;
|
|
19745
20539
|
var MAX_SESSION_SNAPSHOT_BYTES = 5 * 1024 * 1024;
|
|
19746
20540
|
function sha256(content) {
|
|
19747
|
-
return (0,
|
|
20541
|
+
return (0, import_node_crypto10.createHash)("sha256").update(content).digest("hex");
|
|
19748
20542
|
}
|
|
19749
20543
|
function writeBlob(blobPath, content) {
|
|
19750
|
-
if (
|
|
19751
|
-
|
|
19752
|
-
const temporary = `${blobPath}.${process.pid}.${(0,
|
|
20544
|
+
if (import_node_fs24.default.existsSync(blobPath)) return;
|
|
20545
|
+
import_node_fs24.default.mkdirSync(import_node_path19.default.dirname(blobPath), { recursive: true });
|
|
20546
|
+
const temporary = `${blobPath}.${process.pid}.${(0, import_node_crypto10.randomUUID)()}.tmp`;
|
|
19753
20547
|
try {
|
|
19754
|
-
const descriptor =
|
|
20548
|
+
const descriptor = import_node_fs24.default.openSync(temporary, "wx");
|
|
19755
20549
|
try {
|
|
19756
|
-
|
|
19757
|
-
|
|
20550
|
+
import_node_fs24.default.writeFileSync(descriptor, content);
|
|
20551
|
+
import_node_fs24.default.fsyncSync(descriptor);
|
|
19758
20552
|
} finally {
|
|
19759
|
-
|
|
20553
|
+
import_node_fs24.default.closeSync(descriptor);
|
|
19760
20554
|
}
|
|
19761
20555
|
try {
|
|
19762
|
-
|
|
20556
|
+
import_node_fs24.default.renameSync(temporary, blobPath);
|
|
19763
20557
|
} catch (error) {
|
|
19764
|
-
if (!
|
|
20558
|
+
if (!import_node_fs24.default.existsSync(blobPath)) throw error;
|
|
19765
20559
|
}
|
|
19766
20560
|
} finally {
|
|
19767
|
-
if (
|
|
20561
|
+
if (import_node_fs24.default.existsSync(temporary)) import_node_fs24.default.unlinkSync(temporary);
|
|
19768
20562
|
}
|
|
19769
20563
|
}
|
|
19770
20564
|
function createNodeFileMutationStore(options) {
|
|
19771
20565
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19772
20566
|
function ensureDir() {
|
|
19773
20567
|
const state = ensureNodeStateRoot(paths.root);
|
|
19774
|
-
|
|
19775
|
-
|
|
19776
|
-
|
|
19777
|
-
|
|
20568
|
+
import_node_fs24.default.mkdirSync(state.mutationsDir, { recursive: true });
|
|
20569
|
+
import_node_fs24.default.mkdirSync(state.mutationBlobsDir, { recursive: true });
|
|
20570
|
+
import_node_fs24.default.mkdirSync(state.mutationLocksDir, { recursive: true });
|
|
20571
|
+
import_node_fs24.default.mkdirSync(state.undoTransactionsDir, { recursive: true });
|
|
19778
20572
|
}
|
|
19779
20573
|
function mutationPath(id) {
|
|
19780
20574
|
return safeFilePath(paths.mutationsDir, id, ".json");
|
|
@@ -19788,9 +20582,9 @@ function createNodeFileMutationStore(options) {
|
|
|
19788
20582
|
}
|
|
19789
20583
|
function readAll() {
|
|
19790
20584
|
ensureDir();
|
|
19791
|
-
return
|
|
20585
|
+
return import_node_fs24.default.readdirSync(paths.mutationsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
|
|
19792
20586
|
try {
|
|
19793
|
-
return [JSON.parse(
|
|
20587
|
+
return [JSON.parse(import_node_fs24.default.readFileSync(mutationPath(entry.slice(0, -5)), "utf8"))];
|
|
19794
20588
|
} catch {
|
|
19795
20589
|
return [];
|
|
19796
20590
|
}
|
|
@@ -19798,9 +20592,9 @@ function createNodeFileMutationStore(options) {
|
|
|
19798
20592
|
}
|
|
19799
20593
|
function readTransactions() {
|
|
19800
20594
|
ensureDir();
|
|
19801
|
-
return
|
|
20595
|
+
return import_node_fs24.default.readdirSync(paths.undoTransactionsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
|
|
19802
20596
|
try {
|
|
19803
|
-
return [JSON.parse(
|
|
20597
|
+
return [JSON.parse(import_node_fs24.default.readFileSync(transactionPath(entry.slice(0, -5)), "utf8"))];
|
|
19804
20598
|
} catch {
|
|
19805
20599
|
return [];
|
|
19806
20600
|
}
|
|
@@ -19808,7 +20602,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19808
20602
|
}
|
|
19809
20603
|
function sessionBlobBytes(sessionId) {
|
|
19810
20604
|
const refs3 = new Set(readAll().filter((item) => item.sessionId === sessionId).flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
|
|
19811
|
-
return [...refs3].reduce((total, ref) => total + (
|
|
20605
|
+
return [...refs3].reduce((total, ref) => total + (import_node_fs24.default.statSync(blobPath(ref), { throwIfNoEntry: false })?.size ?? 0), 0);
|
|
19812
20606
|
}
|
|
19813
20607
|
return {
|
|
19814
20608
|
async prepare(input) {
|
|
@@ -19818,13 +20612,13 @@ function createNodeFileMutationStore(options) {
|
|
|
19818
20612
|
const refs3 = /* @__PURE__ */ new Map();
|
|
19819
20613
|
if (input.before) refs3.set(beforeRef, input.before);
|
|
19820
20614
|
if (input.after) refs3.set(afterRef, input.after);
|
|
19821
|
-
const additionalBytes = [...refs3.entries()].filter(([ref]) => !
|
|
20615
|
+
const additionalBytes = [...refs3.entries()].filter(([ref]) => !import_node_fs24.default.existsSync(blobPath(ref))).reduce((total, [, content]) => total + content.byteLength, 0);
|
|
19822
20616
|
const byteCount = (input.before?.byteLength ?? 0) + (input.after?.byteLength ?? 0);
|
|
19823
20617
|
const binary2 = Boolean(input.before?.includes(0) || input.after?.includes(0));
|
|
19824
20618
|
const reversible = !binary2 && byteCount <= MAX_FILE_SNAPSHOT_BYTES && sessionBlobBytes(input.sessionId) + additionalBytes <= MAX_SESSION_SNAPSHOT_BYTES;
|
|
19825
20619
|
if (reversible) for (const [ref, content] of refs3) writeBlob(blobPath(ref), content);
|
|
19826
20620
|
const mutation = {
|
|
19827
|
-
id: (0,
|
|
20621
|
+
id: (0, import_node_crypto10.randomUUID)(),
|
|
19828
20622
|
sessionId: input.sessionId,
|
|
19829
20623
|
turnId: input.turnId,
|
|
19830
20624
|
toolCallId: input.toolCallId,
|
|
@@ -19849,7 +20643,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19849
20643
|
async getBlob(ref) {
|
|
19850
20644
|
ensureDir();
|
|
19851
20645
|
try {
|
|
19852
|
-
const content =
|
|
20646
|
+
const content = import_node_fs24.default.readFileSync(blobPath(ref));
|
|
19853
20647
|
return sha256(content) === ref ? content : null;
|
|
19854
20648
|
} catch {
|
|
19855
20649
|
return null;
|
|
@@ -19867,14 +20661,14 @@ function createNodeFileMutationStore(options) {
|
|
|
19867
20661
|
},
|
|
19868
20662
|
async deleteBySession(sessionId) {
|
|
19869
20663
|
ensureDir();
|
|
19870
|
-
for (const mutation of readAll().filter((item) => item.sessionId === sessionId))
|
|
19871
|
-
for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId))
|
|
20664
|
+
for (const mutation of readAll().filter((item) => item.sessionId === sessionId)) import_node_fs24.default.rmSync(mutationPath(mutation.id), { force: true });
|
|
20665
|
+
for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId)) import_node_fs24.default.rmSync(transactionPath(transaction.id), { force: true });
|
|
19872
20666
|
const referenced = new Set(readAll().flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
|
|
19873
|
-
for (const entry of
|
|
20667
|
+
for (const entry of import_node_fs24.default.readdirSync(paths.mutationBlobsDir).filter((item) => item.endsWith(".blob"))) if (!referenced.has(entry.slice(0, -5))) import_node_fs24.default.rmSync(import_node_path19.default.join(paths.mutationBlobsDir, entry), { force: true });
|
|
19874
20668
|
},
|
|
19875
20669
|
async withWorkspaceLock(workspaceRoot, operation, canonicalTargets = []) {
|
|
19876
20670
|
ensureDir();
|
|
19877
|
-
const lockId = (0,
|
|
20671
|
+
const lockId = (0, import_node_crypto10.createHash)("sha256").update(import_node_path19.default.resolve(workspaceRoot)).digest("hex");
|
|
19878
20672
|
return withFileLock(safeFilePath(paths.mutationLocksDir, lockId, ".lock-target"), function lockTargets() {
|
|
19879
20673
|
return withNodeFileMutationLocks(canonicalTargets, operation);
|
|
19880
20674
|
}, { requireExitedOwner: true });
|
|
@@ -19883,32 +20677,94 @@ function createNodeFileMutationStore(options) {
|
|
|
19883
20677
|
}
|
|
19884
20678
|
|
|
19885
20679
|
// src/node/stores/node-session-resource-store.ts
|
|
19886
|
-
var
|
|
19887
|
-
var
|
|
20680
|
+
var import_node_fs25 = __toESM(require("node:fs"));
|
|
20681
|
+
var import_node_path20 = __toESM(require("node:path"));
|
|
19888
20682
|
function isAttachmentSessionId(sessionId) {
|
|
19889
20683
|
return /^[0-9a-f-]{36}$/iu.test(sessionId);
|
|
19890
20684
|
}
|
|
19891
20685
|
function createNodeSessionResourceStore(workspaceRoot) {
|
|
19892
20686
|
const root = canonicalizeNodePath(workspaceRoot);
|
|
19893
|
-
const uploadsRoot =
|
|
20687
|
+
const uploadsRoot = import_node_path20.default.join(root, ".local", "session-uploads");
|
|
19894
20688
|
return {
|
|
19895
20689
|
async deleteBySession(sessionId) {
|
|
19896
20690
|
if (!isAttachmentSessionId(sessionId)) return;
|
|
19897
|
-
const target =
|
|
19898
|
-
if (!target.startsWith(`${uploadsRoot}${
|
|
19899
|
-
|
|
20691
|
+
const target = import_node_path20.default.join(uploadsRoot, sessionId);
|
|
20692
|
+
if (!target.startsWith(`${uploadsRoot}${import_node_path20.default.sep}`)) throw new Error("SESSION_RESOURCE_PATH_INVALID");
|
|
20693
|
+
import_node_fs25.default.rmSync(target, { recursive: true, force: true, maxRetries: 2 });
|
|
20694
|
+
}
|
|
20695
|
+
};
|
|
20696
|
+
}
|
|
20697
|
+
|
|
20698
|
+
// src/node/stores/node-session-image-store.ts
|
|
20699
|
+
var import_node_crypto11 = __toESM(require("node:crypto"));
|
|
20700
|
+
var import_node_fs26 = __toESM(require("node:fs"));
|
|
20701
|
+
var import_node_path21 = __toESM(require("node:path"));
|
|
20702
|
+
var import_core16 = require("@autopilot-agent/core");
|
|
20703
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
20704
|
+
function sessionDirectory(root, sessionId, create3) {
|
|
20705
|
+
if (!UUID.test(sessionId)) throw new Error("SESSION_IMAGE_INVALID");
|
|
20706
|
+
let current = import_node_fs26.default.realpathSync(root);
|
|
20707
|
+
for (const part of [".local", "session-uploads", sessionId]) {
|
|
20708
|
+
current = import_node_path21.default.join(current, part);
|
|
20709
|
+
if (create3) {
|
|
20710
|
+
try {
|
|
20711
|
+
import_node_fs26.default.mkdirSync(current);
|
|
20712
|
+
} catch (error) {
|
|
20713
|
+
if (error.code !== "EEXIST") throw error;
|
|
20714
|
+
}
|
|
20715
|
+
}
|
|
20716
|
+
const stat = import_node_fs26.default.lstatSync(current);
|
|
20717
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("SESSION_IMAGE_INVALID");
|
|
20718
|
+
}
|
|
20719
|
+
return current;
|
|
20720
|
+
}
|
|
20721
|
+
function createNodeSessionImageStore(workspaceRoot) {
|
|
20722
|
+
return {
|
|
20723
|
+
/** 校验并保存规范化副本与不可变元数据。 */
|
|
20724
|
+
async put(input) {
|
|
20725
|
+
let normalized;
|
|
20726
|
+
try {
|
|
20727
|
+
normalized = await (0, import_core16.normalizeWorkImage)({ bytes: input.bytes, mimeType: input.mimeType });
|
|
20728
|
+
} catch {
|
|
20729
|
+
throw new Error("SESSION_IMAGE_INVALID");
|
|
20730
|
+
}
|
|
20731
|
+
const directory = sessionDirectory(workspaceRoot, input.sessionId, true);
|
|
20732
|
+
const id = import_node_crypto11.default.randomUUID();
|
|
20733
|
+
const extension = normalized.mimeType === "image/jpeg" ? ".jpg" : normalized.mimeType === "image/png" ? ".png" : normalized.mimeType === "image/webp" ? ".webp" : ".gif";
|
|
20734
|
+
const bytes = Buffer.from(normalized.bytes);
|
|
20735
|
+
const image = { id, name: import_node_path21.default.basename(input.name), mimeType: normalized.mimeType, relativePath: `.local/session-uploads/${input.sessionId}/${id}${extension}`, sha256: import_node_crypto11.default.createHash("sha256").update(bytes).digest("hex"), width: normalized.width, height: normalized.height, bytes: bytes.length, gifFirstFrame: normalized.gifFirstFrame };
|
|
20736
|
+
import_node_fs26.default.writeFileSync(import_node_path21.default.join(directory, `${id}${extension}`), bytes, { flag: "wx" });
|
|
20737
|
+
import_node_fs26.default.writeFileSync(import_node_path21.default.join(directory, `${id}.json`), JSON.stringify(image), { flag: "wx" });
|
|
20738
|
+
return image;
|
|
20739
|
+
},
|
|
20740
|
+
/** 按会话和图片标识读取并复核文件哈希。 */
|
|
20741
|
+
async read(input) {
|
|
20742
|
+
if (!UUID.test(input.id)) throw new Error("SESSION_IMAGE_INVALID");
|
|
20743
|
+
const directory = sessionDirectory(workspaceRoot, input.sessionId, false);
|
|
20744
|
+
const metadataPath = import_node_path21.default.join(directory, `${input.id}.json`);
|
|
20745
|
+
const metadataStat = import_node_fs26.default.lstatSync(metadataPath);
|
|
20746
|
+
if (!metadataStat.isFile() || metadataStat.isSymbolicLink() || metadataStat.size > 4096) throw new Error("SESSION_IMAGE_INVALID");
|
|
20747
|
+
const image = JSON.parse(import_node_fs26.default.readFileSync(metadataPath, "utf8"));
|
|
20748
|
+
const extension = image.mimeType === "image/jpeg" ? ".jpg" : image.mimeType === "image/png" ? ".png" : image.mimeType === "image/webp" ? ".webp" : image.mimeType === "image/gif" ? ".gif" : "";
|
|
20749
|
+
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");
|
|
20750
|
+
const filePath = import_node_path21.default.join(directory, `${input.id}${extension}`);
|
|
20751
|
+
const stat = import_node_fs26.default.lstatSync(filePath);
|
|
20752
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== image.bytes) throw new Error("SESSION_IMAGE_INVALID");
|
|
20753
|
+
const bytes = import_node_fs26.default.readFileSync(filePath);
|
|
20754
|
+
if (bytes.length !== image.bytes || import_node_crypto11.default.createHash("sha256").update(bytes).digest("hex") !== image.sha256) throw new Error("SESSION_IMAGE_INVALID");
|
|
20755
|
+
return { image, bytes };
|
|
19900
20756
|
}
|
|
19901
20757
|
};
|
|
19902
20758
|
}
|
|
19903
20759
|
|
|
19904
20760
|
// src/node/stores/node-user-question-store.ts
|
|
19905
|
-
var
|
|
20761
|
+
var import_node_fs27 = __toESM(require("node:fs"));
|
|
19906
20762
|
function createNodeUserQuestionStore(options) {
|
|
19907
20763
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19908
20764
|
const recordsFile = `${paths.questionsDir}/requests.jsonl`;
|
|
19909
20765
|
function ensureDir() {
|
|
19910
20766
|
const state = ensureNodeStateRoot(paths.root);
|
|
19911
|
-
|
|
20767
|
+
import_node_fs27.default.mkdirSync(state.questionsDir, { recursive: true });
|
|
19912
20768
|
}
|
|
19913
20769
|
function answersEqual(left, right) {
|
|
19914
20770
|
return JSON.stringify(left) === JSON.stringify(right);
|
|
@@ -19973,6 +20829,7 @@ function createNodeRuntimePorts(options) {
|
|
|
19973
20829
|
}
|
|
19974
20830
|
return {
|
|
19975
20831
|
hostMutationProtection: options.productMode === "chat" ? void 0 : createNodeHostMutationProtection(options),
|
|
20832
|
+
threadStore: createNodeThreadStore(options.stateRoot),
|
|
19976
20833
|
sessionStore: createNodeSessionStore({ ...storeOptions, productMode: options.productMode }),
|
|
19977
20834
|
checkpointStore: createNodeCheckpointStore(storeOptions),
|
|
19978
20835
|
transcriptStore: createNodeTranscriptStore(storeOptions),
|
|
@@ -19996,6 +20853,7 @@ function createNodeRuntimePorts(options) {
|
|
|
19996
20853
|
throw new NodeChatError("CHAT_ATTACHMENT_STORE_REQUIRED");
|
|
19997
20854
|
}
|
|
19998
20855
|
} : createNodeSessionResourceStore(options.workspaceRoot ?? options.cwd ?? process.cwd()),
|
|
20856
|
+
sessionImageStore: options.productMode === "chat" || !options.workspaceRoot ? void 0 : createNodeSessionImageStore(options.workspaceRoot),
|
|
19999
20857
|
userQuestionStore: createNodeUserQuestionStore(storeOptions),
|
|
20000
20858
|
/**
|
|
20001
20859
|
* Stage 2:Work 模式装配真实 SRT adapter(绑定 canonical workspaceRoot;tempRoot
|
|
@@ -20004,7 +20862,7 @@ function createNodeRuntimePorts(options) {
|
|
|
20004
20862
|
* Talk-Plan1022 S1:Windows 宿主执行模式装配宿主执行 port——不加载 SRT、不要求
|
|
20005
20863
|
* provision,进程调用经用户逐次审批后在宿主直接执行;macOS 装配保持不变。
|
|
20006
20864
|
*/
|
|
20007
|
-
sandboxPort: options.productMode === "chat" || options.workspaceRoot === void 0 ? (0,
|
|
20865
|
+
sandboxPort: options.productMode === "chat" || options.workspaceRoot === void 0 ? (0, import_core17.createUnavailableSandboxPort)() : process.platform === "win32" ? createNodeHostExecutionSandboxPort() : createNodeSandboxPort({
|
|
20008
20866
|
workspaceRoot: options.workspaceRoot,
|
|
20009
20867
|
stateRoot: options.stateRoot,
|
|
20010
20868
|
...options.sandboxTempRoot !== void 0 ? { tempRoot: options.sandboxTempRoot } : {}
|
|
@@ -20012,10 +20870,16 @@ function createNodeRuntimePorts(options) {
|
|
|
20012
20870
|
};
|
|
20013
20871
|
}
|
|
20014
20872
|
|
|
20873
|
+
// src/node/runtime-owner.ts
|
|
20874
|
+
var import_node_path22 = require("node:path");
|
|
20875
|
+
function withNodeRuntimeOwner(stateRoot, operation) {
|
|
20876
|
+
return withFileLock((0, import_node_path22.join)(stateRoot, "managed-runtime-owner"), operation, { requireExitedOwner: true });
|
|
20877
|
+
}
|
|
20878
|
+
|
|
20015
20879
|
// src/node/stores/node-chat-attachment-store.ts
|
|
20016
|
-
var
|
|
20017
|
-
var
|
|
20018
|
-
var
|
|
20880
|
+
var import_node_fs28 = __toESM(require("node:fs"));
|
|
20881
|
+
var import_node_path23 = __toESM(require("node:path"));
|
|
20882
|
+
var import_node_crypto12 = require("node:crypto");
|
|
20019
20883
|
var CHAT_ATTACHMENT_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
20020
20884
|
var MAX_BYTES = 20 * 1024 * 1024;
|
|
20021
20885
|
var IMAGE_BYTES = 5 * 1024 * 1024;
|
|
@@ -20028,7 +20892,7 @@ function sessionKey(id) {
|
|
|
20028
20892
|
return id;
|
|
20029
20893
|
}
|
|
20030
20894
|
function digest(bytes) {
|
|
20031
|
-
return (0,
|
|
20895
|
+
return (0, import_node_crypto12.createHash)("sha256").update(bytes).digest("hex");
|
|
20032
20896
|
}
|
|
20033
20897
|
function detectMime(bytes) {
|
|
20034
20898
|
if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png";
|
|
@@ -20054,12 +20918,12 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20054
20918
|
const { paths, sessionStore } = options;
|
|
20055
20919
|
const now = options.now ?? Date.now;
|
|
20056
20920
|
const root = paths.attachmentsRoot;
|
|
20057
|
-
const dataRoot =
|
|
20058
|
-
const retiredRoot =
|
|
20059
|
-
const deletingRoot =
|
|
20060
|
-
const lock =
|
|
20921
|
+
const dataRoot = import_node_path23.default.join(root, "sessions");
|
|
20922
|
+
const retiredRoot = import_node_path23.default.join(root, "retired");
|
|
20923
|
+
const deletingRoot = import_node_path23.default.join(root, "deleting");
|
|
20924
|
+
const lock = import_node_path23.default.join(root, "lifecycle");
|
|
20061
20925
|
function ensure() {
|
|
20062
|
-
assertSafeNodePath(
|
|
20926
|
+
assertSafeNodePath(import_node_path23.default.dirname(paths.root), paths.root);
|
|
20063
20927
|
for (const directory of [root, dataRoot, retiredRoot, deletingRoot]) ensureChatDirectory(paths.root, directory);
|
|
20064
20928
|
assertSafeNodePath(root, `${lock}.lock`);
|
|
20065
20929
|
}
|
|
@@ -20081,9 +20945,9 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20081
20945
|
}
|
|
20082
20946
|
function isSessionDeleting(sessionId) {
|
|
20083
20947
|
try {
|
|
20084
|
-
const target =
|
|
20948
|
+
const target = import_node_path23.default.join(deletingRoot, `${sessionKey(sessionId)}.json`);
|
|
20085
20949
|
assertSafeNodePath(root, target);
|
|
20086
|
-
return
|
|
20950
|
+
return import_node_fs28.default.existsSync(target);
|
|
20087
20951
|
} catch (error) {
|
|
20088
20952
|
throw toNodeBoundaryError(error, "CHAT_ATTACHMENT_UNAVAILABLE");
|
|
20089
20953
|
}
|
|
@@ -20100,16 +20964,16 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20100
20964
|
if (session?.productMode !== "chat" || !["none", "web"].includes(session.chatRetrievalMode ?? "")) throw new NodeChatError("CHAT_UPLOAD_MODE_MISMATCH");
|
|
20101
20965
|
}
|
|
20102
20966
|
function records(sessionId) {
|
|
20103
|
-
const directory =
|
|
20967
|
+
const directory = import_node_path23.default.join(dataRoot, sessionKey(sessionId));
|
|
20104
20968
|
assertSafeNodePath(root, directory);
|
|
20105
|
-
if (!
|
|
20969
|
+
if (!import_node_fs28.default.existsSync(directory)) return [];
|
|
20106
20970
|
const result = [];
|
|
20107
|
-
for (const ref of
|
|
20971
|
+
for (const ref of import_node_fs28.default.readdirSync(directory)) {
|
|
20108
20972
|
if (!opaque.test(ref)) unavailable();
|
|
20109
|
-
const target =
|
|
20973
|
+
const target = import_node_path23.default.join(directory, ref, "metadata.json");
|
|
20110
20974
|
assertSafeNodePath(root, target);
|
|
20111
|
-
if (!
|
|
20112
|
-
const record = JSON.parse(
|
|
20975
|
+
if (!import_node_fs28.default.statSync(target).isFile() || import_node_fs28.default.statSync(target).size > 16384) unavailable();
|
|
20976
|
+
const record = JSON.parse(import_node_fs28.default.readFileSync(target, "utf8"));
|
|
20113
20977
|
if (record.ref !== ref || record.sessionId !== sessionId || record.status !== "active" || !["image", "document"].includes(record.kind) || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0 || record.expiresAt !== record.createdAt + CHAT_ATTACHMENT_TTL_MS || !Array.isArray(record.pages) || record.pages.length > 20) unavailable();
|
|
20114
20978
|
for (const page of record.pages) if (!opaque.test(page.ref)) unavailable();
|
|
20115
20979
|
result.push(record);
|
|
@@ -20120,7 +20984,7 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20120
20984
|
return { ref: record.ref, sessionId: record.sessionId, kind: record.kind, expiresAt: record.expiresAt };
|
|
20121
20985
|
}
|
|
20122
20986
|
function active(record) {
|
|
20123
|
-
return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !
|
|
20987
|
+
return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !import_node_fs28.default.existsSync(import_node_path23.default.join(retiredRoot, `${record.ref}.json`));
|
|
20124
20988
|
}
|
|
20125
20989
|
function sanitizeSession(session) {
|
|
20126
20990
|
try {
|
|
@@ -20159,17 +21023,17 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20159
21023
|
return !opaque.test(ref);
|
|
20160
21024
|
}
|
|
20161
21025
|
)) unavailable();
|
|
20162
|
-
const directory =
|
|
21026
|
+
const directory = import_node_path23.default.join(dataRoot, item.sessionId, item.ref);
|
|
20163
21027
|
assertSafeNodePath(root, directory);
|
|
20164
|
-
|
|
21028
|
+
import_node_fs28.default.rmSync(directory, { recursive: true, force: true });
|
|
20165
21029
|
await removePresentationRefs(item.sessionId, item.refs);
|
|
20166
|
-
|
|
21030
|
+
import_node_fs28.default.rmSync(import_node_path23.default.join(retiredRoot, `${item.ref}.json`), { force: true });
|
|
20167
21031
|
}
|
|
20168
21032
|
async function retire(record) {
|
|
20169
21033
|
const item = { sessionId: record.sessionId, ref: record.ref, refs: [record.ref, ...record.pages.map(function pageRef(page) {
|
|
20170
21034
|
return page.ref;
|
|
20171
21035
|
})] };
|
|
20172
|
-
atomicReplace(
|
|
21036
|
+
atomicReplace(import_node_path23.default.join(retiredRoot, `${record.ref}.json`), JSON.stringify(item));
|
|
20173
21037
|
await finishRetirement(item);
|
|
20174
21038
|
}
|
|
20175
21039
|
async function put(input) {
|
|
@@ -20201,32 +21065,32 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20201
21065
|
await requireSession(input.sessionId);
|
|
20202
21066
|
const createdAt = now();
|
|
20203
21067
|
if (!Number.isSafeInteger(createdAt) || createdAt < 0) unavailable();
|
|
20204
|
-
const ref = (0,
|
|
20205
|
-
const parent =
|
|
21068
|
+
const ref = (0, import_node_crypto12.randomUUID)();
|
|
21069
|
+
const parent = import_node_path23.default.join(dataRoot, sessionKey(input.sessionId));
|
|
20206
21070
|
ensureChatDirectory(root, parent);
|
|
20207
|
-
const staging =
|
|
21071
|
+
const staging = import_node_path23.default.join(root, `staging-${ref}`);
|
|
20208
21072
|
const record = { ref, sessionId: input.sessionId, kind, mimeType, byteLength: bytes.length, sha256: digest(bytes), createdAt, expiresAt: createdAt + CHAT_ATTACHMENT_TTL_MS, status: "active", displayName: input.displayName.split(/[\\/]/).at(-1).replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 120) || "\u9644\u4EF6", pages: [] };
|
|
20209
21073
|
try {
|
|
20210
21074
|
ensureChatDirectory(root, staging);
|
|
20211
|
-
|
|
21075
|
+
import_node_fs28.default.writeFileSync(import_node_path23.default.join(staging, "content"), bytes, { flag: "wx", mode: 384 });
|
|
20212
21076
|
let pageBytes = 0;
|
|
20213
21077
|
for (const inputPage of parsed?.pages ?? []) {
|
|
20214
21078
|
const page = Buffer.from(inputPage);
|
|
20215
21079
|
const type2 = detectMime(page);
|
|
20216
21080
|
pageBytes += page.length;
|
|
20217
21081
|
if (!type2.startsWith("image/") || !page.length || page.length > IMAGE_BYTES || pageBytes > MAX_BYTES) unavailable();
|
|
20218
|
-
const pageRef = (0,
|
|
20219
|
-
|
|
21082
|
+
const pageRef = (0, import_node_crypto12.randomUUID)();
|
|
21083
|
+
import_node_fs28.default.writeFileSync(import_node_path23.default.join(staging, pageRef), page, { flag: "wx", mode: 384 });
|
|
20220
21084
|
record.pages.push({ ref: pageRef, mimeType: type2, byteLength: page.length, sha256: digest(page) });
|
|
20221
21085
|
}
|
|
20222
|
-
if (parsed)
|
|
20223
|
-
|
|
21086
|
+
if (parsed) import_node_fs28.default.writeFileSync(import_node_path23.default.join(staging, "parsed.json"), JSON.stringify({ text: parsed.text.slice(0, 16e3) }), { flag: "wx", mode: 384 });
|
|
21087
|
+
import_node_fs28.default.writeFileSync(import_node_path23.default.join(staging, "metadata.json"), JSON.stringify(record), { flag: "wx", mode: 384 });
|
|
20224
21088
|
checkSignal(input.signal);
|
|
20225
|
-
|
|
21089
|
+
import_node_fs28.default.renameSync(staging, import_node_path23.default.join(parent, ref));
|
|
20226
21090
|
const { pages: _pages, ...view } = record;
|
|
20227
21091
|
return view;
|
|
20228
21092
|
} finally {
|
|
20229
|
-
|
|
21093
|
+
import_node_fs28.default.rmSync(staging, { recursive: true, force: true });
|
|
20230
21094
|
}
|
|
20231
21095
|
}, input.signal);
|
|
20232
21096
|
} catch (error) {
|
|
@@ -20268,10 +21132,10 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20268
21132
|
return locked(async function readParsed() {
|
|
20269
21133
|
const { record, page } = await find3(sessionId, ref);
|
|
20270
21134
|
if (page || record.kind !== "document") unavailable();
|
|
20271
|
-
const target =
|
|
21135
|
+
const target = import_node_path23.default.join(dataRoot, sessionId, ref, "parsed.json");
|
|
20272
21136
|
assertSafeNodePath(root, target);
|
|
20273
|
-
if (
|
|
20274
|
-
const parsed = JSON.parse(
|
|
21137
|
+
if (import_node_fs28.default.statSync(target).size > 1e5) unavailable();
|
|
21138
|
+
const parsed = JSON.parse(import_node_fs28.default.readFileSync(target, "utf8"));
|
|
20275
21139
|
if (typeof parsed.text !== "string") unavailable();
|
|
20276
21140
|
return { text: parsed.text.slice(0, 16e3), pageImages: record.pages.map(function pageGrant(item) {
|
|
20277
21141
|
return grant({ ...record, ref: item.ref, kind: "image" });
|
|
@@ -20281,44 +21145,44 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20281
21145
|
async function readBytes(sessionId, ref, signal) {
|
|
20282
21146
|
return locked(async function readContent() {
|
|
20283
21147
|
const { record, page } = await find3(sessionId, ref);
|
|
20284
|
-
const target =
|
|
21148
|
+
const target = import_node_path23.default.join(dataRoot, sessionId, record.ref, page?.ref ?? "content");
|
|
20285
21149
|
assertSafeNodePath(root, target);
|
|
20286
21150
|
const metadata = page ?? record;
|
|
20287
|
-
if (
|
|
20288
|
-
const bytes =
|
|
21151
|
+
if (import_node_fs28.default.statSync(target).size !== metadata.byteLength || metadata.byteLength > MAX_BYTES) unavailable();
|
|
21152
|
+
const bytes = import_node_fs28.default.readFileSync(target);
|
|
20289
21153
|
if (digest(bytes) !== metadata.sha256) unavailable();
|
|
20290
21154
|
return { bytes: new Uint8Array(bytes), mimeType: metadata.mimeType };
|
|
20291
21155
|
}, signal);
|
|
20292
21156
|
}
|
|
20293
21157
|
async function deleteBySession(sessionId) {
|
|
20294
21158
|
await locked(async function deleteSessionAttachments() {
|
|
20295
|
-
atomicReplace(
|
|
21159
|
+
atomicReplace(import_node_path23.default.join(deletingRoot, `${sessionKey(sessionId)}.json`), JSON.stringify({ sessionId }));
|
|
20296
21160
|
for (const record of records(sessionId)) await retire(record);
|
|
20297
21161
|
await removePresentationRefs(sessionId);
|
|
20298
|
-
|
|
21162
|
+
import_node_fs28.default.rmSync(import_node_path23.default.join(dataRoot, sessionId), { recursive: true, force: true });
|
|
20299
21163
|
}, void 0, "CHAT_ATTACHMENT_CLEANUP_FAILED");
|
|
20300
21164
|
}
|
|
20301
21165
|
async function cleanupExpired(input = {}) {
|
|
20302
21166
|
const limit = input.limit ?? 32;
|
|
20303
21167
|
if (!Number.isInteger(limit) || limit < 1 || limit > 128) throw new NodeChatError("CHAT_ATTACHMENT_CLEANUP_FAILED");
|
|
20304
21168
|
return locked(async function cleanupBatch() {
|
|
20305
|
-
for (const file of
|
|
21169
|
+
for (const file of import_node_fs28.default.readdirSync(root)) {
|
|
20306
21170
|
if (!/^staging-[0-9a-f-]{36}$/.test(file)) continue;
|
|
20307
|
-
const target =
|
|
21171
|
+
const target = import_node_path23.default.join(root, file);
|
|
20308
21172
|
assertSafeNodePath(root, target);
|
|
20309
|
-
|
|
21173
|
+
import_node_fs28.default.rmSync(target, { recursive: true, force: true });
|
|
20310
21174
|
}
|
|
20311
|
-
for (const file of
|
|
21175
|
+
for (const file of import_node_fs28.default.readdirSync(retiredRoot)) {
|
|
20312
21176
|
if (!file.endsWith(".json")) continue;
|
|
20313
|
-
const target =
|
|
21177
|
+
const target = import_node_path23.default.join(retiredRoot, file);
|
|
20314
21178
|
assertSafeNodePath(root, target);
|
|
20315
21179
|
checkSignal(input.signal);
|
|
20316
|
-
const item = JSON.parse(
|
|
21180
|
+
const item = JSON.parse(import_node_fs28.default.readFileSync(target, "utf8"));
|
|
20317
21181
|
if (file !== `${item.ref}.json`) unavailable();
|
|
20318
21182
|
await finishRetirement(item);
|
|
20319
21183
|
}
|
|
20320
21184
|
const expired = [];
|
|
20321
|
-
for (const sessionId of
|
|
21185
|
+
for (const sessionId of import_node_fs28.default.readdirSync(dataRoot)) {
|
|
20322
21186
|
for (const record of records(sessionId)) if (record.expiresAt <= now() || isSessionDeleting(sessionId)) expired.push(record);
|
|
20323
21187
|
}
|
|
20324
21188
|
expired.sort(function oldestFirst(left, right) {
|
|
@@ -20428,6 +21292,7 @@ function createNodeChatCapabilityLoader(options) {
|
|
|
20428
21292
|
}
|
|
20429
21293
|
const attachments = await storage.attachments.list(binding.sessionId);
|
|
20430
21294
|
return {
|
|
21295
|
+
...(binding.retrievalMode === "none" || binding.retrievalMode === "web") && options.interactiveUi === true ? { interactiveUi: true } : {},
|
|
20431
21296
|
/** 目录只含授权字段,实际引用仍由 Core 的冻结交集和 Store 复查约束。 */
|
|
20432
21297
|
attachments: attachments.map(function grant(item) {
|
|
20433
21298
|
return { ref: item.ref, displayName: item.displayName, sessionId: item.sessionId, kind: item.kind, expiresAt: item.expiresAt };
|
|
@@ -20552,8 +21417,8 @@ function createNodeRagRuntime(options) {
|
|
|
20552
21417
|
}
|
|
20553
21418
|
|
|
20554
21419
|
// src/node/settings/node-settings-writer.ts
|
|
20555
|
-
var
|
|
20556
|
-
var
|
|
21420
|
+
var import_node_fs29 = __toESM(require("node:fs"));
|
|
21421
|
+
var import_core18 = require("@autopilot-agent/core");
|
|
20557
21422
|
var CONFIG_KEY_ALLOWLIST = /* @__PURE__ */ new Set([
|
|
20558
21423
|
"model",
|
|
20559
21424
|
"effortLevel",
|
|
@@ -20565,9 +21430,9 @@ function createNodeSettingsWriter(options = {}) {
|
|
|
20565
21430
|
}
|
|
20566
21431
|
function readScope(scope, workspaceRoot) {
|
|
20567
21432
|
const filePath = getPaths(workspaceRoot)[scope];
|
|
20568
|
-
if (!
|
|
21433
|
+
if (!import_node_fs29.default.existsSync(filePath)) return {};
|
|
20569
21434
|
try {
|
|
20570
|
-
const parsed = JSON.parse(
|
|
21435
|
+
const parsed = JSON.parse(import_node_fs29.default.readFileSync(filePath, "utf8"));
|
|
20571
21436
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? { ...parsed } : {};
|
|
20572
21437
|
} catch {
|
|
20573
21438
|
return {};
|
|
@@ -20598,7 +21463,7 @@ function createNodeSettingsWriter(options = {}) {
|
|
|
20598
21463
|
cursor = cursor[part];
|
|
20599
21464
|
}
|
|
20600
21465
|
cursor[parts[parts.length - 1]] = parsedValue;
|
|
20601
|
-
(0,
|
|
21466
|
+
(0, import_core18.resolveAutopilotSettings)([{ scope, value: target }]);
|
|
20602
21467
|
atomicReplace(getPaths(workspaceRoot)[scope], JSON.stringify(target, null, 2));
|
|
20603
21468
|
return toSafeView(target);
|
|
20604
21469
|
}
|
|
@@ -20663,9 +21528,9 @@ function parseConfigValue(key2, rawValue) {
|
|
|
20663
21528
|
}
|
|
20664
21529
|
|
|
20665
21530
|
// src/node/settings/node-user-settings-service.ts
|
|
20666
|
-
var
|
|
20667
|
-
var
|
|
20668
|
-
var
|
|
21531
|
+
var import_node_crypto13 = require("node:crypto");
|
|
21532
|
+
var import_node_fs30 = __toESM(require("node:fs"));
|
|
21533
|
+
var import_core19 = require("@autopilot-agent/core");
|
|
20669
21534
|
var RAG_ROLE_CONTRACT = Object.freeze({
|
|
20670
21535
|
textRerank: { provider: "bailian", key: "RAG_TEXT_RERANK_API_KEY", dimension: false },
|
|
20671
21536
|
visionRerank: { provider: "bailian", key: "RAG_VISION_RERANK_API_KEY", dimension: false },
|
|
@@ -20686,7 +21551,7 @@ function splitDiagnostics(diagnostics) {
|
|
|
20686
21551
|
const blocking = [];
|
|
20687
21552
|
const permissions = [];
|
|
20688
21553
|
for (const diagnostic of diagnostics) {
|
|
20689
|
-
if ((0,
|
|
21554
|
+
if ((0, import_core19.isExternalPermissionDiagnostic)(diagnostic)) permissions.push(safeDiagnostic(diagnostic));
|
|
20690
21555
|
else blocking.push(diagnostic);
|
|
20691
21556
|
}
|
|
20692
21557
|
return { blocking, permissions };
|
|
@@ -20702,14 +21567,14 @@ function parseApiKey(value) {
|
|
|
20702
21567
|
return typeof value === "string" && value.length <= 4096 && !/[\s\u0000-\u001f\u007f]/u.test(value) ? value : void 0;
|
|
20703
21568
|
}
|
|
20704
21569
|
function revisionOf(content) {
|
|
20705
|
-
return (0,
|
|
21570
|
+
return (0, import_node_crypto13.createHash)("sha256").update(content).digest("hex");
|
|
20706
21571
|
}
|
|
20707
21572
|
function readUserSettings(settingsPath) {
|
|
20708
|
-
if (!
|
|
21573
|
+
if (!import_node_fs30.default.existsSync(settingsPath)) return { raw: {}, original: "" };
|
|
20709
21574
|
try {
|
|
20710
|
-
const stat =
|
|
21575
|
+
const stat = import_node_fs30.default.lstatSync(settingsPath);
|
|
20711
21576
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw new Error();
|
|
20712
|
-
const original =
|
|
21577
|
+
const original = import_node_fs30.default.readFileSync(settingsPath, "utf8");
|
|
20713
21578
|
const raw = JSON.parse(original);
|
|
20714
21579
|
if (!isRecord4(raw) || raw.env !== void 0 && !isRecord4(raw.env)) throw new Error();
|
|
20715
21580
|
return { raw: { ...raw }, original };
|
|
@@ -20722,7 +21587,13 @@ function assertRevision(original, revision) {
|
|
|
20722
21587
|
}
|
|
20723
21588
|
function readEnvironmentKey(environment, key2) {
|
|
20724
21589
|
if (!key2) return void 0;
|
|
20725
|
-
return parseApiKey(environment[key2]);
|
|
21590
|
+
return parseApiKey(environment[key2] ?? (key2.startsWith("USER_SETTINGS_") ? environment[key2.slice("USER_SETTINGS_".length)] : void 0));
|
|
21591
|
+
}
|
|
21592
|
+
function readMainCredential(environment, ref, env) {
|
|
21593
|
+
const configured = readEnvironmentKey(environment, ref.key);
|
|
21594
|
+
if (configured || ref.key.startsWith("USER_SETTINGS_")) return configured;
|
|
21595
|
+
const envKey = `${ref.provider.toUpperCase().replace(/[^A-Z0-9_]/gu, "_")}_${ref.key.toUpperCase()}`;
|
|
21596
|
+
return parseApiKey(env[envKey]);
|
|
20726
21597
|
}
|
|
20727
21598
|
function collectMainCredentialCandidates(raw, environment) {
|
|
20728
21599
|
const candidates = [];
|
|
@@ -20770,31 +21641,109 @@ function removeLegacyPrimaryRoutes(raw, environment) {
|
|
|
20770
21641
|
for (const key2 of removedKeys) if (!hasCredentialReference(raw, key2)) delete environment[key2];
|
|
20771
21642
|
}
|
|
20772
21643
|
function normalizeMainInput(input) {
|
|
20773
|
-
const
|
|
21644
|
+
const apiProtocol = input.apiProtocol ?? "anthropic-messages";
|
|
21645
|
+
const baseUrl = (0, import_core19.normalizeProviderBaseUrl)(input.baseUrl);
|
|
20774
21646
|
const model = parseSettingString(input.model);
|
|
20775
21647
|
const apiKey = parseApiKey(input.apiKey);
|
|
20776
21648
|
const availableModels = input.availableModels?.map(function parseModel(value) {
|
|
20777
21649
|
return parseSettingString(value);
|
|
20778
21650
|
});
|
|
20779
|
-
if (!baseUrl || !model || input.apiKey !== void 0 && input.apiKey !== "" && !apiKey || availableModels && (availableModels.length === 0 || availableModels.some(function missing(value) {
|
|
21651
|
+
if (!["anthropic-messages", "openai-chat-completions", "openai-responses"].includes(apiProtocol) || input.compatibilityPreset !== void 0 && (apiProtocol === "anthropic-messages" || !["openai", "deepseek", "generic"].includes(input.compatibilityPreset)) || !baseUrl || !model || input.apiKey !== void 0 && input.apiKey !== "" && !apiKey || availableModels && (availableModels.length === 0 || availableModels.some(function missing(value) {
|
|
20780
21652
|
return !value;
|
|
20781
|
-
}) || new Set(availableModels).size !== availableModels.length) || input.effort !== void 0 && !["auto", "low", "medium", "high", "max"].includes(input.effort) || input.maxOutputTokens !== void 0 && (!Number.isInteger(input.maxOutputTokens) || input.maxOutputTokens < 1 || input.maxOutputTokens > 1e6) || input.compactWindow !== void 0 && (!Number.isInteger(input.compactWindow) || input.compactWindow < 1 || input.compactWindow > 1e7) || input.timeoutMs !== void 0 && (!Number.isInteger(input.timeoutMs) || input.timeoutMs < 1e3 || input.timeoutMs > 6e5) || input.alwaysThinkingEnabled !== void 0 && typeof input.alwaysThinkingEnabled !== "boolean") throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
21653
|
+
}) || new Set(availableModels).size !== availableModels.length) || input.effort !== void 0 && !["auto", "none", "low", "medium", "high", "xhigh", "max"].includes(input.effort) || input.maxOutputTokens !== void 0 && (!Number.isInteger(input.maxOutputTokens) || input.maxOutputTokens < 1 || input.maxOutputTokens > 1e6) || input.compactWindow !== void 0 && (!Number.isInteger(input.compactWindow) || input.compactWindow < 1 || input.compactWindow > 1e7) || input.timeoutMs !== void 0 && (!Number.isInteger(input.timeoutMs) || input.timeoutMs < 1e3 || input.timeoutMs > 6e5) || input.alwaysThinkingEnabled !== void 0 && typeof input.alwaysThinkingEnabled !== "boolean") throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
20782
21654
|
for (const value of [input.opusModel, input.sonnetModel, input.haikuModel, input.subagentModel]) {
|
|
20783
21655
|
if (value !== void 0 && !parseSettingString(value)) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
20784
21656
|
}
|
|
20785
|
-
return { ...input, baseUrl, model, ...apiKey ? { apiKey } : {}, ...availableModels ? { availableModels } : {} };
|
|
21657
|
+
return { ...input, apiProtocol, baseUrl, model, ...apiKey ? { apiKey } : {}, ...availableModels ? { availableModels } : {} };
|
|
21658
|
+
}
|
|
21659
|
+
function createMainRoute(raw, input) {
|
|
21660
|
+
const previous = (0, import_core19.resolveAutopilotSettings)([{ scope: "user", value: raw }]);
|
|
21661
|
+
const selected = previous.modelRef && previous.providerRoutes[previous.modelRef.provider];
|
|
21662
|
+
const apiProtocol = input.apiProtocol ?? "anthropic-messages";
|
|
21663
|
+
const sameConnection = selected?.apiProtocol === apiProtocol && selected.baseUrl === input.baseUrl;
|
|
21664
|
+
const matches3 = sameConnection && selected.compatibilityPreset === input.compatibilityPreset;
|
|
21665
|
+
let id = selected?.id ?? "web-main";
|
|
21666
|
+
for (let suffix = 2; !selected && previous.providerRoutes[id]; suffix += 1) id = `web-main-${suffix}`;
|
|
21667
|
+
const ids = [.../* @__PURE__ */ new Set([...input.availableModels ?? (matches3 ? selected.models.map(function modelId(model) {
|
|
21668
|
+
return model.id;
|
|
21669
|
+
}) : []), input.model])];
|
|
21670
|
+
return {
|
|
21671
|
+
id,
|
|
21672
|
+
apiProtocol,
|
|
21673
|
+
baseUrl: input.baseUrl,
|
|
21674
|
+
credentialRef: sameConnection ? selected.credentialRef : { provider: id, key: `USER_SETTINGS_WEB_MAIN_${revisionOf(`${id}/${apiProtocol}/${input.baseUrl}`).slice(0, 16).toUpperCase()}` },
|
|
21675
|
+
...selected?.displayName ? { displayName: selected.displayName } : {},
|
|
21676
|
+
...input.compatibilityPreset ? { compatibilityPreset: input.compatibilityPreset } : {},
|
|
21677
|
+
...matches3 && selected.protocolProfile ? { protocolProfile: selected.protocolProfile } : {},
|
|
21678
|
+
models: ids.map(function modelEntry(modelId) {
|
|
21679
|
+
return matches3 ? selected.models.find(function matchesId(model) {
|
|
21680
|
+
return model.id === modelId;
|
|
21681
|
+
}) ?? { id: modelId } : { id: modelId };
|
|
21682
|
+
})
|
|
21683
|
+
};
|
|
21684
|
+
}
|
|
21685
|
+
function resolveMainCapabilities(route, model) {
|
|
21686
|
+
try {
|
|
21687
|
+
const capability = (0, import_core19.resolveRouteModelCapability)(route, model);
|
|
21688
|
+
return { supportedReasoningEfforts: capability.supportedReasoningEfforts ?? [], supportsToolCalls: capability.supportsToolCalls !== false };
|
|
21689
|
+
} catch {
|
|
21690
|
+
throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
21691
|
+
}
|
|
20786
21692
|
}
|
|
20787
|
-
function
|
|
21693
|
+
function applyRoutedMainCategory(raw, input, env) {
|
|
21694
|
+
const route = createMainRoute(raw, input);
|
|
21695
|
+
const capabilities = resolveMainCapabilities(route, input.model);
|
|
21696
|
+
if (!capabilities.supportsToolCalls) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID", { scope: "user", code: "MODEL_NOT_SUPPORTED", field: "model" });
|
|
21697
|
+
if (input.effort && input.effort !== "auto" && !capabilities.supportedReasoningEfforts.includes(input.effort)) {
|
|
21698
|
+
throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID", { scope: "user", code: "SETTINGS_EFFORT_INVALID", field: "effortLevel" });
|
|
21699
|
+
}
|
|
21700
|
+
const environment = { ...isRecord4(raw.env) ? raw.env : {} };
|
|
21701
|
+
const previous = (0, import_core19.resolveAutopilotSettings)([{ scope: "user", value: raw }]);
|
|
21702
|
+
const selected = previous.modelRef && previous.providerRoutes[previous.modelRef.provider];
|
|
21703
|
+
const sameConnection = selected?.apiProtocol === route.apiProtocol && selected.baseUrl === route.baseUrl;
|
|
21704
|
+
if (!input.apiKey && !sameConnection) throw new NodeUserSettingsError("SETTINGS_KEY_REQUIRED");
|
|
21705
|
+
const key2 = input.apiKey ?? readMainCredential(environment, route.credentialRef, env);
|
|
21706
|
+
if (!key2) throw new NodeUserSettingsError("SETTINGS_KEY_REQUIRED");
|
|
21707
|
+
if (input.apiKey) environment[route.credentialRef.key] = input.apiKey;
|
|
21708
|
+
delete environment.ANTHROPIC_MODEL;
|
|
21709
|
+
delete environment.CLAUDE_CODE_EFFORT_LEVEL;
|
|
21710
|
+
raw.env = environment;
|
|
21711
|
+
raw.providerRoutes = { ...isRecord4(raw.providerRoutes) ? raw.providerRoutes : {}, [route.id]: route };
|
|
21712
|
+
raw.model = `${route.id}/${input.model}`;
|
|
21713
|
+
if (input.effort && input.effort !== "auto") raw.effortLevel = input.effort;
|
|
21714
|
+
else delete raw.effortLevel;
|
|
21715
|
+
}
|
|
21716
|
+
function applyMainCategory(raw, input, env) {
|
|
20788
21717
|
const normalized = normalizeMainInput(input);
|
|
21718
|
+
const previous = (0, import_core19.resolveAutopilotSettings)([{ scope: "user", value: raw }]);
|
|
21719
|
+
const previousRoute = previous.modelRef && previous.providerRoutes[previous.modelRef.provider];
|
|
21720
|
+
if (normalized.apiProtocol !== "anthropic-messages" || input.apiProtocol !== void 0 && previousRoute) {
|
|
21721
|
+
applyRoutedMainCategory(raw, normalized, env);
|
|
21722
|
+
if (normalized.maxOutputTokens === void 0) delete raw.maxOutputTokens;
|
|
21723
|
+
else raw.maxOutputTokens = normalized.maxOutputTokens;
|
|
21724
|
+
const environment2 = raw.env;
|
|
21725
|
+
const optional2 = {
|
|
21726
|
+
ANTHROPIC_DEFAULT_OPUS_MODEL: normalized.opusModel,
|
|
21727
|
+
ANTHROPIC_DEFAULT_SONNET_MODEL: normalized.sonnetModel,
|
|
21728
|
+
ANTHROPIC_DEFAULT_HAIKU_MODEL: normalized.haikuModel,
|
|
21729
|
+
CLAUDE_CODE_AUTO_COMPACT_WINDOW: normalized.compactWindow?.toString(),
|
|
21730
|
+
API_TIMEOUT_MS: normalized.timeoutMs?.toString(),
|
|
21731
|
+
CLAUDE_CODE_SUBAGENT_MODEL: normalized.subagentModel
|
|
21732
|
+
};
|
|
21733
|
+
for (const [key2, value] of Object.entries(optional2)) {
|
|
21734
|
+
if (value === void 0) delete environment2[key2];
|
|
21735
|
+
else environment2[key2] = value;
|
|
21736
|
+
}
|
|
21737
|
+
if (normalized.apiProtocol === "anthropic-messages" && normalized.alwaysThinkingEnabled !== void 0) raw.alwaysThinkingEnabled = normalized.alwaysThinkingEnabled;
|
|
21738
|
+
return;
|
|
21739
|
+
}
|
|
20789
21740
|
const environment = { ...isRecord4(raw.env) ? raw.env : {} };
|
|
20790
21741
|
const candidates = collectMainCredentialCandidates(raw, environment);
|
|
20791
21742
|
const distinct = [...new Set(candidates.map(function value(candidate) {
|
|
20792
21743
|
return candidate.value;
|
|
20793
21744
|
}))];
|
|
20794
21745
|
if (!normalized.apiKey && distinct.length > 1) throw new NodeUserSettingsError("SETTINGS_MIGRATION_CONFLICT");
|
|
20795
|
-
const
|
|
20796
|
-
const previousRoute = previous.modelRef && previous.providerRoutes[previous.modelRef.provider];
|
|
20797
|
-
const previousBaseUrl = (0, import_core16.normalizeProviderBaseUrl)(previousRoute?.baseUrl ?? previous.firstParty.baseUrl);
|
|
21746
|
+
const previousBaseUrl = (0, import_core19.normalizeProviderBaseUrl)(previousRoute?.baseUrl ?? previous.firstParty.baseUrl);
|
|
20798
21747
|
const officialDeepSeekMigration = previousBaseUrl === "https://api.deepseek.com" && normalized.baseUrl === "https://api.deepseek.com/anthropic";
|
|
20799
21748
|
if (!normalized.apiKey && previousBaseUrl !== normalized.baseUrl && !officialDeepSeekMigration) throw new NodeUserSettingsError("SETTINGS_KEY_REQUIRED");
|
|
20800
21749
|
const apiKey = normalized.apiKey ?? distinct[0];
|
|
@@ -20820,6 +21769,7 @@ function applyMainCategory(raw, input) {
|
|
|
20820
21769
|
}
|
|
20821
21770
|
raw.env = environment;
|
|
20822
21771
|
delete raw.model;
|
|
21772
|
+
delete raw.effortLevel;
|
|
20823
21773
|
raw.availableModels = normalized.availableModels ?? [...new Set([normalized.model, normalized.opusModel, normalized.sonnetModel, normalized.haikuModel, normalized.subagentModel].filter(function present(value) {
|
|
20824
21774
|
return Boolean(value);
|
|
20825
21775
|
}))];
|
|
@@ -20828,32 +21778,36 @@ function applyMainCategory(raw, input) {
|
|
|
20828
21778
|
if (normalized.alwaysThinkingEnabled === void 0) delete raw.alwaysThinkingEnabled;
|
|
20829
21779
|
else raw.alwaysThinkingEnabled = normalized.alwaysThinkingEnabled;
|
|
20830
21780
|
}
|
|
20831
|
-
function applyWebSearch(raw, input) {
|
|
21781
|
+
function applyWebSearch(raw, input, env) {
|
|
20832
21782
|
if (typeof input.enabled !== "boolean" || typeof input.useMainKey !== "boolean") throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
20833
21783
|
if (!input.enabled) {
|
|
20834
21784
|
raw.webSearch = false;
|
|
20835
21785
|
return;
|
|
20836
21786
|
}
|
|
20837
21787
|
const provider = input.provider;
|
|
20838
|
-
const baseUrl = (0,
|
|
21788
|
+
const baseUrl = (0, import_core19.normalizeProviderBaseUrl)(input.baseUrl);
|
|
20839
21789
|
const model = parseSettingString(input.model);
|
|
20840
21790
|
const environment = { ...isRecord4(raw.env) ? raw.env : {} };
|
|
20841
|
-
const
|
|
20842
|
-
const
|
|
21791
|
+
const settings = (0, import_core19.resolveAutopilotSettings)([{ scope: "user", value: raw }]);
|
|
21792
|
+
const mainRoute = settings.modelRef && settings.providerRoutes[settings.modelRef.provider];
|
|
21793
|
+
const mainBaseUrl = mainRoute?.baseUrl ?? (0, import_core19.normalizeProviderBaseUrl)(environment.ANTHROPIC_BASE_URL);
|
|
21794
|
+
const mainRef = mainRoute?.credentialRef ?? { provider: "deepseek", key: "USER_SETTINGS_ANTHROPIC_AUTH_TOKEN" };
|
|
21795
|
+
const mainKey = mainRoute ? readMainCredential(environment, mainRef, env) : readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY");
|
|
21796
|
+
const canReuseMainKey = (!mainRoute || mainRoute.apiProtocol === "anthropic-messages") && mainBaseUrl === "https://api.deepseek.com/anthropic" && Boolean(mainKey);
|
|
20843
21797
|
if (input.useMainKey) {
|
|
20844
21798
|
if (!canReuseMainKey) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
20845
21799
|
raw.webSearch = {
|
|
20846
21800
|
provider: "deepseek",
|
|
20847
21801
|
baseUrl: "https://api.deepseek.com/anthropic",
|
|
20848
21802
|
model: "deepseek-flash",
|
|
20849
|
-
credentialRef:
|
|
21803
|
+
credentialRef: mainRef
|
|
20850
21804
|
};
|
|
20851
21805
|
return;
|
|
20852
21806
|
}
|
|
20853
21807
|
const apiKey = parseApiKey(input.apiKey);
|
|
20854
21808
|
const current = isRecord4(raw.webSearch) ? raw.webSearch : void 0;
|
|
20855
21809
|
const currentRef = current && isRecord4(current.credentialRef) ? current.credentialRef : void 0;
|
|
20856
|
-
const sameConnection = current?.provider === provider && (0,
|
|
21810
|
+
const sameConnection = current?.provider === provider && (0, import_core19.normalizeProviderBaseUrl)(current?.baseUrl) === baseUrl;
|
|
20857
21811
|
const preservedKeyName = sameConnection ? parseSettingString(currentRef?.key) : void 0;
|
|
20858
21812
|
const preservedKey = readEnvironmentKey(environment, preservedKeyName);
|
|
20859
21813
|
if (provider !== "deepseek" && provider !== "openai-compatible" && provider !== "xiaomi-mimo" || !baseUrl || !model || !apiKey && !preservedKey) {
|
|
@@ -20872,7 +21826,7 @@ function applyRagRole(raw, role, input) {
|
|
|
20872
21826
|
delete rag[role];
|
|
20873
21827
|
delete environment[contract.key];
|
|
20874
21828
|
} else {
|
|
20875
|
-
const baseUrl = (0,
|
|
21829
|
+
const baseUrl = (0, import_core19.normalizeProviderBaseUrl)(input.baseUrl);
|
|
20876
21830
|
const model = parseSettingString(input.model);
|
|
20877
21831
|
const apiKey = parseApiKey(input.apiKey);
|
|
20878
21832
|
const current = isRecord4(rag[role]) ? rag[role] : void 0;
|
|
@@ -20891,13 +21845,14 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20891
21845
|
const homeDirectory = options.homeDirectory;
|
|
20892
21846
|
const settingsPath = resolveNodeUserSettingsPath(homeDirectory);
|
|
20893
21847
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
21848
|
+
const env = options.env ?? process.env;
|
|
20894
21849
|
async function save(update2, revision) {
|
|
20895
21850
|
return withFileLock(settingsPath, function writeSettings() {
|
|
20896
21851
|
ensureUserConfigDirectory({ ...homeDirectory ? { homeDirectory } : {} });
|
|
20897
21852
|
const current = readUserSettings(settingsPath);
|
|
20898
21853
|
assertRevision(current.original, revision);
|
|
20899
21854
|
update2(current.raw);
|
|
20900
|
-
const { blocking } = splitDiagnostics((0,
|
|
21855
|
+
const { blocking } = splitDiagnostics((0, import_core19.resolveAutopilotSettings)([{ scope: "user", value: current.raw }]).diagnostics);
|
|
20901
21856
|
if (blocking.length > 0) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID", safeDiagnostic(blocking[0]));
|
|
20902
21857
|
const content = `${JSON.stringify(current.raw, null, 2)}
|
|
20903
21858
|
`;
|
|
@@ -20906,12 +21861,17 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20906
21861
|
});
|
|
20907
21862
|
}
|
|
20908
21863
|
return {
|
|
21864
|
+
/** 预览草稿模型在当前 route 覆盖下的能力,不读取或返回 API Key。 */
|
|
21865
|
+
getMainModelCapabilities(input) {
|
|
21866
|
+
const normalized = normalizeMainInput(input);
|
|
21867
|
+
return resolveMainCapabilities(createMainRoute(readUserSettings(settingsPath).raw, normalized), normalized.model);
|
|
21868
|
+
},
|
|
20909
21869
|
/** 用户主动刷新时调用 DeepSeek 官方目录;无凭据、失败或异常响应均使用维护目录。 */
|
|
20910
21870
|
async refreshMainModelCatalog() {
|
|
20911
21871
|
const maintained = ["deepseek-v4-pro[1m]", "deepseek-v4-flash"];
|
|
20912
21872
|
const current = readUserSettings(settingsPath);
|
|
20913
21873
|
const environment = isRecord4(current.raw.env) ? current.raw.env : {};
|
|
20914
|
-
const baseUrl = (0,
|
|
21874
|
+
const baseUrl = (0, import_core19.normalizeProviderBaseUrl)(environment.ANTHROPIC_BASE_URL);
|
|
20915
21875
|
const apiKey = readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY");
|
|
20916
21876
|
if (baseUrl !== "https://api.deepseek.com/anthropic" || !apiKey) return { models: maintained, source: "maintained" };
|
|
20917
21877
|
try {
|
|
@@ -20934,13 +21894,14 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20934
21894
|
const current = readUserSettings(settingsPath);
|
|
20935
21895
|
const raw = current.raw;
|
|
20936
21896
|
const environment = isRecord4(raw.env) ? raw.env : {};
|
|
20937
|
-
const resolved = (0,
|
|
21897
|
+
const resolved = (0, import_core19.resolveAutopilotSettings)([{ scope: "user", value: raw }]);
|
|
20938
21898
|
const { blocking, permissions } = splitDiagnostics(resolved.diagnostics);
|
|
20939
21899
|
if (blocking.length > 0) throw new NodeUserSettingsError("SETTINGS_INVALID", safeDiagnostic(blocking[0]));
|
|
20940
|
-
const
|
|
21900
|
+
const mainRoute = resolved.modelRef && resolved.providerRoutes[resolved.modelRef.provider];
|
|
21901
|
+
const mainBaseUrl = mainRoute?.baseUrl ?? resolved.firstParty.baseUrl ?? "https://api.deepseek.com/anthropic";
|
|
20941
21902
|
const mainModel = resolved.modelRef?.modelId ?? "deepseek-v4-flash";
|
|
20942
|
-
const mainKey = readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY");
|
|
20943
|
-
const search = resolved.webSearch ?? (!resolved.webSearchDisabled && mainKey && mainBaseUrl === "https://api.deepseek.com/anthropic" ? { provider: "deepseek", baseUrl: "https://api.deepseek.com/anthropic", model: "deepseek-flash", credentialRef: { key: "USER_SETTINGS_ANTHROPIC_AUTH_TOKEN" } } : void 0);
|
|
21903
|
+
const mainKey = mainRoute ? readMainCredential(environment, mainRoute.credentialRef, env) : readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY");
|
|
21904
|
+
const search = resolved.webSearch ?? (!resolved.webSearchDisabled && !mainRoute && mainKey && mainBaseUrl === "https://api.deepseek.com/anthropic" ? { provider: "deepseek", baseUrl: "https://api.deepseek.com/anthropic", model: "deepseek-flash", credentialRef: { key: "USER_SETTINGS_ANTHROPIC_AUTH_TOKEN" } } : void 0);
|
|
20944
21905
|
const searchKeyName = search?.credentialRef.key;
|
|
20945
21906
|
const searchKey = readEnvironmentKey(environment, searchKeyName) ?? (searchKeyName === "USER_SETTINGS_ANTHROPIC_AUTH_TOKEN" ? mainKey : void 0);
|
|
20946
21907
|
const rag = {};
|
|
@@ -20958,16 +21919,20 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20958
21919
|
return {
|
|
20959
21920
|
revision: revisionOf(current.original),
|
|
20960
21921
|
main: {
|
|
20961
|
-
provider: mainBaseUrl === "https://api.deepseek.com/anthropic" ? "deepseek" : "custom",
|
|
21922
|
+
provider: mainBaseUrl === "https://api.deepseek.com/anthropic" || mainRoute?.compatibilityPreset === "deepseek" ? "deepseek" : "custom",
|
|
21923
|
+
apiProtocol: mainRoute?.apiProtocol ?? "anthropic-messages",
|
|
21924
|
+
...mainRoute?.compatibilityPreset ? { compatibilityPreset: mainRoute.compatibilityPreset } : {},
|
|
20962
21925
|
baseUrl: mainBaseUrl,
|
|
20963
21926
|
model: mainModel,
|
|
20964
21927
|
configured: Boolean(mainKey),
|
|
20965
|
-
availableModels:
|
|
21928
|
+
availableModels: mainRoute ? mainRoute.models.map(function modelId(model) {
|
|
21929
|
+
return model.id;
|
|
21930
|
+
}) : resolved.availableModels.length > 0 ? [...resolved.availableModels] : ["deepseek-v4-flash", "deepseek-v4-pro[1m]"],
|
|
20966
21931
|
opusModel: typeof environment.ANTHROPIC_DEFAULT_OPUS_MODEL === "string" ? environment.ANTHROPIC_DEFAULT_OPUS_MODEL : void 0,
|
|
20967
21932
|
sonnetModel: typeof environment.ANTHROPIC_DEFAULT_SONNET_MODEL === "string" ? environment.ANTHROPIC_DEFAULT_SONNET_MODEL : void 0,
|
|
20968
21933
|
haikuModel: typeof environment.ANTHROPIC_DEFAULT_HAIKU_MODEL === "string" ? environment.ANTHROPIC_DEFAULT_HAIKU_MODEL : void 0,
|
|
20969
21934
|
subagentModel: resolved.firstParty.subagentModelId,
|
|
20970
|
-
effort:
|
|
21935
|
+
effort: resolved.reasoningProfile?.effort ?? "auto",
|
|
20971
21936
|
maxOutputTokens: resolved.firstParty.maxOutputTokens,
|
|
20972
21937
|
compactWindow: resolved.firstParty.compactWindow,
|
|
20973
21938
|
timeoutMs: resolved.firstParty.timeoutMs,
|
|
@@ -20975,7 +21940,7 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20975
21940
|
},
|
|
20976
21941
|
search: {
|
|
20977
21942
|
enabled: Boolean(search),
|
|
20978
|
-
useMainKey: searchKeyName === "USER_SETTINGS_ANTHROPIC_AUTH_TOKEN",
|
|
21943
|
+
useMainKey: mainRoute ? mainRoute.apiProtocol === "anthropic-messages" && mainRoute.baseUrl === "https://api.deepseek.com/anthropic" && searchKeyName === mainRoute.credentialRef.key : searchKeyName === "USER_SETTINGS_ANTHROPIC_AUTH_TOKEN",
|
|
20979
21944
|
provider: search?.provider ?? "deepseek",
|
|
20980
21945
|
baseUrl: search?.baseUrl ?? "https://api.deepseek.com",
|
|
20981
21946
|
model: search?.model ?? "deepseek-v4-flash",
|
|
@@ -20993,7 +21958,7 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20993
21958
|
/** 保存主模型分类并执行旧 route/哈希凭据迁移。 */
|
|
20994
21959
|
saveMain(input, revision) {
|
|
20995
21960
|
return save(function updateMain(raw) {
|
|
20996
|
-
applyMainCategory(raw, input);
|
|
21961
|
+
applyMainCategory(raw, input, env);
|
|
20997
21962
|
}, revision);
|
|
20998
21963
|
},
|
|
20999
21964
|
/** 原子保存设置中心的主模型分类,包含已经独立化的 Search 连接。 */
|
|
@@ -21002,8 +21967,8 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
21002
21967
|
return key2 !== "main" && key2 !== "search";
|
|
21003
21968
|
})) return Promise.reject(new NodeUserSettingsError("SETTINGS_INPUT_INVALID"));
|
|
21004
21969
|
return save(function updateMainAndSearch(raw) {
|
|
21005
|
-
applyMainCategory(raw, input.main);
|
|
21006
|
-
applyWebSearch(raw, input.search);
|
|
21970
|
+
applyMainCategory(raw, input.main, env);
|
|
21971
|
+
applyWebSearch(raw, input.search, env);
|
|
21007
21972
|
}, revision);
|
|
21008
21973
|
},
|
|
21009
21974
|
/** 增量保存 RAG 分类;未提交角色保持不变。 */
|
|
@@ -21019,36 +21984,36 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
21019
21984
|
}
|
|
21020
21985
|
|
|
21021
21986
|
// src/node/capabilities/memory-retriever.ts
|
|
21022
|
-
var
|
|
21023
|
-
var
|
|
21024
|
-
var
|
|
21987
|
+
var import_node_crypto14 = __toESM(require("node:crypto"));
|
|
21988
|
+
var import_node_fs31 = __toESM(require("node:fs"));
|
|
21989
|
+
var import_node_path24 = __toESM(require("node:path"));
|
|
21025
21990
|
function getNodeMemoryWorkspaceId(workspaceRoot) {
|
|
21026
|
-
return
|
|
21991
|
+
return import_node_crypto14.default.createHash("sha256").update(import_node_fs31.default.realpathSync.native(workspaceRoot).toLowerCase()).digest("hex").slice(0, 24);
|
|
21027
21992
|
}
|
|
21028
21993
|
function getNodeMemoryDirectory(stateRoot, workspaceRoot) {
|
|
21029
|
-
return
|
|
21994
|
+
return import_node_path24.default.join(import_node_path24.default.resolve(stateRoot), "memory", getNodeMemoryWorkspaceId(workspaceRoot));
|
|
21030
21995
|
}
|
|
21031
21996
|
function getLegacyWebMemoryDirectory(workspaceRoot, cwd = process.cwd()) {
|
|
21032
|
-
return
|
|
21997
|
+
return import_node_path24.default.join(import_node_path24.default.resolve(cwd), ".local", "agent", "workspaces", getNodeMemoryWorkspaceId(workspaceRoot), "memory");
|
|
21033
21998
|
}
|
|
21034
21999
|
function retrieveNodeMemories(_stateRoot, _workspaceRoot, _query, _maxItems = 5) {
|
|
21035
22000
|
return [];
|
|
21036
22001
|
}
|
|
21037
22002
|
|
|
21038
22003
|
// src/node/trust-policy.ts
|
|
21039
|
-
var
|
|
21040
|
-
var
|
|
22004
|
+
var import_node_fs32 = __toESM(require("node:fs"));
|
|
22005
|
+
var import_node_path25 = __toESM(require("node:path"));
|
|
21041
22006
|
function createNodeTrustStore(options) {
|
|
21042
22007
|
const trustRoot = resolveNodeTrustRoot({ stateRoot: options.stateRoot, trustRoot: options.trustRoot });
|
|
21043
|
-
const trustFile =
|
|
22008
|
+
const trustFile = import_node_path25.default.join(trustRoot, "trust.json");
|
|
21044
22009
|
const now = options.now ?? (() => Date.now());
|
|
21045
22010
|
function ensureDir() {
|
|
21046
|
-
|
|
22011
|
+
import_node_fs32.default.mkdirSync(trustRoot, { recursive: true });
|
|
21047
22012
|
}
|
|
21048
22013
|
function loadStore() {
|
|
21049
|
-
if (!
|
|
22014
|
+
if (!import_node_fs32.default.existsSync(trustFile)) return { version: 1, workspaces: {} };
|
|
21050
22015
|
try {
|
|
21051
|
-
const parsed = JSON.parse(
|
|
22016
|
+
const parsed = JSON.parse(import_node_fs32.default.readFileSync(trustFile, "utf8"));
|
|
21052
22017
|
if (parsed.version !== 1 || !parsed.workspaces || typeof parsed.workspaces !== "object") return { version: 1, workspaces: {} };
|
|
21053
22018
|
return { version: 1, workspaces: parsed.workspaces };
|
|
21054
22019
|
} catch {
|
|
@@ -21150,16 +22115,16 @@ function createNodeTrustPolicy(options) {
|
|
|
21150
22115
|
}
|
|
21151
22116
|
|
|
21152
22117
|
// src/node/workspace-registry.ts
|
|
21153
|
-
var
|
|
21154
|
-
var
|
|
22118
|
+
var import_node_fs33 = __toESM(require("node:fs"));
|
|
22119
|
+
var import_node_path26 = __toESM(require("node:path"));
|
|
21155
22120
|
function createNodeWorkspaceRegistry(options = {}) {
|
|
21156
22121
|
const globalStateRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: options.cwd });
|
|
21157
|
-
const registryPath =
|
|
22122
|
+
const registryPath = import_node_path26.default.join(globalStateRoot, "workspace-registry.json");
|
|
21158
22123
|
const now = options.now ?? (() => Date.now());
|
|
21159
22124
|
function load2() {
|
|
21160
|
-
if (!
|
|
22125
|
+
if (!import_node_fs33.default.existsSync(registryPath)) return [];
|
|
21161
22126
|
try {
|
|
21162
|
-
const parsed = JSON.parse(
|
|
22127
|
+
const parsed = JSON.parse(import_node_fs33.default.readFileSync(registryPath, "utf8"));
|
|
21163
22128
|
if (!Array.isArray(parsed)) return [];
|
|
21164
22129
|
return parsed.filter(function isEntry(value) {
|
|
21165
22130
|
return Boolean(value) && typeof value === "object" && typeof value.workspaceId === "string" && typeof value.workspaceRoot === "string" && typeof value.displayName === "string" && typeof value.lastOpenedAt === "number";
|
|
@@ -21182,7 +22147,7 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21182
22147
|
const next = {
|
|
21183
22148
|
workspaceId,
|
|
21184
22149
|
workspaceRoot: canonicalRoot,
|
|
21185
|
-
displayName:
|
|
22150
|
+
displayName: import_node_path26.default.basename(canonicalRoot) || canonicalRoot,
|
|
21186
22151
|
lastOpenedAt: now()
|
|
21187
22152
|
};
|
|
21188
22153
|
const entries2 = load2().filter(function removeExisting(entry) {
|
|
@@ -21203,12 +22168,534 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21203
22168
|
}
|
|
21204
22169
|
return { list: load2, get, register, remove: remove2 };
|
|
21205
22170
|
}
|
|
22171
|
+
|
|
22172
|
+
// src/node/thread-runner.ts
|
|
22173
|
+
var import_core20 = require("@autopilot-agent/core");
|
|
22174
|
+
var import_node_crypto15 = require("node:crypto");
|
|
22175
|
+
function createNodeThreadRunner(options) {
|
|
22176
|
+
const delivery = options.delivery;
|
|
22177
|
+
const ownerId = delivery.ownerId;
|
|
22178
|
+
const pollIntervalMs = options.pollIntervalMs ?? 250;
|
|
22179
|
+
const staleMs = options.staleMs ?? 45e3;
|
|
22180
|
+
const heartbeatMs = options.heartbeatMs ?? Math.max(200, Math.min(5e3, Math.floor(staleMs / 3)));
|
|
22181
|
+
const reconcileEveryMs = options.reconcileEveryMs ?? 3e3;
|
|
22182
|
+
const active = /* @__PURE__ */ new Map();
|
|
22183
|
+
let timer;
|
|
22184
|
+
let ticking = false;
|
|
22185
|
+
let stopped = false;
|
|
22186
|
+
let lastReconcileAt = 0;
|
|
22187
|
+
let running = false;
|
|
22188
|
+
let kicked = false;
|
|
22189
|
+
let idleDelayMs = pollIntervalMs;
|
|
22190
|
+
async function hasFreshLease(threadId) {
|
|
22191
|
+
const checkpoint = await options.ports.checkpointStore.getLatest(threadId);
|
|
22192
|
+
return Boolean(checkpoint && checkpoint.status === "running" && checkpoint.lease && Date.now() - checkpoint.lease.heartbeatAt <= delivery.leaseStaleMs);
|
|
22193
|
+
}
|
|
22194
|
+
function activeMessageIds() {
|
|
22195
|
+
return [...active.values()].filter(function deliveryRecord(record) {
|
|
22196
|
+
return !record.external && Boolean(record.messageId);
|
|
22197
|
+
}).map(function id(record) {
|
|
22198
|
+
return record.messageId;
|
|
22199
|
+
});
|
|
22200
|
+
}
|
|
22201
|
+
async function safeTick(reconcileFirst = false) {
|
|
22202
|
+
if (ticking || stopped) return;
|
|
22203
|
+
if (timer) clearTimeout(timer);
|
|
22204
|
+
timer = void 0;
|
|
22205
|
+
kicked = false;
|
|
22206
|
+
ticking = true;
|
|
22207
|
+
try {
|
|
22208
|
+
const snapshot = await delivery.querySnapshot();
|
|
22209
|
+
if (reconcileFirst || Date.now() - lastReconcileAt >= reconcileEveryMs) {
|
|
22210
|
+
lastReconcileAt = Date.now();
|
|
22211
|
+
await delivery.reconcile({ staleMs, activeMessageIds: activeMessageIds(), snapshot });
|
|
22212
|
+
}
|
|
22213
|
+
await applyInterrupts(snapshot);
|
|
22214
|
+
await applyResumes(snapshot);
|
|
22215
|
+
await applyInteractionContinuations(snapshot);
|
|
22216
|
+
const claimed = await delivery.claimDeliveries({ snapshot, activeThreads: [...active.values()].filter(function controllable(record) {
|
|
22217
|
+
return record.ready;
|
|
22218
|
+
}).map(function thread(record) {
|
|
22219
|
+
return record.threadId;
|
|
22220
|
+
}) });
|
|
22221
|
+
for (const item of claimed) startDelivery(item);
|
|
22222
|
+
idleDelayMs = active.size || claimed.length ? pollIntervalMs : Math.min(Math.max(pollIntervalMs, 2e3), idleDelayMs * 2);
|
|
22223
|
+
} catch (error) {
|
|
22224
|
+
options.onError?.(error);
|
|
22225
|
+
} finally {
|
|
22226
|
+
ticking = false;
|
|
22227
|
+
if (running && !stopped) {
|
|
22228
|
+
timer = setTimeout(function poll() {
|
|
22229
|
+
void safeTick();
|
|
22230
|
+
}, kicked ? 0 : idleDelayMs);
|
|
22231
|
+
timer.unref?.();
|
|
22232
|
+
}
|
|
22233
|
+
}
|
|
22234
|
+
}
|
|
22235
|
+
async function applyInterrupts(snapshot) {
|
|
22236
|
+
for (const intent of await delivery.pendingInterrupts(snapshot)) {
|
|
22237
|
+
const task = active.get(intent.threadId);
|
|
22238
|
+
if (!task || !task.ready || task.turnId !== intent.expectedTurnId) {
|
|
22239
|
+
const turn = await options.ports.turnStore.get(intent.expectedTurnId);
|
|
22240
|
+
if (turn && (turn.status === "waiting_approval" || turn.status === "waiting_user_input")) {
|
|
22241
|
+
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)]);
|
|
22242
|
+
const checkpointStatus = turn.status === "waiting_approval" ? "awaiting_approval" : "awaiting_user_input";
|
|
22243
|
+
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) {
|
|
22244
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22245
|
+
continue;
|
|
22246
|
+
}
|
|
22247
|
+
try {
|
|
22248
|
+
await options.runtime.turns.cancel({ sessionId: intent.threadId, turnId: intent.expectedTurnId });
|
|
22249
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: true });
|
|
22250
|
+
} catch {
|
|
22251
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22252
|
+
}
|
|
22253
|
+
continue;
|
|
22254
|
+
}
|
|
22255
|
+
const terminal = turn && turn.status !== "running" && turn.status !== "waiting_approval" && turn.status !== "waiting_user_input";
|
|
22256
|
+
if (terminal) await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22257
|
+
else if (!turn && !await hasFreshLease(intent.threadId)) {
|
|
22258
|
+
const control = await delivery.readGroup(intent.groupId);
|
|
22259
|
+
const recorded = control?.controls.find(function match(item) {
|
|
22260
|
+
return item.controlId === intent.controlId;
|
|
22261
|
+
});
|
|
22262
|
+
if (recorded && Date.now() - recorded.createdAt > staleMs) await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22263
|
+
}
|
|
22264
|
+
continue;
|
|
22265
|
+
}
|
|
22266
|
+
try {
|
|
22267
|
+
if (task.cancelExecution) await task.cancelExecution();
|
|
22268
|
+
else await options.runtime.turns.cancel({ sessionId: intent.threadId, turnId: intent.expectedTurnId });
|
|
22269
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: true });
|
|
22270
|
+
} catch {
|
|
22271
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22272
|
+
}
|
|
22273
|
+
}
|
|
22274
|
+
}
|
|
22275
|
+
async function applyResumes(snapshot) {
|
|
22276
|
+
for (const intent of await delivery.pendingResumes(snapshot)) {
|
|
22277
|
+
if (active.has(intent.threadId) || await hasFreshLease(intent.threadId)) continue;
|
|
22278
|
+
if (!await delivery.claimResume(intent)) continue;
|
|
22279
|
+
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)]);
|
|
22280
|
+
if (!session || session.status !== "interrupted" || latest?.id !== intent.expectedTurnId || checkpoint?.turnId !== intent.expectedTurnId || (0, import_node_crypto15.createHash)("sha256").update(JSON.stringify(checkpoint)).digest("hex") !== intent.checkpointDigest) {
|
|
22281
|
+
await delivery.rejectResume(intent);
|
|
22282
|
+
continue;
|
|
22283
|
+
}
|
|
22284
|
+
const record = { threadId: intent.threadId, turnId: intent.expectedTurnId, groupId: intent.groupId, messageId: "", cancelled: false, task: Promise.resolve() };
|
|
22285
|
+
active.set(intent.threadId, record);
|
|
22286
|
+
record.task = continueOriginal().finally(function settled() {
|
|
22287
|
+
if (active.get(intent.threadId) === record) active.delete(intent.threadId);
|
|
22288
|
+
kick();
|
|
22289
|
+
});
|
|
22290
|
+
async function continueOriginal() {
|
|
22291
|
+
let started = false;
|
|
22292
|
+
try {
|
|
22293
|
+
for await (const event of options.runtime.turns.continue({ sessionId: intent.threadId, turnId: intent.expectedTurnId })) {
|
|
22294
|
+
if (event.type === "turn_started") {
|
|
22295
|
+
started = true;
|
|
22296
|
+
record.ready = true;
|
|
22297
|
+
}
|
|
22298
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) record.ready = false;
|
|
22299
|
+
}
|
|
22300
|
+
} catch (error) {
|
|
22301
|
+
if (!started) await delivery.rejectResume(intent);
|
|
22302
|
+
options.onError?.(error);
|
|
22303
|
+
} finally {
|
|
22304
|
+
await notifySettled(record);
|
|
22305
|
+
}
|
|
22306
|
+
}
|
|
22307
|
+
}
|
|
22308
|
+
}
|
|
22309
|
+
async function applyInteractionContinuations(snapshot) {
|
|
22310
|
+
for (const intent of await delivery.pendingInteractionContinuations(snapshot)) {
|
|
22311
|
+
if (active.has(intent.threadId) || await hasFreshLease(intent.threadId)) continue;
|
|
22312
|
+
if (!await delivery.claimInteractionContinuation(intent)) continue;
|
|
22313
|
+
const record = { threadId: intent.threadId, turnId: intent.expectedTurnId, groupId: intent.groupId, messageId: "", cancelled: false, task: Promise.resolve() };
|
|
22314
|
+
active.set(intent.threadId, record);
|
|
22315
|
+
record.task = continueInteraction().finally(function settled() {
|
|
22316
|
+
if (active.get(intent.threadId) === record) active.delete(intent.threadId);
|
|
22317
|
+
kick();
|
|
22318
|
+
}).catch(function report(error) {
|
|
22319
|
+
options.onError?.(error);
|
|
22320
|
+
});
|
|
22321
|
+
async function continueInteraction() {
|
|
22322
|
+
const beat = setInterval(function heartbeat() {
|
|
22323
|
+
delivery.settleInteractionContinuation({ groupId: intent.groupId, controlId: intent.controlId }).catch(function failed(error) {
|
|
22324
|
+
options.onError?.(error);
|
|
22325
|
+
});
|
|
22326
|
+
}, heartbeatMs);
|
|
22327
|
+
let stage = "read_decision";
|
|
22328
|
+
let started = false;
|
|
22329
|
+
try {
|
|
22330
|
+
const decision = intent.approvalId ? await options.ports.approvalStore.getDecision({ sessionId: intent.threadId, turnId: intent.expectedTurnId, approvalId: intent.approvalId }) : void 0;
|
|
22331
|
+
if (intent.approvalId && !decision) throw Object.assign(new Error("INTERACTION_DECISION_REQUIRED"), { code: "INTERACTION_DECISION_REQUIRED" });
|
|
22332
|
+
if (stopped || record.cancelled) {
|
|
22333
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "pending" });
|
|
22334
|
+
return;
|
|
22335
|
+
}
|
|
22336
|
+
stage = "continue";
|
|
22337
|
+
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" } } : {} })) {
|
|
22338
|
+
if (event.type === "turn_started") {
|
|
22339
|
+
started = true;
|
|
22340
|
+
stage = "after_started";
|
|
22341
|
+
record.ready = true;
|
|
22342
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "executing" });
|
|
22343
|
+
}
|
|
22344
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) record.ready = false;
|
|
22345
|
+
}
|
|
22346
|
+
await notifySettled(record);
|
|
22347
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "completed" });
|
|
22348
|
+
} catch (error) {
|
|
22349
|
+
const file = getFileOperationDiagnostic(error) ?? (error instanceof NodeStateError ? error.getStorageDiagnostic() : void 0);
|
|
22350
|
+
const code = file?.osCode ?? (error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : "CONTINUE_UNKNOWN");
|
|
22351
|
+
const failureDiagnostic = (0, import_core20.sanitizeContinuationFailure)({ stage, started, category: "unknown", code, ...file && ["lock", "temporary_write", "rename", "cleanup"].includes(file.phase) ? { filePhase: file.phase } : {} });
|
|
22352
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "failed", failureCode: "CONTINUE_FAILED", failureDiagnostic });
|
|
22353
|
+
options.onError?.(error, { threadId: intent.threadId, expectedTurnId: intent.expectedTurnId, controlId: intent.controlId, approvalId: intent.approvalId, requestId: intent.requestId, failureDiagnostic });
|
|
22354
|
+
await notifySettled(record);
|
|
22355
|
+
} finally {
|
|
22356
|
+
clearInterval(beat);
|
|
22357
|
+
}
|
|
22358
|
+
}
|
|
22359
|
+
}
|
|
22360
|
+
}
|
|
22361
|
+
function startDelivery(item) {
|
|
22362
|
+
const threadId = item.delivery.threadId;
|
|
22363
|
+
const turnId = item.delivery.reservedTurnId;
|
|
22364
|
+
if (!turnId) {
|
|
22365
|
+
void delivery.failDelivery({ groupId: item.groupId, messageId: item.delivery.messageId, reason: "start_failed" });
|
|
22366
|
+
return;
|
|
22367
|
+
}
|
|
22368
|
+
if (active.has(threadId)) {
|
|
22369
|
+
void delivery.releaseDelivery({ groupId: item.groupId, messageId: item.delivery.messageId });
|
|
22370
|
+
return;
|
|
22371
|
+
}
|
|
22372
|
+
const record = { threadId, turnId, groupId: item.groupId, messageId: item.delivery.messageId, cancelled: false, task: Promise.resolve() };
|
|
22373
|
+
record.task = runDelivery(item, record).catch(function ignore() {
|
|
22374
|
+
}).finally(function finish() {
|
|
22375
|
+
if (active.get(threadId) === record) active.delete(threadId);
|
|
22376
|
+
kick();
|
|
22377
|
+
});
|
|
22378
|
+
active.set(threadId, record);
|
|
22379
|
+
}
|
|
22380
|
+
async function notifyStarted(record, message) {
|
|
22381
|
+
if (!options.onTurnStarted) return;
|
|
22382
|
+
try {
|
|
22383
|
+
await options.onTurnStarted({
|
|
22384
|
+
threadId: record.threadId,
|
|
22385
|
+
turnId: record.turnId,
|
|
22386
|
+
prompt: { content: message.content, messageId: message.messageId, from: message.from, ...message.handoff ? { handoff: message.handoff } : {}, ...message.handoffDisplay ? { handoffDisplay: message.handoffDisplay } : {} }
|
|
22387
|
+
});
|
|
22388
|
+
} catch (error) {
|
|
22389
|
+
options.onError?.(error);
|
|
22390
|
+
}
|
|
22391
|
+
}
|
|
22392
|
+
async function notifySettled(record) {
|
|
22393
|
+
if (!options.onTurnSettled) return;
|
|
22394
|
+
try {
|
|
22395
|
+
await options.onTurnSettled({ threadId: record.threadId, turnId: record.turnId });
|
|
22396
|
+
} catch (error) {
|
|
22397
|
+
options.onError?.(error);
|
|
22398
|
+
}
|
|
22399
|
+
}
|
|
22400
|
+
async function runDelivery(item, record) {
|
|
22401
|
+
const { groupId, delivery: claimed, message } = item;
|
|
22402
|
+
const turnId = record.turnId;
|
|
22403
|
+
const existing = await options.ports.turnStore.get(turnId);
|
|
22404
|
+
if (existing) {
|
|
22405
|
+
await settle(item, record, turnId);
|
|
22406
|
+
return;
|
|
22407
|
+
}
|
|
22408
|
+
if (await hasFreshLease(record.threadId)) {
|
|
22409
|
+
await delivery.releaseDelivery({ groupId, messageId: claimed.messageId });
|
|
22410
|
+
return;
|
|
22411
|
+
}
|
|
22412
|
+
let failure;
|
|
22413
|
+
const beat = setInterval(function heartbeat() {
|
|
22414
|
+
void delivery.heartbeat({ groupId, messageId: claimed.messageId });
|
|
22415
|
+
}, heartbeatMs);
|
|
22416
|
+
beat.unref?.();
|
|
22417
|
+
let controlEnded = false;
|
|
22418
|
+
try {
|
|
22419
|
+
await delivery.heartbeat({ groupId, messageId: claimed.messageId });
|
|
22420
|
+
await notifyStarted(record, message);
|
|
22421
|
+
for await (const event of options.runtime.turns.start({
|
|
22422
|
+
sessionId: record.threadId,
|
|
22423
|
+
turnId,
|
|
22424
|
+
content: message.content,
|
|
22425
|
+
// 与页面队列同语义:这是目标空闲后的下一轮,不是新话题。
|
|
22426
|
+
continuity: { source: "claimed_queue" }
|
|
22427
|
+
})) {
|
|
22428
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) controlEnded = true;
|
|
22429
|
+
record.ready = !controlEnded;
|
|
22430
|
+
if (record.cancelled) break;
|
|
22431
|
+
}
|
|
22432
|
+
} catch (error) {
|
|
22433
|
+
failure = error;
|
|
22434
|
+
} finally {
|
|
22435
|
+
clearInterval(beat);
|
|
22436
|
+
}
|
|
22437
|
+
await settle(item, record, turnId, failure);
|
|
22438
|
+
}
|
|
22439
|
+
async function settle(item, record, turnId, failure) {
|
|
22440
|
+
const groupId = item.groupId;
|
|
22441
|
+
const messageId = item.delivery.messageId;
|
|
22442
|
+
const turn = await options.ports.turnStore.get(turnId);
|
|
22443
|
+
if (failure) {
|
|
22444
|
+
options.onError?.(failure);
|
|
22445
|
+
}
|
|
22446
|
+
if (turn) {
|
|
22447
|
+
await delivery.completeDelivery({ groupId, messageId, turnId });
|
|
22448
|
+
await notifySettled(record);
|
|
22449
|
+
return;
|
|
22450
|
+
}
|
|
22451
|
+
const code = failure?.code;
|
|
22452
|
+
if (code === "TURN_ALREADY_RUNNING") {
|
|
22453
|
+
await delivery.releaseDelivery({ groupId, messageId });
|
|
22454
|
+
return;
|
|
22455
|
+
}
|
|
22456
|
+
await delivery.failDelivery({ groupId, messageId, reason: "start_failed" });
|
|
22457
|
+
}
|
|
22458
|
+
async function stop() {
|
|
22459
|
+
stopped = true;
|
|
22460
|
+
running = false;
|
|
22461
|
+
if (timer) {
|
|
22462
|
+
clearTimeout(timer);
|
|
22463
|
+
timer = void 0;
|
|
22464
|
+
}
|
|
22465
|
+
const cancelledTurnIds = [];
|
|
22466
|
+
const unconfirmedTurnIds = [];
|
|
22467
|
+
const releasedMessageIds = [];
|
|
22468
|
+
const waitingTurnIds = [];
|
|
22469
|
+
const pendingMessageIds = [];
|
|
22470
|
+
const recoverableTurnIds = [];
|
|
22471
|
+
const tasks = [...active.values()].filter(function ownDelivery(record) {
|
|
22472
|
+
return !record.external;
|
|
22473
|
+
});
|
|
22474
|
+
for (const record of tasks) {
|
|
22475
|
+
if (record.cancelled) continue;
|
|
22476
|
+
const actual = await options.ports.turnStore.get(record.turnId);
|
|
22477
|
+
if (actual && actual.status !== "running") {
|
|
22478
|
+
if (actual.status === "waiting_approval" || actual.status === "waiting_user_input") waitingTurnIds.push(actual.id);
|
|
22479
|
+
continue;
|
|
22480
|
+
}
|
|
22481
|
+
record.cancelled = true;
|
|
22482
|
+
try {
|
|
22483
|
+
await options.runtime.turns.cancel({ sessionId: record.threadId, turnId: record.turnId });
|
|
22484
|
+
cancelledTurnIds.push(record.turnId);
|
|
22485
|
+
} catch {
|
|
22486
|
+
unconfirmedTurnIds.push(record.turnId);
|
|
22487
|
+
}
|
|
22488
|
+
}
|
|
22489
|
+
await Promise.allSettled(tasks.map(function task(record) {
|
|
22490
|
+
return record.task;
|
|
22491
|
+
}));
|
|
22492
|
+
for (const groupId of await delivery.listGroups()) {
|
|
22493
|
+
const control = await delivery.readGroup(groupId);
|
|
22494
|
+
if (!control) continue;
|
|
22495
|
+
for (const item of control.deliveries) {
|
|
22496
|
+
if (item.status === "pending" || item.status === "blocked") pendingMessageIds.push(item.messageId);
|
|
22497
|
+
const turnId = item.turnId ?? item.reservedTurnId;
|
|
22498
|
+
const turn = turnId ? await options.ports.turnStore.get(turnId) : void 0;
|
|
22499
|
+
if (turn?.status === "waiting_approval" || turn?.status === "waiting_user_input") waitingTurnIds.push(turn.id);
|
|
22500
|
+
if (turn?.status === "interrupted") recoverableTurnIds.push(turn.id);
|
|
22501
|
+
if (item.ownerId === ownerId && item.status === "claimed" && turn?.status === "running" && !cancelledTurnIds.includes(turn.id)) unconfirmedTurnIds.push(turn.id);
|
|
22502
|
+
if (item.status === "claimed" && item.ownerId === ownerId && !turn) {
|
|
22503
|
+
await delivery.releaseDelivery({ groupId, messageId: item.messageId });
|
|
22504
|
+
releasedMessageIds.push(item.messageId);
|
|
22505
|
+
pendingMessageIds.push(item.messageId);
|
|
22506
|
+
}
|
|
22507
|
+
}
|
|
22508
|
+
if (control.deliveries.some(function pending(item) {
|
|
22509
|
+
return item.status === "pending" || item.status === "blocked";
|
|
22510
|
+
})) await delivery.recordHostOffline(groupId);
|
|
22511
|
+
}
|
|
22512
|
+
for (const turnId of cancelledTurnIds) {
|
|
22513
|
+
const turn = await options.ports.turnStore.get(turnId);
|
|
22514
|
+
if (!turn || turn.status === "running") unconfirmedTurnIds.push(turnId);
|
|
22515
|
+
}
|
|
22516
|
+
return { stopped: true, cancelledTurnIds: cancelledTurnIds.filter(function confirmed(id) {
|
|
22517
|
+
return !unconfirmedTurnIds.includes(id);
|
|
22518
|
+
}), unconfirmedTurnIds: [...new Set(unconfirmedTurnIds)], releasedMessageIds, waitingTurnIds: [...new Set(waitingTurnIds)], pendingMessageIds: [...new Set(pendingMessageIds)], recoverableTurnIds: [...new Set(recoverableTurnIds)] };
|
|
22519
|
+
}
|
|
22520
|
+
function kick() {
|
|
22521
|
+
if (!running || stopped) return;
|
|
22522
|
+
idleDelayMs = pollIntervalMs;
|
|
22523
|
+
kicked = true;
|
|
22524
|
+
if (!ticking) void safeTick();
|
|
22525
|
+
}
|
|
22526
|
+
function registerExecution(input) {
|
|
22527
|
+
const previous = active.get(input.threadId);
|
|
22528
|
+
if (previous && (previous.ready || previous.turnId !== input.turnId)) throw Object.assign(new Error("TURN_ALREADY_RUNNING"), { code: "TURN_ALREADY_RUNNING" });
|
|
22529
|
+
const record = { threadId: input.threadId, turnId: input.turnId, groupId: "", messageId: "", cancelled: false, task: Promise.resolve(), external: true, ready: false, cancelExecution: input.cancel };
|
|
22530
|
+
active.set(input.threadId, record);
|
|
22531
|
+
return {
|
|
22532
|
+
activate: function activate() {
|
|
22533
|
+
if (active.get(input.threadId) === record) {
|
|
22534
|
+
record.ready = true;
|
|
22535
|
+
kick();
|
|
22536
|
+
}
|
|
22537
|
+
},
|
|
22538
|
+
release: function release() {
|
|
22539
|
+
if (active.get(input.threadId) === record) {
|
|
22540
|
+
active.delete(input.threadId);
|
|
22541
|
+
kick();
|
|
22542
|
+
}
|
|
22543
|
+
}
|
|
22544
|
+
};
|
|
22545
|
+
}
|
|
22546
|
+
async function start() {
|
|
22547
|
+
if (running) return;
|
|
22548
|
+
stopped = false;
|
|
22549
|
+
running = true;
|
|
22550
|
+
await safeTick(true);
|
|
22551
|
+
}
|
|
22552
|
+
return {
|
|
22553
|
+
start,
|
|
22554
|
+
stop,
|
|
22555
|
+
kick,
|
|
22556
|
+
registerExecution,
|
|
22557
|
+
listExecutions: function listExecutions() {
|
|
22558
|
+
return [...active.values()].map(function identity(record) {
|
|
22559
|
+
return { threadId: record.threadId, turnId: record.turnId };
|
|
22560
|
+
});
|
|
22561
|
+
},
|
|
22562
|
+
isRunning: function isRunning() {
|
|
22563
|
+
return running;
|
|
22564
|
+
},
|
|
22565
|
+
reconcile: function converge() {
|
|
22566
|
+
return delivery.reconcile({ staleMs, activeMessageIds: activeMessageIds() });
|
|
22567
|
+
}
|
|
22568
|
+
};
|
|
22569
|
+
}
|
|
22570
|
+
|
|
22571
|
+
// src/node/desktop-status-protocol.ts
|
|
22572
|
+
var DESKTOP_STATUS_VERSION = 1;
|
|
22573
|
+
var DESKTOP_STATUS_FRAME_BYTES = 64 * 1024;
|
|
22574
|
+
var DESKTOP_STATUS_QUEUE_BYTES = 256 * 1024;
|
|
22575
|
+
function isDesktopStatusId(value) {
|
|
22576
|
+
return typeof value === "string" && /^[a-zA-Z0-9:_-]{1,160}$/.test(value);
|
|
22577
|
+
}
|
|
22578
|
+
function fields(value, required, optional = []) {
|
|
22579
|
+
return !!value && typeof value === "object" && !Array.isArray(value) && required.every(function present(key2) {
|
|
22580
|
+
return Object.prototype.hasOwnProperty.call(value, key2);
|
|
22581
|
+
}) && Object.keys(value).every(function allowed(key2) {
|
|
22582
|
+
return required.includes(key2) || optional.includes(key2);
|
|
22583
|
+
});
|
|
22584
|
+
}
|
|
22585
|
+
function optionalEnum(value, values) {
|
|
22586
|
+
return value === void 0 || typeof value === "string" && values.includes(value);
|
|
22587
|
+
}
|
|
22588
|
+
function isDesktopSessionStatus(value) {
|
|
22589
|
+
if (!fields(value, ["sessionId", "selected", "relation", "freshness", "status", "lastSeq"], ["turnId", "execution", "waiting", "result", "interaction", "continuation", "recoverable"])) return false;
|
|
22590
|
+
return isDesktopStatusId(value.sessionId) && (value.turnId === void 0 || isDesktopStatusId(value.turnId)) && typeof value.selected === "boolean" && ["opened", "locallyDriven", "relatedObserved"].includes(value.relation) && ["fresh", "unknown"].includes(value.freshness) && ["idle", "running", "waiting_approval", "waiting_user_input", "completed", "failed", "interrupted"].includes(value.status) && Number.isSafeInteger(value.lastSeq) && value.lastSeq >= 0 && optionalEnum(value.execution, ["active", "inactive", "unconfirmed", "lost"]) && optionalEnum(value.waiting, ["approval", "user_input", "threads"]) && optionalEnum(value.result, ["completed", "failed", "interrupted", "limit_reached"]) && optionalEnum(value.interaction, ["pending", "decided", "expired", "unconfirmed"]) && optionalEnum(value.continuation, ["pending", "applied", "rejected", "claimed", "executing", "completed", "failed"]) && (value.recoverable === void 0 || typeof value.recoverable === "boolean");
|
|
22591
|
+
}
|
|
22592
|
+
function workspace(value) {
|
|
22593
|
+
return fields(value, ["workspaceId", "stateRootId", "projectId", "displayName"]) && isDesktopStatusId(value.workspaceId) && isDesktopStatusId(value.stateRootId) && isDesktopStatusId(value.projectId) && typeof value.displayName === "string" && value.displayName.length <= 80 && !/[\x00-\x1f\x7f/\\]/.test(value.displayName);
|
|
22594
|
+
}
|
|
22595
|
+
function isDesktopStatusFrame(value) {
|
|
22596
|
+
if (!value || typeof value !== "object") return false;
|
|
22597
|
+
const v = value;
|
|
22598
|
+
const common2 = ["protocolVersion", "desktopInstanceId", "paneId", "generation", "apInstanceId", "seq", "type"];
|
|
22599
|
+
if (v.protocolVersion !== 1 || !isDesktopStatusId(v.desktopInstanceId) || !isDesktopStatusId(v.paneId) || !isDesktopStatusId(v.apInstanceId) || !Number.isSafeInteger(v.generation) || v.generation < 1 || !Number.isSafeInteger(v.seq) || v.seq < 1) return false;
|
|
22600
|
+
if (v.type === "hello") return fields(v, [...common2, "token", "cliVersion"]) && typeof v.token === "string" && /^[0-9a-f]{64}$/.test(v.token) && typeof v.cliVersion === "string" && /^\d+\.\d+\.\d+[-\w.]*$/.test(v.cliVersion);
|
|
22601
|
+
if (v.type === "heartbeat" || v.type === "ap_exiting") return fields(v, common2);
|
|
22602
|
+
return v.type === "snapshot" && fields(v, [...common2, "snapshotId", "part", "final", "lifecycle", "sessions"], ["workspace"]) && isDesktopStatusId(v.snapshotId) && Number.isSafeInteger(v.part) && v.part >= 0 && typeof v.final === "boolean" && ["starting", "ready"].includes(v.lifecycle) && (v.workspace === void 0 || workspace(v.workspace)) && (v.lifecycle !== "ready" || v.workspace !== void 0) && Array.isArray(v.sessions) && v.sessions.length <= 128 && v.sessions.every(isDesktopSessionStatus) && (v.lifecycle !== "starting" || v.sessions.length === 0 && v.workspace === void 0);
|
|
22603
|
+
}
|
|
22604
|
+
function isDesktopStatusReply(value) {
|
|
22605
|
+
return fields(value, ["type", "seq"]) && ["accepted", "ack", "resync_required"].includes(value.type) && Number.isSafeInteger(value.seq) && value.seq >= 0;
|
|
22606
|
+
}
|
|
22607
|
+
var DesktopStatusLines = class {
|
|
22608
|
+
constructor() {
|
|
22609
|
+
this.pending = Buffer.alloc(0);
|
|
22610
|
+
}
|
|
22611
|
+
push(chunk) {
|
|
22612
|
+
const values = [];
|
|
22613
|
+
let offset = 0;
|
|
22614
|
+
while (offset < chunk.length) {
|
|
22615
|
+
const newline = chunk.indexOf(10, offset);
|
|
22616
|
+
const end = newline < 0 ? chunk.length : newline;
|
|
22617
|
+
if (this.pending.length + end - offset > DESKTOP_STATUS_FRAME_BYTES) throw new Error("STATUS_FRAME_INVALID");
|
|
22618
|
+
this.pending = Buffer.concat([this.pending, chunk.subarray(offset, end)]);
|
|
22619
|
+
if (newline < 0) break;
|
|
22620
|
+
const line = new TextDecoder("utf-8", { fatal: true }).decode(this.pending);
|
|
22621
|
+
this.pending = Buffer.alloc(0);
|
|
22622
|
+
values.push(JSON.parse(line));
|
|
22623
|
+
offset = newline + 1;
|
|
22624
|
+
}
|
|
22625
|
+
return values;
|
|
22626
|
+
}
|
|
22627
|
+
};
|
|
22628
|
+
|
|
22629
|
+
// src/node/thread-handoff.ts
|
|
22630
|
+
var import_node_crypto16 = require("node:crypto");
|
|
22631
|
+
var import_node_fs34 = __toESM(require("node:fs"));
|
|
22632
|
+
var import_node_path27 = __toESM(require("node:path"));
|
|
22633
|
+
var HANDOFF_DIRECTORY = ".autopilot";
|
|
22634
|
+
function assertWithinRoot(root, candidate) {
|
|
22635
|
+
const relative = import_node_path27.default.relative(root, candidate);
|
|
22636
|
+
if (!relative || relative.startsWith(`..${import_node_path27.default.sep}`) || relative === ".." || import_node_path27.default.isAbsolute(relative)) {
|
|
22637
|
+
throw new Error("THREAD_HANDOFF_WRITE_FAILED");
|
|
22638
|
+
}
|
|
22639
|
+
}
|
|
22640
|
+
function sha2562(content) {
|
|
22641
|
+
return (0, import_node_crypto16.createHash)("sha256").update(content, "utf8").digest("hex");
|
|
22642
|
+
}
|
|
22643
|
+
function createNodeThreadHandoffWriter(options) {
|
|
22644
|
+
const workspaceRoot = import_node_path27.default.resolve(options.workspaceRoot);
|
|
22645
|
+
function resolveTarget(handoffId) {
|
|
22646
|
+
if (!/^[0-9a-f]{16,64}$/.test(handoffId)) throw new Error("THREAD_HANDOFF_WRITE_FAILED");
|
|
22647
|
+
const realRoot = import_node_fs34.default.realpathSync(workspaceRoot);
|
|
22648
|
+
const directory = import_node_path27.default.resolve(realRoot, HANDOFF_DIRECTORY);
|
|
22649
|
+
assertWithinRoot(realRoot, directory);
|
|
22650
|
+
const filePath = import_node_path27.default.join(directory, `thread-passdown-${handoffId}.md`);
|
|
22651
|
+
assertWithinRoot(realRoot, filePath);
|
|
22652
|
+
return { directory, filePath };
|
|
22653
|
+
}
|
|
22654
|
+
async function write(input) {
|
|
22655
|
+
const { directory, filePath } = resolveTarget(input.handoffId);
|
|
22656
|
+
const content = `# Handoff\uFF1A${input.title}
|
|
22657
|
+
|
|
22658
|
+
${input.markdown}
|
|
22659
|
+
`;
|
|
22660
|
+
import_node_fs34.default.mkdirSync(directory, { recursive: true });
|
|
22661
|
+
const realDirectory = import_node_fs34.default.realpathSync(directory);
|
|
22662
|
+
assertWithinRoot(import_node_fs34.default.realpathSync(workspaceRoot), realDirectory);
|
|
22663
|
+
await withAsyncFileLock(filePath, function writeLocked() {
|
|
22664
|
+
if (import_node_fs34.default.existsSync(filePath)) {
|
|
22665
|
+
const existing = import_node_fs34.default.readFileSync(filePath, "utf8");
|
|
22666
|
+
if (existing !== content) throw new Error("THREAD_HANDOFF_CONFLICT");
|
|
22667
|
+
return;
|
|
22668
|
+
}
|
|
22669
|
+
atomicReplace(filePath, content);
|
|
22670
|
+
});
|
|
22671
|
+
const written = import_node_fs34.default.readFileSync(filePath, "utf8");
|
|
22672
|
+
if (written !== content) throw new Error("THREAD_HANDOFF_CONFLICT");
|
|
22673
|
+
return {
|
|
22674
|
+
handoffId: input.handoffId,
|
|
22675
|
+
relativePath: `${HANDOFF_DIRECTORY}/thread-passdown-${input.handoffId}.md`,
|
|
22676
|
+
sha256: sha2562(content)
|
|
22677
|
+
};
|
|
22678
|
+
}
|
|
22679
|
+
return { write };
|
|
22680
|
+
}
|
|
22681
|
+
|
|
22682
|
+
// src/node/host-identity.ts
|
|
22683
|
+
var import_node_crypto17 = require("node:crypto");
|
|
22684
|
+
var LOCAL_HUMAN_PRINCIPAL_ID = "web-local-user";
|
|
22685
|
+
function createNodeStateRootId(stateRoot) {
|
|
22686
|
+
return (0, import_node_crypto17.createHash)("sha256").update(stateRoot).digest("hex");
|
|
22687
|
+
}
|
|
21206
22688
|
// Annotate the CommonJS export names for ESM import in node:
|
|
21207
22689
|
0 && (module.exports = {
|
|
21208
22690
|
CHAT_ATTACHMENT_TTL_MS,
|
|
21209
22691
|
DEFAULT_COMPACT_TARGET_RATIO,
|
|
21210
22692
|
DEFAULT_COMPACT_TRIGGER_RATIO,
|
|
21211
22693
|
DEFAULT_CONTEXT_WINDOW_TOKENS,
|
|
22694
|
+
DESKTOP_STATUS_FRAME_BYTES,
|
|
22695
|
+
DESKTOP_STATUS_QUEUE_BYTES,
|
|
22696
|
+
DESKTOP_STATUS_VERSION,
|
|
22697
|
+
DesktopStatusLines,
|
|
22698
|
+
LOCAL_HUMAN_PRINCIPAL_ID,
|
|
21212
22699
|
NODE_CHAT_KNOWLEDGE_SPACE_ID,
|
|
21213
22700
|
NODE_STATE_SCHEMA_VERSION,
|
|
21214
22701
|
NODE_WORKSPACE_ID_VERSION,
|
|
@@ -21240,11 +22727,15 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21240
22727
|
createNodeRagRuntime,
|
|
21241
22728
|
createNodeRuntimePorts,
|
|
21242
22729
|
createNodeSandboxPort,
|
|
22730
|
+
createNodeSessionImageStore,
|
|
21243
22731
|
createNodeSessionResourceStore,
|
|
21244
22732
|
createNodeSessionStore,
|
|
21245
22733
|
createNodeSettingsLoader,
|
|
21246
22734
|
createNodeSettingsWriter,
|
|
22735
|
+
createNodeStateRootId,
|
|
21247
22736
|
createNodeStateSchemaManager,
|
|
22737
|
+
createNodeThreadHandoffWriter,
|
|
22738
|
+
createNodeThreadRunner,
|
|
21248
22739
|
createNodeTranscriptStore,
|
|
21249
22740
|
createNodeTrustPolicy,
|
|
21250
22741
|
createNodeTrustStore,
|
|
@@ -21266,6 +22757,10 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21266
22757
|
getNodeStatePaths,
|
|
21267
22758
|
getNodeStateSchemaDiagnostic,
|
|
21268
22759
|
initializeNodeStateRoot,
|
|
22760
|
+
isDesktopSessionStatus,
|
|
22761
|
+
isDesktopStatusFrame,
|
|
22762
|
+
isDesktopStatusId,
|
|
22763
|
+
isDesktopStatusReply,
|
|
21269
22764
|
isSafeSettingsFile,
|
|
21270
22765
|
loadMcpConfigFromWorkspace,
|
|
21271
22766
|
resolveNodeChatStatePaths,
|
|
@@ -21275,5 +22770,6 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21275
22770
|
resolveNodeTrustRoot,
|
|
21276
22771
|
resolveNodeUserSettingsPath,
|
|
21277
22772
|
retrieveNodeMemories,
|
|
21278
|
-
serializePosixCommand
|
|
22773
|
+
serializePosixCommand,
|
|
22774
|
+
withNodeRuntimeOwner
|
|
21279
22775
|
});
|