@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.mjs
CHANGED
|
@@ -38,9 +38,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
38
38
|
mod
|
|
39
39
|
));
|
|
40
40
|
|
|
41
|
-
// node_modules/boolbase/index.js
|
|
41
|
+
// ../../node_modules/boolbase/index.js
|
|
42
42
|
var require_boolbase = __commonJS({
|
|
43
|
-
"node_modules/boolbase/index.js"(exports, module) {
|
|
43
|
+
"../../node_modules/boolbase/index.js"(exports, module) {
|
|
44
44
|
module.exports = {
|
|
45
45
|
trueFunc: function trueFunc() {
|
|
46
46
|
return true;
|
|
@@ -52,9 +52,9 @@ var require_boolbase = __commonJS({
|
|
|
52
52
|
}
|
|
53
53
|
});
|
|
54
54
|
|
|
55
|
-
// node_modules/css-what/lib/commonjs/types.js
|
|
55
|
+
// ../../node_modules/css-what/lib/commonjs/types.js
|
|
56
56
|
var require_types = __commonJS({
|
|
57
|
-
"node_modules/css-what/lib/commonjs/types.js"(exports) {
|
|
57
|
+
"../../node_modules/css-what/lib/commonjs/types.js"(exports) {
|
|
58
58
|
"use strict";
|
|
59
59
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
60
60
|
exports.AttributeAction = exports.IgnoreCaseMode = exports.SelectorType = void 0;
|
|
@@ -92,9 +92,9 @@ var require_types = __commonJS({
|
|
|
92
92
|
}
|
|
93
93
|
});
|
|
94
94
|
|
|
95
|
-
// node_modules/css-what/lib/commonjs/parse.js
|
|
95
|
+
// ../../node_modules/css-what/lib/commonjs/parse.js
|
|
96
96
|
var require_parse = __commonJS({
|
|
97
|
-
"node_modules/css-what/lib/commonjs/parse.js"(exports) {
|
|
97
|
+
"../../node_modules/css-what/lib/commonjs/parse.js"(exports) {
|
|
98
98
|
"use strict";
|
|
99
99
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
100
100
|
exports.parse = exports.isTraversal = void 0;
|
|
@@ -447,9 +447,9 @@ var require_parse = __commonJS({
|
|
|
447
447
|
}
|
|
448
448
|
});
|
|
449
449
|
|
|
450
|
-
// node_modules/css-what/lib/commonjs/stringify.js
|
|
450
|
+
// ../../node_modules/css-what/lib/commonjs/stringify.js
|
|
451
451
|
var require_stringify = __commonJS({
|
|
452
|
-
"node_modules/css-what/lib/commonjs/stringify.js"(exports) {
|
|
452
|
+
"../../node_modules/css-what/lib/commonjs/stringify.js"(exports) {
|
|
453
453
|
"use strict";
|
|
454
454
|
var __spreadArray = exports && exports.__spreadArray || function(to, from, pack) {
|
|
455
455
|
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
@@ -571,9 +571,9 @@ var require_stringify = __commonJS({
|
|
|
571
571
|
}
|
|
572
572
|
});
|
|
573
573
|
|
|
574
|
-
// node_modules/css-what/lib/commonjs/index.js
|
|
574
|
+
// ../../node_modules/css-what/lib/commonjs/index.js
|
|
575
575
|
var require_commonjs = __commonJS({
|
|
576
|
-
"node_modules/css-what/lib/commonjs/index.js"(exports) {
|
|
576
|
+
"../../node_modules/css-what/lib/commonjs/index.js"(exports) {
|
|
577
577
|
"use strict";
|
|
578
578
|
var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
579
579
|
if (k2 === void 0) k2 = k;
|
|
@@ -2169,14 +2169,20 @@ var runtimeMessages = {
|
|
|
2169
2169
|
};
|
|
2170
2170
|
var NodeStateError = class extends Error {
|
|
2171
2171
|
/** 只使用固定错误码作为消息,恢复信息保存为不可枚举的私有字段。 */
|
|
2172
|
-
constructor(code, recovery) {
|
|
2172
|
+
constructor(code, recovery, storage) {
|
|
2173
2173
|
super(code);
|
|
2174
2174
|
this.code = code;
|
|
2175
2175
|
this.name = "NodeStateError";
|
|
2176
2176
|
this.#recovery = recovery ? { ...recovery } : void 0;
|
|
2177
|
+
this.#storage = storage ? { ...storage } : void 0;
|
|
2177
2178
|
}
|
|
2178
2179
|
#recovery;
|
|
2180
|
+
#storage;
|
|
2179
2181
|
/** 受信宿主显式取得恢复信息副本,不得将它投影到 HTTP 或模型事件。 */
|
|
2182
|
+
/** 受信CLI诊断显式读取,序列化错误不会暴露内部阶段。 */
|
|
2183
|
+
getStorageDiagnostic() {
|
|
2184
|
+
return this.#storage ? { ...this.#storage } : void 0;
|
|
2185
|
+
}
|
|
2180
2186
|
getRecoveryDiagnostic() {
|
|
2181
2187
|
return this.#recovery ? { ...this.#recovery } : void 0;
|
|
2182
2188
|
}
|
|
@@ -2192,15 +2198,15 @@ var NodeChatError = class extends Error {
|
|
|
2192
2198
|
function createNodeIdentityError(code) {
|
|
2193
2199
|
return new AgentRuntimeError(code, runtimeMessages[code]);
|
|
2194
2200
|
}
|
|
2195
|
-
function toNodeBoundaryError(error, fallback) {
|
|
2201
|
+
function toNodeBoundaryError(error, fallback, storage) {
|
|
2196
2202
|
if (error instanceof Error && "code" in error && typeof error.code === "string") {
|
|
2197
2203
|
if (error.name === "AgentRuntimeError" && Object.prototype.hasOwnProperty.call(runtimeMessages, error.code)) return createNodeIdentityError(error.code);
|
|
2198
2204
|
if (error.name === "NodeStateError" && stateCodes.includes(error.code)) {
|
|
2199
|
-
return new NodeStateError(error.code, error instanceof NodeStateError ? error.getRecoveryDiagnostic() : void 0);
|
|
2205
|
+
return new NodeStateError(error.code, error instanceof NodeStateError ? error.getRecoveryDiagnostic() : void 0, storage ?? (error instanceof NodeStateError ? error.getStorageDiagnostic() : void 0));
|
|
2200
2206
|
}
|
|
2201
2207
|
if (error.name === "NodeChatError" && chatCodes.includes(error.code)) return new NodeChatError(error.code);
|
|
2202
2208
|
}
|
|
2203
|
-
return stateCodes.includes(fallback) ? new NodeStateError(fallback) : new NodeChatError(fallback);
|
|
2209
|
+
return stateCodes.includes(fallback) ? new NodeStateError(fallback, void 0, storage) : new NodeChatError(fallback);
|
|
2204
2210
|
}
|
|
2205
2211
|
|
|
2206
2212
|
// src/node/create-node-runtime-ports.ts
|
|
@@ -5416,12 +5422,12 @@ function parseSkillFrontmatter(frontmatter) {
|
|
|
5416
5422
|
return void 0;
|
|
5417
5423
|
}
|
|
5418
5424
|
}
|
|
5419
|
-
function readSkillString(
|
|
5420
|
-
const value =
|
|
5425
|
+
function readSkillString(fields2, key2) {
|
|
5426
|
+
const value = fields2[key2];
|
|
5421
5427
|
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
5422
5428
|
}
|
|
5423
|
-
function readSkillBoolean(
|
|
5424
|
-
const value =
|
|
5429
|
+
function readSkillBoolean(fields2, key2) {
|
|
5430
|
+
const value = fields2[key2];
|
|
5425
5431
|
if (typeof value === "boolean") return value;
|
|
5426
5432
|
if (typeof value !== "string") return void 0;
|
|
5427
5433
|
const normalized = value.trim().toLocaleLowerCase();
|
|
@@ -5429,8 +5435,8 @@ function readSkillBoolean(fields, key2) {
|
|
|
5429
5435
|
if (["false", "no", "off", "0"].includes(normalized)) return false;
|
|
5430
5436
|
return void 0;
|
|
5431
5437
|
}
|
|
5432
|
-
function readSkillTools(
|
|
5433
|
-
const value =
|
|
5438
|
+
function readSkillTools(fields2) {
|
|
5439
|
+
const value = fields2["allowed-tools"];
|
|
5434
5440
|
if (Array.isArray(value) && value.every(function isToolName(item) {
|
|
5435
5441
|
return typeof item === "string" && item.trim();
|
|
5436
5442
|
})) {
|
|
@@ -5444,9 +5450,9 @@ function readSkillTools(fields) {
|
|
|
5444
5450
|
return item.trim();
|
|
5445
5451
|
}).filter(Boolean);
|
|
5446
5452
|
}
|
|
5447
|
-
function readSkillDescription(
|
|
5448
|
-
const explicit = readSkillString(
|
|
5449
|
-
const whenToUse = readSkillString(
|
|
5453
|
+
function readSkillDescription(fields2, markdown) {
|
|
5454
|
+
const explicit = readSkillString(fields2, "description");
|
|
5455
|
+
const whenToUse = readSkillString(fields2, "when_to_use") ?? readSkillString(fields2, "when-to-use");
|
|
5450
5456
|
const description = explicit ?? markdown.trim().split(/\r?\n\s*\r?\n/u).find(function firstParagraph(paragraph) {
|
|
5451
5457
|
return paragraph.trim();
|
|
5452
5458
|
})?.trim();
|
|
@@ -5468,18 +5474,18 @@ function parseSkill(filePath, source, root) {
|
|
|
5468
5474
|
const content = fs3.readFileSync(filePath, "utf8");
|
|
5469
5475
|
const match = /^---\r?\n([\s\S]{0,4096}?)\r?\n---\r?\n/.exec(content);
|
|
5470
5476
|
if (!match) return void 0;
|
|
5471
|
-
const
|
|
5472
|
-
if (!
|
|
5477
|
+
const fields2 = parseSkillFrontmatter(match[1]);
|
|
5478
|
+
if (!fields2) return void 0;
|
|
5473
5479
|
const name = path3.basename(path3.dirname(filePath));
|
|
5474
|
-
const description = readSkillDescription(
|
|
5480
|
+
const description = readSkillDescription(fields2, content.slice(match[0].length));
|
|
5475
5481
|
if (!/^[a-z0-9-]{1,64}$/.test(name) || !description) return void 0;
|
|
5476
|
-
const declaredName = readSkillString(
|
|
5482
|
+
const declaredName = readSkillString(fields2, "name");
|
|
5477
5483
|
const displayName = declaredName && declaredName.length <= 64 ? declaredName : name;
|
|
5478
|
-
const modelInvocable = !(readSkillBoolean(
|
|
5479
|
-
const userInvocable = readSkillBoolean(
|
|
5480
|
-
const argumentHint = readSkillString(
|
|
5481
|
-
const whenToUse = readSkillString(
|
|
5482
|
-
const allowedTools = readSkillTools(
|
|
5484
|
+
const modelInvocable = !(readSkillBoolean(fields2, "disable-model-invocation") ?? false);
|
|
5485
|
+
const userInvocable = readSkillBoolean(fields2, "user-invocable") ?? true;
|
|
5486
|
+
const argumentHint = readSkillString(fields2, "argument-hint") ?? readSkillString(fields2, "dash-hint");
|
|
5487
|
+
const whenToUse = readSkillString(fields2, "when_to_use") ?? readSkillString(fields2, "when-to-use");
|
|
5488
|
+
const allowedTools = readSkillTools(fields2);
|
|
5483
5489
|
const canonical = fs3.realpathSync.native(filePath);
|
|
5484
5490
|
const contentHash = crypto2.createHash("sha256").update(content).digest("hex");
|
|
5485
5491
|
const skillId = `${source}:${crypto2.createHash("sha256").update(canonical).digest("hex").slice(0, 16)}:${contentHash.slice(0, 16)}`;
|
|
@@ -7943,7 +7949,7 @@ var Parser = class {
|
|
|
7943
7949
|
}
|
|
7944
7950
|
};
|
|
7945
7951
|
|
|
7946
|
-
// ../../node_modules/
|
|
7952
|
+
// ../../node_modules/domelementtype/lib/esm/index.js
|
|
7947
7953
|
var esm_exports = {};
|
|
7948
7954
|
__export(esm_exports, {
|
|
7949
7955
|
CDATA: () => CDATA,
|
|
@@ -7959,16 +7965,16 @@ __export(esm_exports, {
|
|
|
7959
7965
|
isTag: () => isTag
|
|
7960
7966
|
});
|
|
7961
7967
|
var ElementType;
|
|
7962
|
-
(function(
|
|
7963
|
-
|
|
7964
|
-
|
|
7965
|
-
|
|
7966
|
-
|
|
7967
|
-
|
|
7968
|
-
|
|
7969
|
-
|
|
7970
|
-
|
|
7971
|
-
|
|
7968
|
+
(function(ElementType2) {
|
|
7969
|
+
ElementType2["Root"] = "root";
|
|
7970
|
+
ElementType2["Text"] = "text";
|
|
7971
|
+
ElementType2["Directive"] = "directive";
|
|
7972
|
+
ElementType2["Comment"] = "comment";
|
|
7973
|
+
ElementType2["Script"] = "script";
|
|
7974
|
+
ElementType2["Style"] = "style";
|
|
7975
|
+
ElementType2["Tag"] = "tag";
|
|
7976
|
+
ElementType2["CDATA"] = "cdata";
|
|
7977
|
+
ElementType2["Doctype"] = "doctype";
|
|
7972
7978
|
})(ElementType || (ElementType = {}));
|
|
7973
7979
|
function isTag(elem) {
|
|
7974
7980
|
return elem.type === ElementType.Tag || elem.type === ElementType.Script || elem.type === ElementType.Style;
|
|
@@ -10941,8 +10947,8 @@ var Comment3 = class _Comment extends CharacterData {
|
|
|
10941
10947
|
};
|
|
10942
10948
|
|
|
10943
10949
|
// node_modules/domutils/lib/esm/index.js
|
|
10944
|
-
var
|
|
10945
|
-
__export(
|
|
10950
|
+
var esm_exports4 = {};
|
|
10951
|
+
__export(esm_exports4, {
|
|
10946
10952
|
DocumentPosition: () => DocumentPosition2,
|
|
10947
10953
|
append: () => append3,
|
|
10948
10954
|
appendChild: () => appendChild2,
|
|
@@ -10973,7 +10979,7 @@ __export(esm_exports5, {
|
|
|
10973
10979
|
isCDATA: () => isCDATA2,
|
|
10974
10980
|
isComment: () => isComment2,
|
|
10975
10981
|
isDocument: () => isDocument2,
|
|
10976
|
-
isTag: () =>
|
|
10982
|
+
isTag: () => isTag3,
|
|
10977
10983
|
isText: () => isText2,
|
|
10978
10984
|
nextElementSibling: () => nextElementSibling3,
|
|
10979
10985
|
prepend: () => prepend2,
|
|
@@ -10987,47 +10993,21 @@ __export(esm_exports5, {
|
|
|
10987
10993
|
uniqueSort: () => uniqueSort2
|
|
10988
10994
|
});
|
|
10989
10995
|
|
|
10990
|
-
// node_modules/domelementtype/lib/esm/index.js
|
|
10991
|
-
var ElementType2;
|
|
10992
|
-
(function(ElementType3) {
|
|
10993
|
-
ElementType3["Root"] = "root";
|
|
10994
|
-
ElementType3["Text"] = "text";
|
|
10995
|
-
ElementType3["Directive"] = "directive";
|
|
10996
|
-
ElementType3["Comment"] = "comment";
|
|
10997
|
-
ElementType3["Script"] = "script";
|
|
10998
|
-
ElementType3["Style"] = "style";
|
|
10999
|
-
ElementType3["Tag"] = "tag";
|
|
11000
|
-
ElementType3["CDATA"] = "cdata";
|
|
11001
|
-
ElementType3["Doctype"] = "doctype";
|
|
11002
|
-
})(ElementType2 || (ElementType2 = {}));
|
|
11003
|
-
function isTag3(elem) {
|
|
11004
|
-
return elem.type === ElementType2.Tag || elem.type === ElementType2.Script || elem.type === ElementType2.Style;
|
|
11005
|
-
}
|
|
11006
|
-
var Root2 = ElementType2.Root;
|
|
11007
|
-
var Text3 = ElementType2.Text;
|
|
11008
|
-
var Directive2 = ElementType2.Directive;
|
|
11009
|
-
var Comment4 = ElementType2.Comment;
|
|
11010
|
-
var Script2 = ElementType2.Script;
|
|
11011
|
-
var Style2 = ElementType2.Style;
|
|
11012
|
-
var Tag2 = ElementType2.Tag;
|
|
11013
|
-
var CDATA3 = ElementType2.CDATA;
|
|
11014
|
-
var Doctype2 = ElementType2.Doctype;
|
|
11015
|
-
|
|
11016
10996
|
// node_modules/domhandler/lib/esm/node.js
|
|
11017
|
-
function
|
|
11018
|
-
return
|
|
10997
|
+
function isTag3(node) {
|
|
10998
|
+
return isTag(node);
|
|
11019
10999
|
}
|
|
11020
11000
|
function isCDATA2(node) {
|
|
11021
|
-
return node.type ===
|
|
11001
|
+
return node.type === ElementType.CDATA;
|
|
11022
11002
|
}
|
|
11023
11003
|
function isText2(node) {
|
|
11024
|
-
return node.type ===
|
|
11004
|
+
return node.type === ElementType.Text;
|
|
11025
11005
|
}
|
|
11026
11006
|
function isComment2(node) {
|
|
11027
|
-
return node.type ===
|
|
11007
|
+
return node.type === ElementType.Comment;
|
|
11028
11008
|
}
|
|
11029
11009
|
function isDocument2(node) {
|
|
11030
|
-
return node.type ===
|
|
11010
|
+
return node.type === ElementType.Root;
|
|
11031
11011
|
}
|
|
11032
11012
|
function hasChildren2(node) {
|
|
11033
11013
|
return Object.prototype.hasOwnProperty.call(node, "children");
|
|
@@ -11714,21 +11694,21 @@ function render2(node, options = {}) {
|
|
|
11714
11694
|
var esm_default2 = render2;
|
|
11715
11695
|
function renderNode2(node, options) {
|
|
11716
11696
|
switch (node.type) {
|
|
11717
|
-
case
|
|
11697
|
+
case Root:
|
|
11718
11698
|
return render2(node.children, options);
|
|
11719
11699
|
// @ts-expect-error We don't use `Doctype` yet
|
|
11720
|
-
case
|
|
11721
|
-
case
|
|
11700
|
+
case Doctype:
|
|
11701
|
+
case Directive:
|
|
11722
11702
|
return renderDirective2(node);
|
|
11723
|
-
case
|
|
11703
|
+
case Comment:
|
|
11724
11704
|
return renderComment2(node);
|
|
11725
|
-
case
|
|
11705
|
+
case CDATA:
|
|
11726
11706
|
return renderCdata2(node);
|
|
11727
|
-
case
|
|
11728
|
-
case
|
|
11729
|
-
case
|
|
11707
|
+
case Script:
|
|
11708
|
+
case Style:
|
|
11709
|
+
case Tag:
|
|
11730
11710
|
return renderTag2(node, options);
|
|
11731
|
-
case
|
|
11711
|
+
case Text:
|
|
11732
11712
|
return renderText2(node, options);
|
|
11733
11713
|
}
|
|
11734
11714
|
}
|
|
@@ -11809,7 +11789,7 @@ function getInnerHTML2(node, options) {
|
|
|
11809
11789
|
function getText2(node) {
|
|
11810
11790
|
if (Array.isArray(node))
|
|
11811
11791
|
return node.map(getText2).join("");
|
|
11812
|
-
if (
|
|
11792
|
+
if (isTag3(node))
|
|
11813
11793
|
return node.name === "br" ? "\n" : getText2(node.children);
|
|
11814
11794
|
if (isCDATA2(node))
|
|
11815
11795
|
return getText2(node.children);
|
|
@@ -11830,7 +11810,7 @@ function textContent2(node) {
|
|
|
11830
11810
|
function innerText2(node) {
|
|
11831
11811
|
if (Array.isArray(node))
|
|
11832
11812
|
return node.map(innerText2).join("");
|
|
11833
|
-
if (hasChildren2(node) && (node.type ===
|
|
11813
|
+
if (hasChildren2(node) && (node.type === ElementType.Tag || isCDATA2(node))) {
|
|
11834
11814
|
return innerText2(node.children);
|
|
11835
11815
|
}
|
|
11836
11816
|
if (isText2(node))
|
|
@@ -11873,13 +11853,13 @@ function getName2(elem) {
|
|
|
11873
11853
|
}
|
|
11874
11854
|
function nextElementSibling3(elem) {
|
|
11875
11855
|
let { next } = elem;
|
|
11876
|
-
while (next !== null && !
|
|
11856
|
+
while (next !== null && !isTag3(next))
|
|
11877
11857
|
({ next } = next);
|
|
11878
11858
|
return next;
|
|
11879
11859
|
}
|
|
11880
11860
|
function prevElementSibling2(elem) {
|
|
11881
11861
|
let { prev } = elem;
|
|
11882
|
-
while (prev !== null && !
|
|
11862
|
+
while (prev !== null && !isTag3(prev))
|
|
11883
11863
|
({ prev } = prev);
|
|
11884
11864
|
return prev;
|
|
11885
11865
|
}
|
|
@@ -12011,7 +11991,7 @@ function findOne2(test, nodes, recurse = true) {
|
|
|
12011
11991
|
const searchedNodes = Array.isArray(nodes) ? nodes : [nodes];
|
|
12012
11992
|
for (let i = 0; i < searchedNodes.length; i++) {
|
|
12013
11993
|
const node = searchedNodes[i];
|
|
12014
|
-
if (
|
|
11994
|
+
if (isTag3(node) && test(node)) {
|
|
12015
11995
|
return node;
|
|
12016
11996
|
}
|
|
12017
11997
|
if (recurse && hasChildren2(node) && node.children.length > 0) {
|
|
@@ -12023,7 +12003,7 @@ function findOne2(test, nodes, recurse = true) {
|
|
|
12023
12003
|
return null;
|
|
12024
12004
|
}
|
|
12025
12005
|
function existsOne2(test, nodes) {
|
|
12026
|
-
return (Array.isArray(nodes) ? nodes : [nodes]).some((node) =>
|
|
12006
|
+
return (Array.isArray(nodes) ? nodes : [nodes]).some((node) => isTag3(node) && test(node) || hasChildren2(node) && existsOne2(test, node.children));
|
|
12027
12007
|
}
|
|
12028
12008
|
function findAll2(test, nodes) {
|
|
12029
12009
|
const result = [];
|
|
@@ -12039,7 +12019,7 @@ function findAll2(test, nodes) {
|
|
|
12039
12019
|
continue;
|
|
12040
12020
|
}
|
|
12041
12021
|
const elem = nodeStack[0][indexStack[0]++];
|
|
12042
|
-
if (
|
|
12022
|
+
if (isTag3(elem) && test(elem))
|
|
12043
12023
|
result.push(elem);
|
|
12044
12024
|
if (hasChildren2(elem) && elem.children.length > 0) {
|
|
12045
12025
|
indexStack.unshift(0);
|
|
@@ -12052,11 +12032,11 @@ function findAll2(test, nodes) {
|
|
|
12052
12032
|
var Checks2 = {
|
|
12053
12033
|
tag_name(name) {
|
|
12054
12034
|
if (typeof name === "function") {
|
|
12055
|
-
return (elem) =>
|
|
12035
|
+
return (elem) => isTag3(elem) && name(elem.name);
|
|
12056
12036
|
} else if (name === "*") {
|
|
12057
|
-
return
|
|
12037
|
+
return isTag3;
|
|
12058
12038
|
}
|
|
12059
|
-
return (elem) =>
|
|
12039
|
+
return (elem) => isTag3(elem) && elem.name === name;
|
|
12060
12040
|
},
|
|
12061
12041
|
tag_type(type2) {
|
|
12062
12042
|
if (typeof type2 === "function") {
|
|
@@ -12073,9 +12053,9 @@ var Checks2 = {
|
|
|
12073
12053
|
};
|
|
12074
12054
|
function getAttribCheck2(attrib, value) {
|
|
12075
12055
|
if (typeof value === "function") {
|
|
12076
|
-
return (elem) =>
|
|
12056
|
+
return (elem) => isTag3(elem) && value(elem.attribs[attrib]);
|
|
12077
12057
|
}
|
|
12078
|
-
return (elem) =>
|
|
12058
|
+
return (elem) => isTag3(elem) && elem.attribs[attrib] === value;
|
|
12079
12059
|
}
|
|
12080
12060
|
function combineFuncs2(a, b) {
|
|
12081
12061
|
return (elem) => a(elem) || b(elem);
|
|
@@ -12562,7 +12542,7 @@ var attributeRules = {
|
|
|
12562
12542
|
// node_modules/css-select/lib/esm/pseudo-selectors/index.js
|
|
12563
12543
|
var import_css_what2 = __toESM(require_commonjs(), 1);
|
|
12564
12544
|
|
|
12565
|
-
// node_modules/nth-check/lib/esm/parse.js
|
|
12545
|
+
// ../../node_modules/nth-check/lib/esm/parse.js
|
|
12566
12546
|
var whitespace = /* @__PURE__ */ new Set([9, 10, 12, 13, 32]);
|
|
12567
12547
|
var ZERO = "0".charCodeAt(0);
|
|
12568
12548
|
var NINE = "9".charCodeAt(0);
|
|
@@ -12619,7 +12599,7 @@ function parse(formula) {
|
|
|
12619
12599
|
}
|
|
12620
12600
|
}
|
|
12621
12601
|
|
|
12622
|
-
// node_modules/nth-check/lib/esm/compile.js
|
|
12602
|
+
// ../../node_modules/nth-check/lib/esm/compile.js
|
|
12623
12603
|
var import_boolbase2 = __toESM(require_boolbase(), 1);
|
|
12624
12604
|
function compile(parsed) {
|
|
12625
12605
|
const a = parsed[0];
|
|
@@ -12637,7 +12617,7 @@ function compile(parsed) {
|
|
|
12637
12617
|
return a > 1 ? (index) => index >= b && index % absA === bMod : (index) => index <= b && index % absA === bMod;
|
|
12638
12618
|
}
|
|
12639
12619
|
|
|
12640
|
-
// node_modules/nth-check/lib/esm/index.js
|
|
12620
|
+
// ../../node_modules/nth-check/lib/esm/index.js
|
|
12641
12621
|
function nthCheck(formula) {
|
|
12642
12622
|
return compile(parse(formula));
|
|
12643
12623
|
}
|
|
@@ -13198,13 +13178,13 @@ function reduceRules(a, b) {
|
|
|
13198
13178
|
// node_modules/css-select/lib/esm/index.js
|
|
13199
13179
|
var defaultEquals = (a, b) => a === b;
|
|
13200
13180
|
var defaultOptions = {
|
|
13201
|
-
adapter:
|
|
13181
|
+
adapter: esm_exports4,
|
|
13202
13182
|
equals: defaultEquals
|
|
13203
13183
|
};
|
|
13204
13184
|
function convertOptionFormats(options) {
|
|
13205
13185
|
var _a4, _b, _c, _d;
|
|
13206
13186
|
const opts = options !== null && options !== void 0 ? options : defaultOptions;
|
|
13207
|
-
(_a4 = opts.adapter) !== null && _a4 !== void 0 ? _a4 : opts.adapter =
|
|
13187
|
+
(_a4 = opts.adapter) !== null && _a4 !== void 0 ? _a4 : opts.adapter = esm_exports4;
|
|
13208
13188
|
(_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;
|
|
13209
13189
|
return opts;
|
|
13210
13190
|
}
|
|
@@ -13251,9 +13231,9 @@ function is2(elem, query2, options) {
|
|
|
13251
13231
|
|
|
13252
13232
|
// node_modules/linkedom/esm/shared/matches.js
|
|
13253
13233
|
var { isArray } = Array;
|
|
13254
|
-
var
|
|
13234
|
+
var isTag4 = ({ nodeType }) => nodeType === ELEMENT_NODE;
|
|
13255
13235
|
var existsOne3 = (test, elements) => elements.some(
|
|
13256
|
-
(element) =>
|
|
13236
|
+
(element) => isTag4(element) && (test(element) || existsOne3(test, getChildren3(element)))
|
|
13257
13237
|
);
|
|
13258
13238
|
var getAttributeValue3 = (element, name) => name === "class" ? element.classList.value : element.getAttribute(name);
|
|
13259
13239
|
var getChildren3 = ({ childNodes }) => childNodes;
|
|
@@ -13269,7 +13249,7 @@ var getSiblings3 = (element) => {
|
|
|
13269
13249
|
var getText3 = (node) => {
|
|
13270
13250
|
if (isArray(node))
|
|
13271
13251
|
return node.map(getText3).join("");
|
|
13272
|
-
if (
|
|
13252
|
+
if (isTag4(node))
|
|
13273
13253
|
return getText3(getChildren3(node));
|
|
13274
13254
|
if (node.nodeType === TEXT_NODE)
|
|
13275
13255
|
return node.data;
|
|
@@ -13296,7 +13276,7 @@ var removeSubsets3 = (nodes) => {
|
|
|
13296
13276
|
var findAll3 = (test, nodes) => {
|
|
13297
13277
|
const matches3 = [];
|
|
13298
13278
|
for (const node of nodes) {
|
|
13299
|
-
if (
|
|
13279
|
+
if (isTag4(node)) {
|
|
13300
13280
|
if (test(node))
|
|
13301
13281
|
matches3.push(node);
|
|
13302
13282
|
matches3.push(...findAll3(test, getChildren3(node)));
|
|
@@ -13311,7 +13291,7 @@ var findOne3 = (test, nodes) => {
|
|
|
13311
13291
|
return null;
|
|
13312
13292
|
};
|
|
13313
13293
|
var adapter = {
|
|
13314
|
-
isTag:
|
|
13294
|
+
isTag: isTag4,
|
|
13315
13295
|
existsOne: existsOne3,
|
|
13316
13296
|
getAttributeValue: getAttributeValue3,
|
|
13317
13297
|
getChildren: getChildren3,
|
|
@@ -13344,7 +13324,7 @@ var matches = (element, selectors) => is2(
|
|
|
13344
13324
|
);
|
|
13345
13325
|
|
|
13346
13326
|
// node_modules/linkedom/esm/interface/text.js
|
|
13347
|
-
var
|
|
13327
|
+
var Text4 = class _Text extends CharacterData {
|
|
13348
13328
|
constructor(ownerDocument, data = "") {
|
|
13349
13329
|
super(ownerDocument, "#text", TEXT_NODE, data);
|
|
13350
13330
|
}
|
|
@@ -13383,7 +13363,7 @@ var insert = (parentNode, child, nodes) => {
|
|
|
13383
13363
|
const { ownerDocument } = parentNode;
|
|
13384
13364
|
for (const node of nodes)
|
|
13385
13365
|
parentNode.insertBefore(
|
|
13386
|
-
isNode(node) ? node : new
|
|
13366
|
+
isNode(node) ? node : new Text4(ownerDocument, node),
|
|
13387
13367
|
child
|
|
13388
13368
|
);
|
|
13389
13369
|
};
|
|
@@ -14194,7 +14174,7 @@ var Element3 = class extends ParentNode {
|
|
|
14194
14174
|
set textContent(text) {
|
|
14195
14175
|
this.replaceChildren();
|
|
14196
14176
|
if (text != null && text !== "")
|
|
14197
|
-
this.appendChild(new
|
|
14177
|
+
this.appendChild(new Text4(this.ownerDocument, text));
|
|
14198
14178
|
}
|
|
14199
14179
|
get innerHTML() {
|
|
14200
14180
|
return getInnerHtml(this);
|
|
@@ -14568,11 +14548,11 @@ function CharacterData2() {
|
|
|
14568
14548
|
}
|
|
14569
14549
|
setPrototypeOf(CharacterData2, CharacterData);
|
|
14570
14550
|
CharacterData2.prototype = CharacterData.prototype;
|
|
14571
|
-
function
|
|
14551
|
+
function Comment5() {
|
|
14572
14552
|
illegalConstructor();
|
|
14573
14553
|
}
|
|
14574
|
-
setPrototypeOf(
|
|
14575
|
-
|
|
14554
|
+
setPrototypeOf(Comment5, Comment3);
|
|
14555
|
+
Comment5.prototype = Comment3.prototype;
|
|
14576
14556
|
function DocumentFragment2() {
|
|
14577
14557
|
illegalConstructor();
|
|
14578
14558
|
}
|
|
@@ -14598,11 +14578,11 @@ function ShadowRoot2() {
|
|
|
14598
14578
|
}
|
|
14599
14579
|
setPrototypeOf(ShadowRoot2, ShadowRoot);
|
|
14600
14580
|
ShadowRoot2.prototype = ShadowRoot.prototype;
|
|
14601
|
-
function
|
|
14581
|
+
function Text5() {
|
|
14602
14582
|
illegalConstructor();
|
|
14603
14583
|
}
|
|
14604
|
-
setPrototypeOf(
|
|
14605
|
-
|
|
14584
|
+
setPrototypeOf(Text5, Text4);
|
|
14585
|
+
Text5.prototype = Text4.prototype;
|
|
14606
14586
|
function SVGElement2() {
|
|
14607
14587
|
illegalConstructor();
|
|
14608
14588
|
}
|
|
@@ -14612,13 +14592,13 @@ var Facades = {
|
|
|
14612
14592
|
Attr: Attr2,
|
|
14613
14593
|
CDATASection: CDATASection2,
|
|
14614
14594
|
CharacterData: CharacterData2,
|
|
14615
|
-
Comment:
|
|
14595
|
+
Comment: Comment5,
|
|
14616
14596
|
DocumentFragment: DocumentFragment2,
|
|
14617
14597
|
DocumentType: DocumentType2,
|
|
14618
14598
|
Element: Element4,
|
|
14619
14599
|
Node: Node3,
|
|
14620
14600
|
ShadowRoot: ShadowRoot2,
|
|
14621
|
-
Text:
|
|
14601
|
+
Text: Text5,
|
|
14622
14602
|
SVGElement: SVGElement2
|
|
14623
14603
|
};
|
|
14624
14604
|
|
|
@@ -16634,7 +16614,7 @@ var Document3 = class extends NonElementParentNode {
|
|
|
16634
16614
|
return range;
|
|
16635
16615
|
}
|
|
16636
16616
|
createTextNode(textContent3) {
|
|
16637
|
-
return new
|
|
16617
|
+
return new Text4(this, textContent3);
|
|
16638
16618
|
}
|
|
16639
16619
|
createTreeWalker(root, whatToShow = -1) {
|
|
16640
16620
|
return new TreeWalker(root, whatToShow);
|
|
@@ -16983,13 +16963,13 @@ async function validatePublicWebUrl(rawUrl, options = {}) {
|
|
|
16983
16963
|
if (value.length > 2e3) throw new Error("URL_TOO_LONG");
|
|
16984
16964
|
url = new URL(value);
|
|
16985
16965
|
} catch {
|
|
16986
|
-
throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u65E0\u6548");
|
|
16966
|
+
throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u65E0\u6548", void 0, "url_not_allowed");
|
|
16987
16967
|
}
|
|
16988
16968
|
if (url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password || !url.hostname) {
|
|
16989
|
-
throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE");
|
|
16969
|
+
throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE", void 0, "url_not_allowed");
|
|
16990
16970
|
}
|
|
16991
16971
|
const hostname = normalizeHostname(url.hostname).toLowerCase();
|
|
16992
|
-
if (isBlockedHostname(hostname)) throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE");
|
|
16972
|
+
if (isBlockedHostname(hostname)) throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE", void 0, "url_not_allowed");
|
|
16993
16973
|
let addresses;
|
|
16994
16974
|
const literalFamily = isIP(hostname);
|
|
16995
16975
|
if (literalFamily === 4 || literalFamily === 6) {
|
|
@@ -16999,14 +16979,14 @@ async function validatePublicWebUrl(rawUrl, options = {}) {
|
|
|
16999
16979
|
addresses = await (options.resolveDns ?? resolveWebFetchDns)(hostname, options.signal);
|
|
17000
16980
|
} catch (error) {
|
|
17001
16981
|
if (options.signal?.aborted || error instanceof Error && error.name === "AbortError") throw createAbortError();
|
|
17002
|
-
throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u89E3\u6790\u5931\u8D25");
|
|
16982
|
+
throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u89E3\u6790\u5931\u8D25", void 0, "dns_failed");
|
|
17003
16983
|
}
|
|
17004
16984
|
}
|
|
17005
|
-
if (addresses.length === 0) throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u89E3\u6790\u5931\u8D25");
|
|
16985
|
+
if (addresses.length === 0) throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u89E3\u6790\u5931\u8D25", void 0, "dns_failed");
|
|
17006
16986
|
const unique = /* @__PURE__ */ new Map();
|
|
17007
16987
|
for (const record of addresses) {
|
|
17008
16988
|
if (!isPublicWebAddress(record.address, record.family)) {
|
|
17009
|
-
throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE");
|
|
16989
|
+
throw new WebFetchCapabilityError("WEB_URL_BLOCKED", "\u7F51\u9875\u5730\u5740\u4E0D\u5141\u8BB8\u8BBF\u95EE", void 0, "non_public_address");
|
|
17010
16990
|
}
|
|
17011
16991
|
unique.set(`${record.family}:${record.address}`, { address: record.address, family: record.family });
|
|
17012
16992
|
}
|
|
@@ -17215,7 +17195,7 @@ function createSafeWebFetchCapability(options = {}) {
|
|
|
17215
17195
|
/** 读取明确 URL;跨域目标和剩余跳数只交给 Core,在审批后续接。 */
|
|
17216
17196
|
async fetch(input) {
|
|
17217
17197
|
if (input.redirectsRemaining !== void 0 && (!Number.isInteger(input.redirectsRemaining) || input.redirectsRemaining < 0 || input.redirectsRemaining > MAX_REDIRECTS)) {
|
|
17218
|
-
throw new WebFetchCapabilityError2("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u9884\u7B97\u65E0\u6548");
|
|
17198
|
+
throw new WebFetchCapabilityError2("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u9884\u7B97\u65E0\u6548", void 0, "redirect_rejected");
|
|
17219
17199
|
}
|
|
17220
17200
|
const original = await validatePublicWebUrl(input.url, { resolveDns, signal: input.signal });
|
|
17221
17201
|
let current = original;
|
|
@@ -17228,19 +17208,19 @@ function createSafeWebFetchCapability(options = {}) {
|
|
|
17228
17208
|
const location = readHeader(response.headers, "location");
|
|
17229
17209
|
if (!location || redirectCount >= redirectLimit) {
|
|
17230
17210
|
response.abort();
|
|
17231
|
-
throw new WebFetchCapabilityError2("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u65E0\u6548\u6216\u8D85\u8FC7\u4E0A\u9650");
|
|
17211
|
+
throw new WebFetchCapabilityError2("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u65E0\u6548\u6216\u8D85\u8FC7\u4E0A\u9650", void 0, "redirect_rejected");
|
|
17232
17212
|
}
|
|
17233
17213
|
let redirectUrl;
|
|
17234
17214
|
try {
|
|
17235
17215
|
redirectUrl = new URL(location, current.url);
|
|
17236
17216
|
} catch {
|
|
17237
17217
|
response.abort();
|
|
17238
|
-
throw new WebFetchCapabilityError2("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u5730\u5740\u65E0\u6548");
|
|
17218
|
+
throw new WebFetchCapabilityError2("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u5730\u5740\u65E0\u6548", void 0, "redirect_rejected");
|
|
17239
17219
|
}
|
|
17240
17220
|
if (redirectUrl.hostname.toLowerCase() !== current.url.hostname.toLowerCase()) {
|
|
17241
17221
|
response.abort();
|
|
17242
17222
|
if (!["http:", "https:"].includes(redirectUrl.protocol) || redirectUrl.username || redirectUrl.password) {
|
|
17243
|
-
throw new WebFetchCapabilityError2("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u5730\u5740\u65E0\u6548");
|
|
17223
|
+
throw new WebFetchCapabilityError2("WEB_URL_BLOCKED", "\u7F51\u9875\u91CD\u5B9A\u5411\u5730\u5740\u65E0\u6548", void 0, "redirect_rejected");
|
|
17244
17224
|
}
|
|
17245
17225
|
throw new WebFetchCapabilityError2("WEB_REDIRECT_REQUIRES_APPROVAL", "\u7F51\u9875\u91CD\u5B9A\u5411\u9700\u8981\u65B0\u7684\u57DF\u540D\u5BA1\u6279", {
|
|
17246
17226
|
url: redirectUrl.toString(),
|
|
@@ -17345,7 +17325,7 @@ function hostExecutionCapabilityReport() {
|
|
|
17345
17325
|
installed: false,
|
|
17346
17326
|
provisioned: false,
|
|
17347
17327
|
diagnostics: [
|
|
17348
|
-
"Windows \u5BBF\u4E3B\u6267\u884C\u6A21\u5F0F\uFF1A\u8FDB\u7A0B\u6C99\u7BB1\u5DF2\u505C\u7528\uFF0C\
|
|
17328
|
+
"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"
|
|
17349
17329
|
]
|
|
17350
17330
|
};
|
|
17351
17331
|
}
|
|
@@ -17392,7 +17372,7 @@ function loadSrtRuntimeSurface() {
|
|
|
17392
17372
|
}
|
|
17393
17373
|
|
|
17394
17374
|
// src/node/sandbox/node-sandbox-port.ts
|
|
17395
|
-
import
|
|
17375
|
+
import path9 from "node:path";
|
|
17396
17376
|
|
|
17397
17377
|
// src/node/file-mutation-locks.ts
|
|
17398
17378
|
import os2 from "node:os";
|
|
@@ -17404,6 +17384,16 @@ import fs5 from "node:fs";
|
|
|
17404
17384
|
import fsp from "node:fs/promises";
|
|
17405
17385
|
import { randomUUID } from "node:crypto";
|
|
17406
17386
|
import path4 from "node:path";
|
|
17387
|
+
var fileDiagnostics = /* @__PURE__ */ new WeakMap();
|
|
17388
|
+
function getFileOperationDiagnostic(error) {
|
|
17389
|
+
return error && typeof error === "object" ? fileDiagnostics.get(error) : void 0;
|
|
17390
|
+
}
|
|
17391
|
+
function rememberFileFailure(error, diagnostic) {
|
|
17392
|
+
if (!error || typeof error !== "object") return;
|
|
17393
|
+
const code = error.code;
|
|
17394
|
+
const osCode = ["EACCES", "EPERM", "ENOENT", "EEXIST", "ENOSPC", "EIO", "EMFILE", "ENFILE", "EBUSY", "EROFS", "ENOTDIR", "ETIMEDOUT"].includes(code ?? "") ? code : void 0;
|
|
17395
|
+
fileDiagnostics.set(error, { ...diagnostic, ...osCode ? { osCode } : {} });
|
|
17396
|
+
}
|
|
17407
17397
|
var fileLocks = /* @__PURE__ */ new Map();
|
|
17408
17398
|
var PROCESS_LOCK_RETRY_MS = 10;
|
|
17409
17399
|
var PROCESS_LOCK_TIMEOUT_MS = 3e4;
|
|
@@ -17496,15 +17486,31 @@ async function acquireProcessLock(filePath, requireExitedOwner = false) {
|
|
|
17496
17486
|
}
|
|
17497
17487
|
}
|
|
17498
17488
|
}
|
|
17499
|
-
function
|
|
17489
|
+
async function removeOwnedProcessLock(lockPath, ownerId) {
|
|
17490
|
+
const startedAt = Date.now();
|
|
17491
|
+
while (true) {
|
|
17492
|
+
try {
|
|
17493
|
+
const metadata = JSON.parse(await fsp.readFile(lockPath, "utf8"));
|
|
17494
|
+
if (metadata.ownerId !== ownerId) return;
|
|
17495
|
+
await fsp.unlink(lockPath);
|
|
17496
|
+
return;
|
|
17497
|
+
} catch (error) {
|
|
17498
|
+
const code = error.code;
|
|
17499
|
+
if (code === "ENOENT") return;
|
|
17500
|
+
if ((code === "EPERM" || code === "EACCES" || code === "EBUSY") && Date.now() - startedAt < PROCESS_LOCK_TIMEOUT_MS) {
|
|
17501
|
+
await waitForProcessLock();
|
|
17502
|
+
continue;
|
|
17503
|
+
}
|
|
17504
|
+
rememberFileFailure(error, { phase: "cleanup", cleanupFailed: true });
|
|
17505
|
+
throw error;
|
|
17506
|
+
}
|
|
17507
|
+
}
|
|
17508
|
+
}
|
|
17509
|
+
async function releaseProcessLock(handle) {
|
|
17500
17510
|
try {
|
|
17501
17511
|
fs5.closeSync(handle.descriptor);
|
|
17502
17512
|
} finally {
|
|
17503
|
-
|
|
17504
|
-
const metadata = JSON.parse(fs5.readFileSync(handle.lockPath, "utf8"));
|
|
17505
|
-
if (metadata.ownerId === handle.ownerId) fs5.unlinkSync(handle.lockPath);
|
|
17506
|
-
} catch {
|
|
17507
|
-
}
|
|
17513
|
+
await removeOwnedProcessLock(handle.lockPath, handle.ownerId);
|
|
17508
17514
|
}
|
|
17509
17515
|
}
|
|
17510
17516
|
async function withFileLock(filePath, operation, options) {
|
|
@@ -17518,11 +17524,18 @@ async function withFileLock(filePath, operation, options) {
|
|
|
17518
17524
|
fileLocks.set(key2, queued);
|
|
17519
17525
|
try {
|
|
17520
17526
|
await previous;
|
|
17521
|
-
const
|
|
17527
|
+
const startedAt = Date.now();
|
|
17528
|
+
let handle;
|
|
17529
|
+
try {
|
|
17530
|
+
handle = await acquireProcessLock(key2, options?.requireExitedOwner);
|
|
17531
|
+
} catch (error) {
|
|
17532
|
+
rememberFileFailure(error, { phase: "lock", lockWaitMs: Date.now() - startedAt });
|
|
17533
|
+
throw error;
|
|
17534
|
+
}
|
|
17522
17535
|
try {
|
|
17523
17536
|
return await operation();
|
|
17524
17537
|
} finally {
|
|
17525
|
-
releaseProcessLock(handle);
|
|
17538
|
+
await releaseProcessLock(handle);
|
|
17526
17539
|
}
|
|
17527
17540
|
} finally {
|
|
17528
17541
|
release();
|
|
@@ -17562,11 +17575,7 @@ async function releaseAsyncProcessLock(handle) {
|
|
|
17562
17575
|
try {
|
|
17563
17576
|
await handle.descriptor.close();
|
|
17564
17577
|
} finally {
|
|
17565
|
-
|
|
17566
|
-
const metadata = JSON.parse(await fsp.readFile(handle.lockPath, "utf8"));
|
|
17567
|
-
if (metadata.ownerId === handle.ownerId) await fsp.unlink(handle.lockPath);
|
|
17568
|
-
} catch {
|
|
17569
|
-
}
|
|
17578
|
+
await removeOwnedProcessLock(handle.lockPath, handle.ownerId);
|
|
17570
17579
|
}
|
|
17571
17580
|
}
|
|
17572
17581
|
async function withAsyncFileLock(filePath, operation) {
|
|
@@ -17597,11 +17606,59 @@ function ensureParentDirectory(filePath) {
|
|
|
17597
17606
|
function atomicReplace(filePath, content) {
|
|
17598
17607
|
ensureParentDirectory(filePath);
|
|
17599
17608
|
const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
17609
|
+
let phase = "temporary_write";
|
|
17610
|
+
let failure;
|
|
17600
17611
|
try {
|
|
17601
17612
|
fs5.writeFileSync(temporaryPath, content, { encoding: "utf8", flag: "wx" });
|
|
17613
|
+
phase = "rename";
|
|
17602
17614
|
fs5.renameSync(temporaryPath, filePath);
|
|
17615
|
+
} catch (error) {
|
|
17616
|
+
failure = error;
|
|
17617
|
+
rememberFileFailure(error, { phase });
|
|
17618
|
+
throw error;
|
|
17603
17619
|
} finally {
|
|
17604
|
-
|
|
17620
|
+
try {
|
|
17621
|
+
if (fs5.existsSync(temporaryPath)) fs5.unlinkSync(temporaryPath);
|
|
17622
|
+
} catch (error) {
|
|
17623
|
+
if (failure) rememberFileFailure(failure, { ...getFileOperationDiagnostic(failure), cleanupFailed: true });
|
|
17624
|
+
else {
|
|
17625
|
+
rememberFileFailure(error, { phase: "cleanup" });
|
|
17626
|
+
throw error;
|
|
17627
|
+
}
|
|
17628
|
+
}
|
|
17629
|
+
}
|
|
17630
|
+
}
|
|
17631
|
+
async function replaceSessionFile(filePath, content) {
|
|
17632
|
+
if (process.platform !== "win32") return atomicReplace(filePath, content);
|
|
17633
|
+
ensureParentDirectory(filePath);
|
|
17634
|
+
const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
17635
|
+
const delays = [20, 40, 80, 160];
|
|
17636
|
+
let attempts = 0;
|
|
17637
|
+
const started = performance.now();
|
|
17638
|
+
try {
|
|
17639
|
+
await fsp.writeFile(temporaryPath, content, { encoding: "utf8", flag: "wx" });
|
|
17640
|
+
for (; ; ) {
|
|
17641
|
+
attempts++;
|
|
17642
|
+
try {
|
|
17643
|
+
await fsp.rename(temporaryPath, filePath);
|
|
17644
|
+
return;
|
|
17645
|
+
} catch (error) {
|
|
17646
|
+
const delay = delays[attempts - 1];
|
|
17647
|
+
if (!delay || !["EBUSY", "EPERM", "EACCES"].includes(error.code ?? "")) throw error;
|
|
17648
|
+
await new Promise(function backoff(resolve) {
|
|
17649
|
+
setTimeout(resolve, delay);
|
|
17650
|
+
});
|
|
17651
|
+
}
|
|
17652
|
+
}
|
|
17653
|
+
} catch (error) {
|
|
17654
|
+
let cleanupFailed = false;
|
|
17655
|
+
try {
|
|
17656
|
+
await fsp.rm(temporaryPath, { force: true });
|
|
17657
|
+
} catch {
|
|
17658
|
+
cleanupFailed = true;
|
|
17659
|
+
}
|
|
17660
|
+
rememberFileFailure(error, { phase: attempts ? "rename" : "temporary_write", attempts, elapsedMs: Math.round(performance.now() - started), cleanupFailed });
|
|
17661
|
+
throw error;
|
|
17605
17662
|
}
|
|
17606
17663
|
}
|
|
17607
17664
|
function safeFilePath(directory, key2, extension) {
|
|
@@ -17677,22 +17734,37 @@ async function withNodeFileMutationLocks(canonicalTargets, operation) {
|
|
|
17677
17734
|
}
|
|
17678
17735
|
|
|
17679
17736
|
// src/node/state-root.ts
|
|
17680
|
-
import
|
|
17681
|
-
import { createHash as
|
|
17737
|
+
import fs8 from "node:fs";
|
|
17738
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
17682
17739
|
import os3 from "node:os";
|
|
17683
|
-
import
|
|
17740
|
+
import path8 from "node:path";
|
|
17684
17741
|
|
|
17685
17742
|
// src/node/state-schema-manager.ts
|
|
17686
17743
|
import fs6 from "node:fs";
|
|
17687
17744
|
import path6 from "node:path";
|
|
17688
17745
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
17746
|
+
function hasExitedLockOwner(file) {
|
|
17747
|
+
try {
|
|
17748
|
+
const metadata = JSON.parse(fs6.readFileSync(file, "utf8"));
|
|
17749
|
+
if (!Number.isSafeInteger(metadata?.pid) || metadata.pid <= 0) return false;
|
|
17750
|
+
try {
|
|
17751
|
+
process.kill(metadata.pid, 0);
|
|
17752
|
+
} catch (error) {
|
|
17753
|
+
return error.code === "ESRCH";
|
|
17754
|
+
}
|
|
17755
|
+
return false;
|
|
17756
|
+
} catch {
|
|
17757
|
+
return false;
|
|
17758
|
+
}
|
|
17759
|
+
}
|
|
17689
17760
|
function assertPlainStateTree(root) {
|
|
17690
17761
|
const entry = fs6.lstatSync(root);
|
|
17691
17762
|
if (entry.isSymbolicLink() || !entry.isDirectory() && !entry.isFile()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
17692
17763
|
if (!entry.isDirectory()) return;
|
|
17693
17764
|
for (const name of fs6.readdirSync(root)) {
|
|
17694
|
-
|
|
17695
|
-
assertPlainStateTree(
|
|
17765
|
+
const child = path6.join(root, name);
|
|
17766
|
+
assertPlainStateTree(child);
|
|
17767
|
+
if (name.endsWith(".lock") && !hasExitedLockOwner(child)) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17696
17768
|
}
|
|
17697
17769
|
}
|
|
17698
17770
|
function acquireSchemaLock(root) {
|
|
@@ -17755,6 +17827,14 @@ function createBackupPath(root, fromVersion, toVersion) {
|
|
|
17755
17827
|
function backupStateRoot(root, fromVersion, toVersion) {
|
|
17756
17828
|
if (!hasDurableState(root)) return void 0;
|
|
17757
17829
|
assertPlainStateTree(root);
|
|
17830
|
+
const leases = path6.join(root, "leases");
|
|
17831
|
+
if (fs6.existsSync(leases)) {
|
|
17832
|
+
for (const file of fs6.readdirSync(leases)) {
|
|
17833
|
+
if (!file.endsWith(".json")) continue;
|
|
17834
|
+
const record = JSON.parse(fs6.readFileSync(path6.join(leases, file), "utf8"));
|
|
17835
|
+
if (Number.isFinite(record?.lease?.heartbeatAt) && Date.now() - record.lease.heartbeatAt <= 45e3) throw new NodeStateError("STATE_SCHEMA_BUSY");
|
|
17836
|
+
}
|
|
17837
|
+
}
|
|
17758
17838
|
const backupPath = createBackupPath(root, fromVersion, toVersion);
|
|
17759
17839
|
const backupRoot = path6.dirname(backupPath);
|
|
17760
17840
|
if (fs6.existsSync(backupRoot) && fs6.lstatSync(backupRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
@@ -17840,6 +17920,11 @@ function createNodeStateSchemaManager(options) {
|
|
|
17840
17920
|
if (!Number.isInteger(fromVersion) || !Number.isInteger(toVersion)) {
|
|
17841
17921
|
throw new NodeStateError("STATE_SCHEMA_VERSION_INVALID");
|
|
17842
17922
|
}
|
|
17923
|
+
for (let version = fromVersion; version < toVersion; version++) {
|
|
17924
|
+
if (!options.migrations.some(function adjacent(step) {
|
|
17925
|
+
return step.fromVersion === version && step.toVersion === version + 1;
|
|
17926
|
+
})) throw new NodeStateError("STATE_SCHEMA_MIGRATION_MISSING");
|
|
17927
|
+
}
|
|
17843
17928
|
const backupPath = backup(fromVersion, toVersion);
|
|
17844
17929
|
try {
|
|
17845
17930
|
if (fs6.existsSync(root)) fs6.cpSync(root, stagingRoot, { recursive: true, errorOnExist: true });
|
|
@@ -17890,7 +17975,14 @@ function normalizeNodeSession(value, id) {
|
|
|
17890
17975
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
17891
17976
|
const session = value;
|
|
17892
17977
|
if (session.id !== id || !Number.isFinite(session.createdAt) || !Number.isFinite(session.updatedAt)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
17893
|
-
const
|
|
17978
|
+
const source = session.creationSource;
|
|
17979
|
+
const managed = session.managedExecution;
|
|
17980
|
+
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");
|
|
17981
|
+
if (source !== void 0) {
|
|
17982
|
+
const actor = source?.actor;
|
|
17983
|
+
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");
|
|
17984
|
+
}
|
|
17985
|
+
const mode = session.productMode;
|
|
17894
17986
|
if (mode === "chat") {
|
|
17895
17987
|
if (session.projectId !== void 0 || !["none", "web", "rag"].includes(session.chatRetrievalMode ?? "")) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17896
17988
|
} else if (mode !== "work" || session.chatRetrievalMode !== void 0 || typeof session.projectId !== "string" || !session.projectId.trim()) {
|
|
@@ -17899,13 +17991,63 @@ function normalizeNodeSession(value, id) {
|
|
|
17899
17991
|
return { ...session, productMode: mode };
|
|
17900
17992
|
}
|
|
17901
17993
|
function assertNodeSessionIdentity(previous, next) {
|
|
17994
|
+
if (JSON.stringify(previous.managedExecution) !== JSON.stringify(next.managedExecution)) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17995
|
+
if (JSON.stringify(previous.collaborationAllowedTools) !== JSON.stringify(next.collaborationAllowedTools)) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17996
|
+
if (JSON.stringify(previous.creationSource) !== JSON.stringify(next.creationSource)) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17997
|
+
if (previous.collaborationCreationId !== next.collaborationCreationId) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17902
17998
|
if (previous.workContextVersion !== next.workContextVersion) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17903
17999
|
if (previous.productMode !== next.productMode || previous.projectId !== next.projectId) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
17904
18000
|
if (previous.chatRetrievalMode !== next.chatRetrievalMode) throw createNodeIdentityError("CHAT_RETRIEVAL_MODE_LOCKED");
|
|
17905
18001
|
}
|
|
17906
18002
|
|
|
18003
|
+
// src/node/state-upgrade.ts
|
|
18004
|
+
import fs7 from "node:fs";
|
|
18005
|
+
import path7 from "node:path";
|
|
18006
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
18007
|
+
function upgradeSessionIdentity(root, allowLegacyWork) {
|
|
18008
|
+
const directory = path7.join(root, "sessions");
|
|
18009
|
+
if (!fs7.existsSync(directory)) return;
|
|
18010
|
+
for (const file of fs7.readdirSync(directory)) {
|
|
18011
|
+
if (!file.endsWith(".json")) continue;
|
|
18012
|
+
const target = path7.join(directory, file);
|
|
18013
|
+
let value;
|
|
18014
|
+
try {
|
|
18015
|
+
value = JSON.parse(fs7.readFileSync(target, "utf8"));
|
|
18016
|
+
} catch {
|
|
18017
|
+
throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18018
|
+
}
|
|
18019
|
+
const missingMode = value && typeof value === "object" && value.productMode === void 0;
|
|
18020
|
+
if (missingMode && allowLegacyWork) value.productMode = "work";
|
|
18021
|
+
const session = normalizeNodeSession(value, file.slice(0, -5));
|
|
18022
|
+
if (missingMode && allowLegacyWork) fs7.writeFileSync(target, JSON.stringify(session, null, 2), "utf8");
|
|
18023
|
+
}
|
|
18024
|
+
}
|
|
18025
|
+
function upgradeThreadCreationSources(root) {
|
|
18026
|
+
upgradeSessionIdentity(root, false);
|
|
18027
|
+
const groups = path7.join(root, "threads", "groups");
|
|
18028
|
+
if (!fs7.existsSync(groups)) return;
|
|
18029
|
+
for (const groupId of fs7.readdirSync(groups)) {
|
|
18030
|
+
const file = path7.join(groups, groupId, "control.json");
|
|
18031
|
+
if (!fs7.existsSync(file)) continue;
|
|
18032
|
+
const control = JSON.parse(fs7.readFileSync(file, "utf8"));
|
|
18033
|
+
if (control.group?.groupId !== groupId || !Array.isArray(control.creates)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18034
|
+
for (const intent of control.creates) {
|
|
18035
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(intent.threadId)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18036
|
+
const target = path7.join(root, "sessions", `${intent.threadId}.json`);
|
|
18037
|
+
if (!fs7.existsSync(target)) continue;
|
|
18038
|
+
const session = normalizeNodeSession(JSON.parse(fs7.readFileSync(target, "utf8")), intent.threadId);
|
|
18039
|
+
const creationId = createHash2("sha256").update(JSON.stringify([groupId, intent.actorKey, intent.requestId])).digest("hex");
|
|
18040
|
+
if (session.collaborationCreationId !== creationId || session.projectId !== control.group.projectId) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18041
|
+
const source = { actor: intent.from, requestId: intent.requestId };
|
|
18042
|
+
const next = normalizeNodeSession({ ...session, creationSource: source }, session.id);
|
|
18043
|
+
if (session.creationSource !== void 0 && JSON.stringify(session.creationSource) !== JSON.stringify(source)) throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
18044
|
+
if (session.creationSource === void 0) fs7.writeFileSync(target, JSON.stringify(next, null, 2), "utf8");
|
|
18045
|
+
}
|
|
18046
|
+
}
|
|
18047
|
+
}
|
|
18048
|
+
|
|
17907
18049
|
// src/node/state-root.ts
|
|
17908
|
-
var NODE_STATE_SCHEMA_VERSION =
|
|
18050
|
+
var NODE_STATE_SCHEMA_VERSION = 8;
|
|
17909
18051
|
var NODE_WORKSPACE_ID_VERSION = 1;
|
|
17910
18052
|
var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
17911
18053
|
fromVersion: 0,
|
|
@@ -17916,47 +18058,47 @@ var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
|
17916
18058
|
fromVersion: 1,
|
|
17917
18059
|
toVersion: 2,
|
|
17918
18060
|
migrate(stagingRoot) {
|
|
17919
|
-
|
|
18061
|
+
fs8.mkdirSync(path8.join(stagingRoot, "jobs"), { recursive: true });
|
|
17920
18062
|
}
|
|
17921
18063
|
}, {
|
|
17922
18064
|
fromVersion: 2,
|
|
17923
18065
|
toVersion: 3,
|
|
17924
18066
|
migrate(stagingRoot) {
|
|
17925
|
-
|
|
17926
|
-
|
|
17927
|
-
|
|
17928
|
-
|
|
18067
|
+
fs8.mkdirSync(path8.join(stagingRoot, "mutations"), { recursive: true });
|
|
18068
|
+
fs8.mkdirSync(path8.join(stagingRoot, "mutation-blobs"), { recursive: true });
|
|
18069
|
+
fs8.mkdirSync(path8.join(stagingRoot, "mutation-locks"), { recursive: true });
|
|
18070
|
+
fs8.mkdirSync(path8.join(stagingRoot, "undo-transactions"), { recursive: true });
|
|
17929
18071
|
}
|
|
17930
18072
|
}, {
|
|
17931
18073
|
fromVersion: 3,
|
|
17932
18074
|
toVersion: 4,
|
|
17933
18075
|
migrate(stagingRoot) {
|
|
17934
|
-
|
|
18076
|
+
fs8.mkdirSync(path8.join(stagingRoot, "questions"), { recursive: true });
|
|
17935
18077
|
}
|
|
17936
18078
|
}, {
|
|
17937
18079
|
fromVersion: 4,
|
|
17938
18080
|
toVersion: 5,
|
|
17939
18081
|
/** 仅在迁移副本补写产品身份;缺失归属只能采用唯一已有 Project,不能猜工作区。 */
|
|
17940
18082
|
migrate(stagingRoot) {
|
|
17941
|
-
const sessions =
|
|
17942
|
-
if (!
|
|
17943
|
-
const projects =
|
|
17944
|
-
const candidates =
|
|
18083
|
+
const sessions = path8.join(stagingRoot, "sessions");
|
|
18084
|
+
if (!fs8.existsSync(sessions)) return;
|
|
18085
|
+
const projects = path8.join(stagingRoot, "projects");
|
|
18086
|
+
const candidates = fs8.existsSync(projects) ? fs8.readdirSync(projects).filter(
|
|
17945
18087
|
/** 只检查现有 Project 记录,不创建新的工作区身份。 */
|
|
17946
18088
|
function projectFile(file) {
|
|
17947
18089
|
return file.endsWith(".json");
|
|
17948
18090
|
}
|
|
17949
18091
|
) : [];
|
|
17950
|
-
for (const file of
|
|
18092
|
+
for (const file of fs8.readdirSync(sessions)) {
|
|
17951
18093
|
if (!file.endsWith(".json")) continue;
|
|
17952
|
-
const target =
|
|
17953
|
-
const value = JSON.parse(
|
|
18094
|
+
const target = path8.join(sessions, file);
|
|
18095
|
+
const value = JSON.parse(fs8.readFileSync(target, "utf8"));
|
|
17954
18096
|
if (value && value.productMode === void 0 && value.projectId === void 0 && candidates.length === 1) {
|
|
17955
|
-
const project = JSON.parse(
|
|
18097
|
+
const project = JSON.parse(fs8.readFileSync(path8.join(projects, candidates[0]), "utf8"));
|
|
17956
18098
|
if (project.id === candidates[0].slice(0, -5) && typeof project.workspaceRoot === "string" && project.workspaceRoot) value.projectId = project.id;
|
|
17957
18099
|
}
|
|
17958
18100
|
const session = normalizeNodeSession(value, file.slice(0, -5));
|
|
17959
|
-
|
|
18101
|
+
fs8.writeFileSync(target, JSON.stringify(session, null, 2), "utf8");
|
|
17960
18102
|
}
|
|
17961
18103
|
}
|
|
17962
18104
|
}, {
|
|
@@ -17964,70 +18106,87 @@ var NODE_STATE_SCHEMA_MIGRATIONS = [{
|
|
|
17964
18106
|
toVersion: 6,
|
|
17965
18107
|
migrate() {
|
|
17966
18108
|
}
|
|
18109
|
+
}, {
|
|
18110
|
+
fromVersion: 6,
|
|
18111
|
+
toVersion: 7,
|
|
18112
|
+
/** v7 严格校验产品身份;旧 Work 缺省值在副本中显式落盘。 */
|
|
18113
|
+
migrate(stagingRoot) {
|
|
18114
|
+
upgradeSessionIdentity(stagingRoot, true);
|
|
18115
|
+
}
|
|
18116
|
+
}, {
|
|
18117
|
+
fromVersion: 7,
|
|
18118
|
+
toVersion: 8,
|
|
18119
|
+
/** 新来源只从已有持久意图恢复;旧进展仍保留为无任务归属的会话进展。 */
|
|
18120
|
+
migrate(stagingRoot) {
|
|
18121
|
+
upgradeThreadCreationSources(stagingRoot);
|
|
18122
|
+
}
|
|
17967
18123
|
}];
|
|
17968
18124
|
function canonicalizeNodePath(candidate, baseDirectory = process.cwd()) {
|
|
17969
|
-
const resolved =
|
|
18125
|
+
const resolved = path8.resolve(baseDirectory, candidate);
|
|
17970
18126
|
try {
|
|
17971
|
-
return
|
|
18127
|
+
return fs8.realpathSync.native(resolved);
|
|
17972
18128
|
} catch {
|
|
17973
18129
|
return resolved;
|
|
17974
18130
|
}
|
|
17975
18131
|
}
|
|
17976
18132
|
function createNodeWorkspaceId(workspaceRoot, baseDirectory) {
|
|
17977
18133
|
const canonicalRoot = canonicalizeNodePath(workspaceRoot, baseDirectory);
|
|
17978
|
-
const digest2 =
|
|
18134
|
+
const digest2 = createHash3("sha256").update(canonicalRoot).digest("hex").slice(0, 24);
|
|
17979
18135
|
return `v${NODE_WORKSPACE_ID_VERSION}-${digest2}`;
|
|
17980
18136
|
}
|
|
17981
18137
|
function resolveNodeGlobalStateRoot(options = {}) {
|
|
17982
18138
|
const baseDirectory = options.cwd ?? process.cwd();
|
|
17983
|
-
const defaultRoot = process.env.LOCALAPPDATA ?
|
|
18139
|
+
const defaultRoot = process.env.LOCALAPPDATA ? path8.join(process.env.LOCALAPPDATA, "autopilot-agent") : path8.join(os3.homedir(), ".autopilot-agent");
|
|
17984
18140
|
return canonicalizeNodePath(options.globalStateRoot ?? defaultRoot, baseDirectory);
|
|
17985
18141
|
}
|
|
17986
18142
|
function resolveNodeStateRoot(options = {}) {
|
|
17987
18143
|
const baseDirectory = options.cwd ?? process.cwd();
|
|
17988
18144
|
if (options.stateRoot) return canonicalizeNodePath(options.stateRoot, baseDirectory);
|
|
17989
18145
|
const workspaceRoot = options.workspaceRoot ?? baseDirectory;
|
|
17990
|
-
return
|
|
18146
|
+
return path8.join(resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: baseDirectory }), "workspaces", createNodeWorkspaceId(workspaceRoot, baseDirectory));
|
|
17991
18147
|
}
|
|
17992
18148
|
function resolveNodeTrustRoot(options) {
|
|
17993
18149
|
const stateRoot = canonicalizeNodePath(options.stateRoot);
|
|
17994
|
-
return canonicalizeNodePath(options.trustRoot ??
|
|
18150
|
+
return canonicalizeNodePath(options.trustRoot ?? path8.resolve(stateRoot, "..", "agent"));
|
|
17995
18151
|
}
|
|
17996
18152
|
function getNodeStatePaths(stateRoot) {
|
|
17997
18153
|
const root = canonicalizeNodePath(stateRoot);
|
|
17998
18154
|
return {
|
|
17999
18155
|
root,
|
|
18000
|
-
schemaFile:
|
|
18001
|
-
sessionsDir:
|
|
18002
|
-
checkpointsDir:
|
|
18003
|
-
transcriptsDir:
|
|
18004
|
-
projectsDir:
|
|
18005
|
-
turnsDir:
|
|
18006
|
-
approvalsDir:
|
|
18007
|
-
inboxDir:
|
|
18008
|
-
leasesDir:
|
|
18009
|
-
jobsDir:
|
|
18010
|
-
mutationsDir:
|
|
18011
|
-
mutationBlobsDir:
|
|
18012
|
-
mutationLocksDir:
|
|
18013
|
-
undoTransactionsDir:
|
|
18014
|
-
questionsDir:
|
|
18156
|
+
schemaFile: path8.join(root, "schema.json"),
|
|
18157
|
+
sessionsDir: path8.join(root, "sessions"),
|
|
18158
|
+
checkpointsDir: path8.join(root, "checkpoints"),
|
|
18159
|
+
transcriptsDir: path8.join(root, "transcripts"),
|
|
18160
|
+
projectsDir: path8.join(root, "projects"),
|
|
18161
|
+
turnsDir: path8.join(root, "turns"),
|
|
18162
|
+
approvalsDir: path8.join(root, "approvals"),
|
|
18163
|
+
inboxDir: path8.join(root, "inbox"),
|
|
18164
|
+
leasesDir: path8.join(root, "leases"),
|
|
18165
|
+
jobsDir: path8.join(root, "jobs"),
|
|
18166
|
+
mutationsDir: path8.join(root, "mutations"),
|
|
18167
|
+
mutationBlobsDir: path8.join(root, "mutation-blobs"),
|
|
18168
|
+
mutationLocksDir: path8.join(root, "mutation-locks"),
|
|
18169
|
+
undoTransactionsDir: path8.join(root, "undo-transactions"),
|
|
18170
|
+
questionsDir: path8.join(root, "questions")
|
|
18015
18171
|
};
|
|
18016
18172
|
}
|
|
18017
18173
|
function assertNodeStateSchema(stateRoot) {
|
|
18018
18174
|
const paths = getNodeStatePaths(stateRoot);
|
|
18019
|
-
if (!
|
|
18020
|
-
createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations:
|
|
18175
|
+
if (!fs8.existsSync(paths.schemaFile)) throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
18176
|
+
createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: [] }).verify();
|
|
18021
18177
|
}
|
|
18022
18178
|
function ensureNodeStateRoot(stateRoot) {
|
|
18023
18179
|
return initializeNodeStateRoot(stateRoot);
|
|
18024
18180
|
}
|
|
18025
18181
|
function initializeNodeStateRoot(stateRoot) {
|
|
18026
18182
|
try {
|
|
18027
|
-
if (
|
|
18183
|
+
if (fs8.existsSync(stateRoot) && fs8.lstatSync(stateRoot).isSymbolicLink()) throw new NodeStateError("STATE_SCHEMA_UNSAFE_PATH");
|
|
18028
18184
|
const paths = getNodeStatePaths(stateRoot);
|
|
18185
|
+
const recovering = fs8.existsSync(`${paths.root}.schema-original`);
|
|
18186
|
+
if (!recovering && !fs8.existsSync(paths.schemaFile) && fs8.existsSync(paths.root) && fs8.readdirSync(paths.root).length !== 0) throw new NodeStateError("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
18029
18187
|
const manager = createNodeStateSchemaManager({ stateRoot: paths.root, targetVersion: NODE_STATE_SCHEMA_VERSION, migrations: NODE_STATE_SCHEMA_MIGRATIONS });
|
|
18030
18188
|
manager.migrate();
|
|
18189
|
+
assertNodeStateSchema(paths.root);
|
|
18031
18190
|
return paths;
|
|
18032
18191
|
} catch (error) {
|
|
18033
18192
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
@@ -18042,11 +18201,11 @@ function getNodeStateCorruptionDiagnostics(stateRoot) {
|
|
|
18042
18201
|
const directories = [paths.approvalsDir, paths.checkpointsDir, paths.inboxDir, paths.transcriptsDir, paths.questionsDir];
|
|
18043
18202
|
const diagnostics = [];
|
|
18044
18203
|
for (const directory of directories) {
|
|
18045
|
-
if (!
|
|
18046
|
-
for (const entry of
|
|
18047
|
-
const filePath =
|
|
18204
|
+
if (!fs8.existsSync(directory)) continue;
|
|
18205
|
+
for (const entry of fs8.readdirSync(directory).filter((file) => file.endsWith(".jsonl"))) {
|
|
18206
|
+
const filePath = path8.join(directory, entry);
|
|
18048
18207
|
const result = readJsonLines(filePath);
|
|
18049
|
-
for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file:
|
|
18208
|
+
for (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, file: path8.relative(paths.root, filePath) });
|
|
18050
18209
|
}
|
|
18051
18210
|
}
|
|
18052
18211
|
return diagnostics;
|
|
@@ -18099,9 +18258,9 @@ function createNodeSandboxPort(options) {
|
|
|
18099
18258
|
return result;
|
|
18100
18259
|
}
|
|
18101
18260
|
function protectAuthority(policy) {
|
|
18102
|
-
const settingsRoot =
|
|
18261
|
+
const settingsRoot = path9.join(options.workspaceRoot, ".autopilot");
|
|
18103
18262
|
const writes = [getNodeFileMutationLockRoot(), ...["settings.json", "settings.local.json", "mcp.json"].map(function settingsPath(file) {
|
|
18104
|
-
return
|
|
18263
|
+
return path9.join(settingsRoot, file);
|
|
18105
18264
|
})];
|
|
18106
18265
|
const state = options.stateRoot ? [options.stateRoot, canonicalizeNodePath(options.stateRoot)] : [];
|
|
18107
18266
|
return { ...policy, deniedRead: [.../* @__PURE__ */ new Set([...policy.deniedRead, ...state])], deniedWrite: [.../* @__PURE__ */ new Set([...policy.deniedWrite, ...state, ...writes, ...writes.map(function canonical(candidate) {
|
|
@@ -18296,20 +18455,20 @@ function describePlatform() {
|
|
|
18296
18455
|
}
|
|
18297
18456
|
|
|
18298
18457
|
// src/node/workspace-adapter.ts
|
|
18299
|
-
import
|
|
18300
|
-
import
|
|
18458
|
+
import fs9 from "node:fs";
|
|
18459
|
+
import path10 from "node:path";
|
|
18301
18460
|
function findWorkspaceRoot(startDirectory) {
|
|
18302
18461
|
let current = canonicalizeNodePath(startDirectory);
|
|
18303
18462
|
while (true) {
|
|
18304
|
-
const manifestPath =
|
|
18305
|
-
if (
|
|
18463
|
+
const manifestPath = path10.join(current, "package.json");
|
|
18464
|
+
if (fs9.existsSync(manifestPath)) {
|
|
18306
18465
|
try {
|
|
18307
|
-
const manifest = JSON.parse(
|
|
18466
|
+
const manifest = JSON.parse(fs9.readFileSync(manifestPath, "utf8"));
|
|
18308
18467
|
if (manifest.workspaces) return canonicalizeNodePath(current);
|
|
18309
18468
|
} catch {
|
|
18310
18469
|
}
|
|
18311
18470
|
}
|
|
18312
|
-
const parent =
|
|
18471
|
+
const parent = path10.dirname(current);
|
|
18313
18472
|
if (parent === current) throw new Error("\u65E0\u6CD5\u5B9A\u4F4D Agent \u5DE5\u4F5C\u533A\uFF1B\u8BF7\u8BBE\u7F6E AGENT_WORKSPACE_ROOT");
|
|
18314
18473
|
current = parent;
|
|
18315
18474
|
}
|
|
@@ -18328,20 +18487,20 @@ function createNodeWorkspaceAdapter(options = {}) {
|
|
|
18328
18487
|
const root = canonicalizeWorkspaceRoot(workspaceRoot);
|
|
18329
18488
|
const markers = [];
|
|
18330
18489
|
for (const marker of ["AGENTS.md", ".autopilot", ".claude"]) {
|
|
18331
|
-
if (
|
|
18490
|
+
if (fs9.existsSync(path10.join(root, marker))) markers.push(marker);
|
|
18332
18491
|
}
|
|
18333
18492
|
return {
|
|
18334
18493
|
root,
|
|
18335
18494
|
hasTrustMarker: markers.length > 0,
|
|
18336
18495
|
trustMarkers: markers,
|
|
18337
|
-
displayName:
|
|
18496
|
+
displayName: path10.basename(root)
|
|
18338
18497
|
};
|
|
18339
18498
|
}
|
|
18340
18499
|
return { resolveWorkspaceRoot, canonicalizeWorkspaceRoot, getWorkspaceInfo };
|
|
18341
18500
|
}
|
|
18342
18501
|
|
|
18343
18502
|
// src/node/stores/node-approval-store.ts
|
|
18344
|
-
import
|
|
18503
|
+
import fs10 from "node:fs";
|
|
18345
18504
|
import { AgentRuntimeError as AgentRuntimeError2 } from "@autopilot-agent/core";
|
|
18346
18505
|
function createNodeApprovalStore(options) {
|
|
18347
18506
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
@@ -18349,7 +18508,7 @@ function createNodeApprovalStore(options) {
|
|
|
18349
18508
|
const grantsFile = `${paths.approvalsDir}/grants.jsonl`;
|
|
18350
18509
|
function ensureDir() {
|
|
18351
18510
|
const state = ensureNodeStateRoot(paths.root);
|
|
18352
|
-
|
|
18511
|
+
fs10.mkdirSync(state.approvalsDir, { recursive: true });
|
|
18353
18512
|
}
|
|
18354
18513
|
return {
|
|
18355
18514
|
/** 待审批私有身份复用 decisions.jsonl;记录类型不与真实 decision 混淆。 */
|
|
@@ -18596,15 +18755,15 @@ function createNodeApprovalStore(options) {
|
|
|
18596
18755
|
}
|
|
18597
18756
|
|
|
18598
18757
|
// src/node/settings/node-external-permission-projector.ts
|
|
18599
|
-
import
|
|
18758
|
+
import fs13 from "node:fs";
|
|
18600
18759
|
import os6 from "node:os";
|
|
18601
18760
|
import { resolveAutopilotSettings as resolveAutopilotSettings2 } from "@autopilot-agent/core";
|
|
18602
18761
|
import { isValidExternalPermissionRule } from "@autopilot-agent/core";
|
|
18603
18762
|
|
|
18604
18763
|
// src/node/settings/user-config-directory.ts
|
|
18605
|
-
import
|
|
18764
|
+
import fs11 from "node:fs";
|
|
18606
18765
|
import os4 from "node:os";
|
|
18607
|
-
import
|
|
18766
|
+
import path11 from "node:path";
|
|
18608
18767
|
var UserConfigDirectoryError = class extends Error {
|
|
18609
18768
|
constructor(code) {
|
|
18610
18769
|
super(code);
|
|
@@ -18621,20 +18780,20 @@ function resolveUserHome(homeDirectory) {
|
|
|
18621
18780
|
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18622
18781
|
}
|
|
18623
18782
|
}
|
|
18624
|
-
if (!candidate || !
|
|
18625
|
-
return
|
|
18783
|
+
if (!candidate || !path11.isAbsolute(candidate)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18784
|
+
return path11.resolve(candidate);
|
|
18626
18785
|
}
|
|
18627
18786
|
function readEntry(entryPath) {
|
|
18628
18787
|
try {
|
|
18629
|
-
return
|
|
18788
|
+
return fs11.lstatSync(entryPath);
|
|
18630
18789
|
} catch (error) {
|
|
18631
18790
|
if (error.code === "ENOENT") return void 0;
|
|
18632
18791
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18633
18792
|
}
|
|
18634
18793
|
}
|
|
18635
18794
|
function isWithinHome(homeDirectory, configDirectory) {
|
|
18636
|
-
const relative =
|
|
18637
|
-
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${
|
|
18795
|
+
const relative = path11.relative(homeDirectory, configDirectory);
|
|
18796
|
+
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path11.sep}`) && !path11.isAbsolute(relative);
|
|
18638
18797
|
}
|
|
18639
18798
|
function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
18640
18799
|
const entry = readEntry(configDirectory);
|
|
@@ -18642,8 +18801,8 @@ function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
|
18642
18801
|
if (entry.isSymbolicLink()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
18643
18802
|
if (!entry.isDirectory()) throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_NOT_DIRECTORY");
|
|
18644
18803
|
try {
|
|
18645
|
-
const canonicalHome =
|
|
18646
|
-
const canonicalConfigDirectory =
|
|
18804
|
+
const canonicalHome = fs11.realpathSync.native(homeDirectory);
|
|
18805
|
+
const canonicalConfigDirectory = fs11.realpathSync.native(configDirectory);
|
|
18647
18806
|
if (!isWithinHome(canonicalHome, canonicalConfigDirectory)) {
|
|
18648
18807
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNSAFE_LINK");
|
|
18649
18808
|
}
|
|
@@ -18654,12 +18813,12 @@ function assertSafeConfigDirectory(homeDirectory, configDirectory) {
|
|
|
18654
18813
|
}
|
|
18655
18814
|
function ensureUserConfigDirectory(options = {}) {
|
|
18656
18815
|
const homeDirectory = resolveUserHome(options.homeDirectory);
|
|
18657
|
-
const configDirectory =
|
|
18816
|
+
const configDirectory = path11.join(homeDirectory, ".autopilot");
|
|
18658
18817
|
const existing = readEntry(configDirectory);
|
|
18659
18818
|
if (existing) assertSafeConfigDirectory(homeDirectory, configDirectory);
|
|
18660
18819
|
else {
|
|
18661
18820
|
try {
|
|
18662
|
-
|
|
18821
|
+
fs11.mkdirSync(configDirectory, { recursive: true, mode: 448 });
|
|
18663
18822
|
} catch {
|
|
18664
18823
|
throw new UserConfigDirectoryError("AUTOPILOT_CONFIG_ROOT_UNAVAILABLE");
|
|
18665
18824
|
}
|
|
@@ -18669,13 +18828,13 @@ function ensureUserConfigDirectory(options = {}) {
|
|
|
18669
18828
|
}
|
|
18670
18829
|
|
|
18671
18830
|
// src/node/settings/node-settings-loader.ts
|
|
18672
|
-
import
|
|
18831
|
+
import fs12 from "node:fs";
|
|
18673
18832
|
import os5 from "node:os";
|
|
18674
|
-
import
|
|
18833
|
+
import path12 from "node:path";
|
|
18675
18834
|
import {
|
|
18676
18835
|
resolveAutopilotSettings
|
|
18677
18836
|
} from "@autopilot-agent/core";
|
|
18678
|
-
function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi =
|
|
18837
|
+
function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = path12) {
|
|
18679
18838
|
try {
|
|
18680
18839
|
const home = homeDirectory ?? os5.homedir();
|
|
18681
18840
|
if (!pathApi.isAbsolute(home)) throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
@@ -18684,7 +18843,7 @@ function resolveNodeUserSettingsPath(homeDirectory = void 0, pathApi = path11) {
|
|
|
18684
18843
|
throw new UserConfigDirectoryError("AUTOPILOT_HOME_UNRESOLVED");
|
|
18685
18844
|
}
|
|
18686
18845
|
}
|
|
18687
|
-
function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = os5.homedir(), pathApi =
|
|
18846
|
+
function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = os5.homedir(), pathApi = path12) {
|
|
18688
18847
|
const root = pathApi.resolve(workspaceRoot);
|
|
18689
18848
|
return {
|
|
18690
18849
|
user: pathApi.join(homeDirectory, ".autopilot", "settings.json"),
|
|
@@ -18694,14 +18853,14 @@ function resolveNodeSettingsPaths(workspaceRoot, homeDirectory = os5.homedir(),
|
|
|
18694
18853
|
}
|
|
18695
18854
|
function isSafeSettingsFile(filePath) {
|
|
18696
18855
|
try {
|
|
18697
|
-
const file =
|
|
18698
|
-
const configDirectory =
|
|
18699
|
-
const directory =
|
|
18856
|
+
const file = fs12.lstatSync(filePath);
|
|
18857
|
+
const configDirectory = path12.dirname(filePath);
|
|
18858
|
+
const directory = fs12.lstatSync(configDirectory);
|
|
18700
18859
|
if (!file.isFile() || file.isSymbolicLink() || !directory.isDirectory() || directory.isSymbolicLink()) return false;
|
|
18701
|
-
const canonicalDirectory =
|
|
18702
|
-
const canonicalFile =
|
|
18703
|
-
const relative =
|
|
18704
|
-
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${
|
|
18860
|
+
const canonicalDirectory = fs12.realpathSync.native(configDirectory);
|
|
18861
|
+
const canonicalFile = fs12.realpathSync.native(filePath);
|
|
18862
|
+
const relative = path12.relative(canonicalDirectory, canonicalFile);
|
|
18863
|
+
return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path12.sep}`) && !path12.isAbsolute(relative);
|
|
18705
18864
|
} catch (error) {
|
|
18706
18865
|
return error.code === "ENOENT";
|
|
18707
18866
|
}
|
|
@@ -18709,9 +18868,9 @@ function isSafeSettingsFile(filePath) {
|
|
|
18709
18868
|
function createNodeSettingsLoader(options = {}) {
|
|
18710
18869
|
const debounceMs = options.debounceMs ?? 100;
|
|
18711
18870
|
function readSource(scope, filePath) {
|
|
18712
|
-
if (!
|
|
18871
|
+
if (!fs12.existsSync(filePath)) {
|
|
18713
18872
|
try {
|
|
18714
|
-
if (
|
|
18873
|
+
if (fs12.lstatSync(filePath).isSymbolicLink()) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
18715
18874
|
} catch {
|
|
18716
18875
|
return void 0;
|
|
18717
18876
|
}
|
|
@@ -18719,7 +18878,7 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18719
18878
|
}
|
|
18720
18879
|
if (!isSafeSettingsFile(filePath)) return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_FILE_UNSAFE_LINK" }] };
|
|
18721
18880
|
try {
|
|
18722
|
-
return { scope, value: JSON.parse(
|
|
18881
|
+
return { scope, value: JSON.parse(fs12.readFileSync(filePath, "utf8")), diagnostics: [] };
|
|
18723
18882
|
} catch {
|
|
18724
18883
|
return { scope, value: void 0, diagnostics: [{ scope, code: "SETTINGS_JSON_INVALID" }] };
|
|
18725
18884
|
}
|
|
@@ -18755,18 +18914,18 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18755
18914
|
function installWatchers() {
|
|
18756
18915
|
for (const watcher of watchers) watcher.close();
|
|
18757
18916
|
const uniqueDirectories = [...new Set(watched.flatMap(function collectWatchDirectories(filePath) {
|
|
18758
|
-
const directory =
|
|
18759
|
-
return [directory,
|
|
18917
|
+
const directory = path12.dirname(filePath);
|
|
18918
|
+
return [directory, path12.dirname(directory)];
|
|
18760
18919
|
}))].filter(
|
|
18761
18920
|
/** 不把用户配置目录的链接目标注册为监听面;父目录仍能观察链接被替换。 */
|
|
18762
18921
|
function safeWatchDirectory(directory) {
|
|
18763
|
-
return
|
|
18922
|
+
return fs12.existsSync(directory) && fs12.lstatSync(directory).isDirectory() && !fs12.lstatSync(directory).isSymbolicLink();
|
|
18764
18923
|
}
|
|
18765
18924
|
);
|
|
18766
18925
|
watchers = uniqueDirectories.flatMap(function watchParent(directory) {
|
|
18767
18926
|
try {
|
|
18768
|
-
const watcher =
|
|
18769
|
-
if (!fileName || !watched.some((target) =>
|
|
18927
|
+
const watcher = fs12.watch(directory, function reloadOnTargetFile(_eventType, fileName) {
|
|
18928
|
+
if (!fileName || !watched.some((target) => path12.basename(target) === fileName.toString() || path12.basename(path12.dirname(target)) === fileName.toString())) return;
|
|
18770
18929
|
if (timer) clearTimeout(timer);
|
|
18771
18930
|
timer = setTimeout(function reloadAfterDebounce() {
|
|
18772
18931
|
reload();
|
|
@@ -18795,16 +18954,16 @@ function createNodeSettingsLoader(options = {}) {
|
|
|
18795
18954
|
function readScopeValue(filePath, strict = false) {
|
|
18796
18955
|
if (strict) {
|
|
18797
18956
|
try {
|
|
18798
|
-
|
|
18957
|
+
fs13.lstatSync(filePath);
|
|
18799
18958
|
} catch (error) {
|
|
18800
18959
|
if (error.code === "ENOENT") return {};
|
|
18801
18960
|
throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
|
|
18802
18961
|
}
|
|
18803
18962
|
if (!isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
|
|
18804
|
-
} else if (!
|
|
18963
|
+
} else if (!fs13.existsSync(filePath) || !isSafeSettingsFile(filePath)) return {};
|
|
18805
18964
|
let content;
|
|
18806
18965
|
try {
|
|
18807
|
-
content =
|
|
18966
|
+
content = fs13.readFileSync(filePath, "utf8");
|
|
18808
18967
|
} catch {
|
|
18809
18968
|
if (strict) throw new Error("EXTERNAL_RULE_SETTINGS_UNREADABLE");
|
|
18810
18969
|
return {};
|
|
@@ -18849,8 +19008,8 @@ function createNodeExternalPermissionProjector(options = {}) {
|
|
|
18849
19008
|
const resolved = resolveAutopilotSettings2([{ scope: "local", value: updated }]);
|
|
18850
19009
|
if (resolved.permissions.restricted === true) throw new Error("EXTERNAL_RULE_PERMISSIONS_UNSAFE");
|
|
18851
19010
|
if (next.length === 0 && Object.keys(permissions).length === 1) delete updated.permissions;
|
|
18852
|
-
if (
|
|
18853
|
-
|
|
19011
|
+
if (fs13.existsSync(filePath) && !isSafeSettingsFile(filePath)) throw new Error("EXTERNAL_RULE_TARGET_UNSAFE");
|
|
19012
|
+
fs13.mkdirSync(resolveNodeSettingsPaths(workspaceRoot, options.homeDirectory ?? os6.homedir()).local.replace(/[/\\]settings\.local\.json$/u, ""), { recursive: true });
|
|
18854
19013
|
atomicReplace(filePath, `${JSON.stringify(updated, null, 2)}
|
|
18855
19014
|
`);
|
|
18856
19015
|
});
|
|
@@ -18869,16 +19028,16 @@ function createNodeExternalPermissionProjector(options = {}) {
|
|
|
18869
19028
|
}
|
|
18870
19029
|
|
|
18871
19030
|
// src/node/host-mutation-protection.ts
|
|
18872
|
-
import
|
|
19031
|
+
import path13 from "node:path";
|
|
18873
19032
|
function createNodeHostMutationProtection(options) {
|
|
18874
|
-
const stateRoot =
|
|
18875
|
-
const trustFile =
|
|
19033
|
+
const stateRoot = path13.resolve(options.stateRoot);
|
|
19034
|
+
const trustFile = path13.join(resolveNodeTrustRoot(options), "trust.json");
|
|
18876
19035
|
const fixedTargets = [
|
|
18877
19036
|
{ path: getNodeFileMutationLockRoot(), scope: "directory" },
|
|
18878
19037
|
{ path: stateRoot, scope: "directory" },
|
|
18879
19038
|
{ path: canonicalizeNodePath(stateRoot), scope: "directory" },
|
|
18880
19039
|
{ path: trustFile, scope: "file" },
|
|
18881
|
-
...options.userSettingsPath ? [{ path:
|
|
19040
|
+
...options.userSettingsPath ? [{ path: path13.resolve(options.userSettingsPath), scope: "file" }] : []
|
|
18882
19041
|
];
|
|
18883
19042
|
return {
|
|
18884
19043
|
/** 权限配置路径复用真实User/Project/Local resolver,每次保留原路径与canonical判定。 */
|
|
@@ -18894,47 +19053,120 @@ function createNodeHostMutationProtection(options) {
|
|
|
18894
19053
|
}
|
|
18895
19054
|
|
|
18896
19055
|
// src/node/stores/node-checkpoint-store.ts
|
|
18897
|
-
import
|
|
19056
|
+
import fs14 from "node:fs";
|
|
19057
|
+
import path14 from "node:path";
|
|
19058
|
+
import { createInterface } from "node:readline";
|
|
18898
19059
|
function createNodeCheckpointStore(options) {
|
|
18899
19060
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19061
|
+
const latestCache = /* @__PURE__ */ new Map();
|
|
19062
|
+
let cacheBytes = 0;
|
|
19063
|
+
function signature(target) {
|
|
19064
|
+
try {
|
|
19065
|
+
const stat = fs14.statSync(target, { bigint: true });
|
|
19066
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.birthtimeNs}`;
|
|
19067
|
+
} catch (error) {
|
|
19068
|
+
if (error.code === "ENOENT") return "missing";
|
|
19069
|
+
throw error;
|
|
19070
|
+
}
|
|
19071
|
+
}
|
|
19072
|
+
function invalidate(key2) {
|
|
19073
|
+
const previous = latestCache.get(key2);
|
|
19074
|
+
if (previous) cacheBytes -= previous.bytes;
|
|
19075
|
+
latestCache.delete(key2);
|
|
19076
|
+
}
|
|
19077
|
+
function invalidateSession(sessionId) {
|
|
19078
|
+
for (const key2 of latestCache.keys()) if (JSON.parse(key2)[0] === sessionId) invalidate(key2);
|
|
19079
|
+
}
|
|
18900
19080
|
function ensureDir() {
|
|
18901
19081
|
const state = ensureNodeStateRoot(paths.root);
|
|
18902
|
-
|
|
19082
|
+
fs14.mkdirSync(state.checkpointsDir, { recursive: true });
|
|
18903
19083
|
}
|
|
18904
19084
|
function filePath(sessionId) {
|
|
18905
19085
|
return safeFilePath(paths.checkpointsDir, sessionId, ".jsonl");
|
|
18906
19086
|
}
|
|
18907
|
-
function
|
|
18908
|
-
const
|
|
18909
|
-
|
|
18910
|
-
|
|
18911
|
-
|
|
18912
|
-
|
|
18913
|
-
|
|
18914
|
-
|
|
18915
|
-
|
|
19087
|
+
async function readCheckpoint(sessionId, turnId) {
|
|
19088
|
+
const target = filePath(sessionId);
|
|
19089
|
+
const key2 = JSON.stringify([sessionId, turnId ?? null]);
|
|
19090
|
+
try {
|
|
19091
|
+
const before2 = signature(target);
|
|
19092
|
+
const cached = latestCache.get(key2);
|
|
19093
|
+
if (cached?.signature === before2) {
|
|
19094
|
+
latestCache.delete(key2);
|
|
19095
|
+
latestCache.set(key2, cached);
|
|
19096
|
+
return structuredClone(cached.checkpoint);
|
|
19097
|
+
}
|
|
19098
|
+
invalidate(key2);
|
|
19099
|
+
let checkpoint = null;
|
|
19100
|
+
let bytes = 0;
|
|
19101
|
+
const corrupted = [];
|
|
19102
|
+
if (before2 !== "missing") {
|
|
19103
|
+
let failRead2 = function(error) {
|
|
19104
|
+
readError = error;
|
|
19105
|
+
lines.close();
|
|
19106
|
+
};
|
|
19107
|
+
var failRead = failRead2;
|
|
19108
|
+
const input = fs14.createReadStream(target, { encoding: "utf8", highWaterMark: 64 * 1024 });
|
|
19109
|
+
const lines = createInterface({ input, crlfDelay: Infinity });
|
|
19110
|
+
let readError;
|
|
19111
|
+
input.on("error", failRead2);
|
|
19112
|
+
let lineNumber = 0;
|
|
19113
|
+
try {
|
|
19114
|
+
for await (const line of lines) {
|
|
19115
|
+
lineNumber++;
|
|
19116
|
+
if (!line) continue;
|
|
19117
|
+
try {
|
|
19118
|
+
const value = JSON.parse(line);
|
|
19119
|
+
if (!turnId || value?.turnId === turnId) {
|
|
19120
|
+
checkpoint = value;
|
|
19121
|
+
bytes = Buffer.byteLength(line, "utf8");
|
|
19122
|
+
}
|
|
19123
|
+
} catch {
|
|
19124
|
+
corrupted.push(lineNumber);
|
|
19125
|
+
}
|
|
19126
|
+
await new Promise(function yieldParsing(resolve) {
|
|
19127
|
+
setImmediate(resolve);
|
|
19128
|
+
});
|
|
19129
|
+
}
|
|
19130
|
+
if (readError) throw readError;
|
|
19131
|
+
} finally {
|
|
19132
|
+
lines.close();
|
|
19133
|
+
input.destroy();
|
|
19134
|
+
input.off("error", failRead2);
|
|
19135
|
+
}
|
|
19136
|
+
}
|
|
19137
|
+
if (corrupted.length) console.warn(`[DURABLE_JSONL_CORRUPTED] file=${path14.basename(target)} records=${corrupted.length} lines=${corrupted.join(",")}`);
|
|
19138
|
+
if (!corrupted.length && before2 === signature(target) && bytes <= 8 * 1024 * 1024) {
|
|
19139
|
+
while (latestCache.size >= 8 || cacheBytes + bytes > 8 * 1024 * 1024) invalidate(latestCache.keys().next().value);
|
|
19140
|
+
latestCache.set(key2, { signature: before2, checkpoint, bytes });
|
|
19141
|
+
cacheBytes += bytes;
|
|
19142
|
+
return structuredClone(checkpoint);
|
|
19143
|
+
}
|
|
19144
|
+
return checkpoint;
|
|
19145
|
+
} catch (error) {
|
|
19146
|
+
invalidate(key2);
|
|
19147
|
+
throw error;
|
|
18916
19148
|
}
|
|
18917
|
-
return null;
|
|
18918
19149
|
}
|
|
18919
19150
|
return {
|
|
18920
19151
|
async getLatest(sessionId) {
|
|
18921
19152
|
ensureDir();
|
|
18922
|
-
return withFileLock(filePath(sessionId), () =>
|
|
19153
|
+
return withFileLock(filePath(sessionId), () => readCheckpoint(sessionId));
|
|
18923
19154
|
},
|
|
18924
19155
|
async getByTurn(sessionId, turnId) {
|
|
18925
19156
|
ensureDir();
|
|
18926
|
-
return withFileLock(filePath(sessionId), () =>
|
|
19157
|
+
return withFileLock(filePath(sessionId), () => readCheckpoint(sessionId, turnId));
|
|
18927
19158
|
},
|
|
18928
19159
|
async save(sessionId, checkpoint) {
|
|
18929
19160
|
ensureDir();
|
|
18930
19161
|
await withFileLock(filePath(sessionId), () => {
|
|
19162
|
+
invalidateSession(sessionId);
|
|
18931
19163
|
appendJsonLine(filePath(sessionId), JSON.stringify(checkpoint));
|
|
18932
19164
|
});
|
|
18933
19165
|
},
|
|
18934
19166
|
async recoverStale(sessionId, now, staleAfterMs) {
|
|
18935
19167
|
ensureDir();
|
|
18936
|
-
return withFileLock(filePath(sessionId), ()
|
|
18937
|
-
const latest =
|
|
19168
|
+
return withFileLock(filePath(sessionId), async function recover() {
|
|
19169
|
+
const latest = await readCheckpoint(sessionId);
|
|
18938
19170
|
if (!latest) return null;
|
|
18939
19171
|
if (latest.status !== "running" || !latest.lease || now - latest.lease.heartbeatAt <= staleAfterMs) return latest;
|
|
18940
19172
|
const recovered = {
|
|
@@ -18942,6 +19174,7 @@ function createNodeCheckpointStore(options) {
|
|
|
18942
19174
|
status: "interrupted_recoverable",
|
|
18943
19175
|
interruptionReason: "stale_lease"
|
|
18944
19176
|
};
|
|
19177
|
+
invalidateSession(sessionId);
|
|
18945
19178
|
appendJsonLine(filePath(sessionId), JSON.stringify(recovered));
|
|
18946
19179
|
return recovered;
|
|
18947
19180
|
});
|
|
@@ -18950,7 +19183,8 @@ function createNodeCheckpointStore(options) {
|
|
|
18950
19183
|
ensureDir();
|
|
18951
19184
|
const target = filePath(sessionId);
|
|
18952
19185
|
await withFileLock(target, () => {
|
|
18953
|
-
|
|
19186
|
+
invalidateSession(sessionId);
|
|
19187
|
+
if (fs14.existsSync(target)) fs14.unlinkSync(target);
|
|
18954
19188
|
});
|
|
18955
19189
|
}
|
|
18956
19190
|
};
|
|
@@ -18967,12 +19201,13 @@ function createNodeEventSink(_options) {
|
|
|
18967
19201
|
|
|
18968
19202
|
// src/node/stores/node-input-inbox.ts
|
|
18969
19203
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
18970
|
-
import
|
|
19204
|
+
import fs15 from "node:fs";
|
|
19205
|
+
import { inboxOriginKey } from "@autopilot-agent/core";
|
|
18971
19206
|
function createNodeInputInbox(options) {
|
|
18972
19207
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
18973
19208
|
function ensureDir() {
|
|
18974
19209
|
const state = ensureNodeStateRoot(paths.root);
|
|
18975
|
-
|
|
19210
|
+
fs15.mkdirSync(state.inboxDir, { recursive: true });
|
|
18976
19211
|
}
|
|
18977
19212
|
function filePath(sessionId) {
|
|
18978
19213
|
return safeFilePath(paths.inboxDir, sessionId, ".jsonl");
|
|
@@ -18995,7 +19230,10 @@ function createNodeInputInbox(options) {
|
|
|
18995
19230
|
const inputs = readInbox(input.sessionId);
|
|
18996
19231
|
if (input.clientMessageId) {
|
|
18997
19232
|
const existing = inputs.find((candidate) => candidate.clientMessageId === input.clientMessageId);
|
|
18998
|
-
if (existing)
|
|
19233
|
+
if (existing) {
|
|
19234
|
+
if (existing.content !== input.content || inboxOriginKey(existing.origin) !== inboxOriginKey(input.origin)) throw new Error("INBOX_INPUT_CONFLICT");
|
|
19235
|
+
return existing;
|
|
19236
|
+
}
|
|
18999
19237
|
}
|
|
19000
19238
|
const inboxInput = {
|
|
19001
19239
|
inputId: randomUUID3(),
|
|
@@ -19007,6 +19245,7 @@ function createNodeInputInbox(options) {
|
|
|
19007
19245
|
clientMessageId: input.clientMessageId,
|
|
19008
19246
|
attachments: input.attachments ?? [],
|
|
19009
19247
|
selectedSkills: input.selectedSkills ?? [],
|
|
19248
|
+
origin: input.origin,
|
|
19010
19249
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
19011
19250
|
};
|
|
19012
19251
|
inputs.push(inboxInput);
|
|
@@ -19059,7 +19298,7 @@ function createNodeInputInbox(options) {
|
|
|
19059
19298
|
},
|
|
19060
19299
|
async cancel(inputId) {
|
|
19061
19300
|
ensureDir();
|
|
19062
|
-
const files =
|
|
19301
|
+
const files = fs15.readdirSync(paths.inboxDir).filter((file) => file.endsWith(".jsonl"));
|
|
19063
19302
|
for (const file of files) {
|
|
19064
19303
|
const sessionId = file.slice(0, -6);
|
|
19065
19304
|
const cancelled = await withFileLock(filePath(sessionId), () => {
|
|
@@ -19078,7 +19317,7 @@ function createNodeInputInbox(options) {
|
|
|
19078
19317
|
ensureDir();
|
|
19079
19318
|
const target = filePath(sessionId);
|
|
19080
19319
|
await withFileLock(target, () => {
|
|
19081
|
-
if (
|
|
19320
|
+
if (fs15.existsSync(target)) fs15.unlinkSync(target);
|
|
19082
19321
|
});
|
|
19083
19322
|
},
|
|
19084
19323
|
async waitForInput(_query) {
|
|
@@ -19088,20 +19327,20 @@ function createNodeInputInbox(options) {
|
|
|
19088
19327
|
|
|
19089
19328
|
// src/node/stores/node-project-store.ts
|
|
19090
19329
|
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
19091
|
-
import
|
|
19330
|
+
import fs16 from "node:fs";
|
|
19092
19331
|
function createNodeProjectStore(options) {
|
|
19093
19332
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19094
19333
|
function ensureDir() {
|
|
19095
19334
|
const state = ensureNodeStateRoot(paths.root);
|
|
19096
|
-
|
|
19335
|
+
fs16.mkdirSync(state.projectsDir, { recursive: true });
|
|
19097
19336
|
}
|
|
19098
19337
|
function filePath(projectId) {
|
|
19099
19338
|
return safeFilePath(paths.projectsDir, projectId, ".json");
|
|
19100
19339
|
}
|
|
19101
19340
|
return {
|
|
19102
19341
|
async get(id) {
|
|
19103
|
-
|
|
19104
|
-
return
|
|
19342
|
+
assertNodeStateSchema(paths.root);
|
|
19343
|
+
return readJsonFile(filePath(id));
|
|
19105
19344
|
},
|
|
19106
19345
|
async save(project) {
|
|
19107
19346
|
ensureDir();
|
|
@@ -19110,9 +19349,10 @@ function createNodeProjectStore(options) {
|
|
|
19110
19349
|
});
|
|
19111
19350
|
},
|
|
19112
19351
|
async list() {
|
|
19113
|
-
|
|
19352
|
+
assertNodeStateSchema(paths.root);
|
|
19114
19353
|
const projects = [];
|
|
19115
|
-
|
|
19354
|
+
if (!fs16.existsSync(paths.projectsDir)) return projects;
|
|
19355
|
+
for (const file of fs16.readdirSync(paths.projectsDir).filter((entry) => entry.endsWith(".json"))) {
|
|
19116
19356
|
const project = readJsonFile(filePath(file.slice(0, -5)));
|
|
19117
19357
|
if (project) projects.push(project);
|
|
19118
19358
|
}
|
|
@@ -19137,40 +19377,42 @@ function createNodeProjectStore(options) {
|
|
|
19137
19377
|
ensureDir();
|
|
19138
19378
|
const target = filePath(id);
|
|
19139
19379
|
return withFileLock(target, () => {
|
|
19140
|
-
if (!
|
|
19141
|
-
|
|
19380
|
+
if (!fs16.existsSync(target)) return false;
|
|
19381
|
+
fs16.unlinkSync(target);
|
|
19142
19382
|
return true;
|
|
19143
19383
|
});
|
|
19144
19384
|
}
|
|
19145
19385
|
};
|
|
19146
19386
|
}
|
|
19147
19387
|
|
|
19148
|
-
// src/node/stores/node-
|
|
19149
|
-
import
|
|
19388
|
+
// src/node/stores/node-thread-store.ts
|
|
19389
|
+
import { sanitizeContinuationFailure } from "@autopilot-agent/core";
|
|
19390
|
+
import fs18 from "node:fs";
|
|
19391
|
+
import path16 from "node:path";
|
|
19150
19392
|
|
|
19151
19393
|
// src/node/chat-state.ts
|
|
19152
|
-
import
|
|
19394
|
+
import fs17 from "node:fs";
|
|
19153
19395
|
import os7 from "node:os";
|
|
19154
|
-
import
|
|
19396
|
+
import path15 from "node:path";
|
|
19155
19397
|
function resolveNodeChatStatePaths(options = {}) {
|
|
19156
19398
|
try {
|
|
19157
|
-
if (options.globalStateRoot !== void 0 && !
|
|
19399
|
+
if (options.globalStateRoot !== void 0 && !path15.isAbsolute(options.globalStateRoot)) throw new NodeChatError("CHAT_STATE_ROOT_INVALID");
|
|
19158
19400
|
const globalRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: os7.homedir() });
|
|
19159
|
-
const root =
|
|
19160
|
-
return { root, stateRoot:
|
|
19401
|
+
const root = path15.join(globalRoot, "chat");
|
|
19402
|
+
return { root, stateRoot: path15.join(root, "state"), attachmentsRoot: path15.join(root, "attachments"), knowledgeRoot: path15.join(root, "knowledge") };
|
|
19161
19403
|
} catch (error) {
|
|
19162
19404
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19163
19405
|
}
|
|
19164
19406
|
}
|
|
19165
19407
|
function assertSafeNodePath(root, target) {
|
|
19166
19408
|
try {
|
|
19167
|
-
const relative =
|
|
19168
|
-
if (relative === ".." || relative.startsWith(`..${
|
|
19409
|
+
const relative = path15.relative(root, target);
|
|
19410
|
+
if (relative === ".." || relative.startsWith(`..${path15.sep}`) || path15.isAbsolute(relative)) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19169
19411
|
let current = root;
|
|
19170
|
-
for (const segment of ["", ...relative.split(
|
|
19171
|
-
if (segment) current =
|
|
19412
|
+
for (const segment of ["", ...relative.split(path15.sep).filter(Boolean)]) {
|
|
19413
|
+
if (segment) current = path15.join(current, segment);
|
|
19172
19414
|
try {
|
|
19173
|
-
const entry =
|
|
19415
|
+
const entry = fs17.lstatSync(current);
|
|
19174
19416
|
if (entry.isSymbolicLink() || current !== target && !entry.isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19175
19417
|
} catch (error) {
|
|
19176
19418
|
if (error.code !== "ENOENT") throw error;
|
|
@@ -19184,90 +19426,528 @@ function assertSafeNodePath(root, target) {
|
|
|
19184
19426
|
function ensureChatDirectory(root, target) {
|
|
19185
19427
|
try {
|
|
19186
19428
|
assertSafeNodePath(root, target);
|
|
19187
|
-
|
|
19429
|
+
fs17.mkdirSync(target, { recursive: true, mode: 448 });
|
|
19188
19430
|
assertSafeNodePath(root, target);
|
|
19189
|
-
if (!
|
|
19431
|
+
if (!fs17.lstatSync(target).isDirectory()) throw new NodeStateError("STATE_STORAGE_UNSAFE_PATH");
|
|
19190
19432
|
} catch (error) {
|
|
19191
19433
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19192
19434
|
}
|
|
19193
19435
|
}
|
|
19194
19436
|
function initializeNodeChatDirectories(paths) {
|
|
19195
|
-
ensureChatDirectory(
|
|
19437
|
+
ensureChatDirectory(path15.dirname(paths.root), paths.root);
|
|
19196
19438
|
ensureChatDirectory(paths.root, paths.stateRoot);
|
|
19197
19439
|
ensureChatDirectory(paths.root, paths.attachmentsRoot);
|
|
19198
19440
|
}
|
|
19199
19441
|
|
|
19200
|
-
// src/node/stores/node-
|
|
19201
|
-
function
|
|
19202
|
-
const
|
|
19203
|
-
const
|
|
19204
|
-
|
|
19205
|
-
|
|
19206
|
-
|
|
19207
|
-
|
|
19442
|
+
// src/node/stores/node-thread-store.ts
|
|
19443
|
+
function createNodeThreadStore(stateRoot) {
|
|
19444
|
+
const groups = path16.join(stateRoot, "threads", "groups");
|
|
19445
|
+
const controlCache = /* @__PURE__ */ new Map();
|
|
19446
|
+
let controlCacheBytes = 0;
|
|
19447
|
+
function controlSignature(target) {
|
|
19448
|
+
const stat = fs18.statSync(target, { bigint: true });
|
|
19449
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.birthtimeNs}`;
|
|
19208
19450
|
}
|
|
19209
|
-
function
|
|
19210
|
-
|
|
19211
|
-
|
|
19212
|
-
return target;
|
|
19451
|
+
function forgetControl(target) {
|
|
19452
|
+
controlCacheBytes -= controlCache.get(target)?.bytes ?? 0;
|
|
19453
|
+
controlCache.delete(target);
|
|
19213
19454
|
}
|
|
19214
|
-
function
|
|
19215
|
-
const
|
|
19216
|
-
if (!fs17.existsSync(target)) return null;
|
|
19455
|
+
function assertTargetRoot() {
|
|
19456
|
+
const manifest = path16.join(stateRoot, "schema.json");
|
|
19217
19457
|
let value;
|
|
19218
|
-
const content = fs17.readFileSync(target, "utf8");
|
|
19219
19458
|
try {
|
|
19220
|
-
|
|
19459
|
+
if (fs18.lstatSync(stateRoot).isSymbolicLink() || fs18.lstatSync(manifest).isSymbolicLink()) throw new Error("unsafe");
|
|
19460
|
+
value = JSON.parse(fs18.readFileSync(manifest, "utf8"));
|
|
19221
19461
|
} catch {
|
|
19222
|
-
throw new
|
|
19462
|
+
throw new Error("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
19223
19463
|
}
|
|
19224
|
-
|
|
19225
|
-
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19226
|
-
if (value.productMode === void 0) atomicReplace(target, JSON.stringify(session, null, 2));
|
|
19227
|
-
return session;
|
|
19464
|
+
if (!value || typeof value !== "object" || value.schemaVersion !== 8) throw new Error("STATE_SCHEMA_VERSION_UNSUPPORTED");
|
|
19228
19465
|
}
|
|
19229
|
-
|
|
19230
|
-
|
|
19231
|
-
|
|
19466
|
+
function controlPath(groupId) {
|
|
19467
|
+
const target = path16.join(safeFilePath(groups, groupId, ""), "control.json");
|
|
19468
|
+
assertSafeNodePath(stateRoot, target);
|
|
19469
|
+
return target;
|
|
19470
|
+
}
|
|
19471
|
+
function assertInteractionControls(control) {
|
|
19472
|
+
if (control.controls !== void 0 && !Array.isArray(control.controls)) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19473
|
+
for (const intent of control.controls ?? []) {
|
|
19474
|
+
if (intent?.kind !== "continue_interaction") continue;
|
|
19475
|
+
if (intent.failureDiagnostic !== void 0 && (!sanitizeContinuationFailure(intent.failureDiagnostic) || Object.keys(intent.failureDiagnostic).some(function invalid(key2) {
|
|
19476
|
+
return !Object.prototype.hasOwnProperty.call(sanitizeContinuationFailure(intent.failureDiagnostic), key2) || intent.failureDiagnostic[key2] !== sanitizeContinuationFailure(intent.failureDiagnostic)[key2];
|
|
19477
|
+
}))) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19478
|
+
const ids = [intent.controlId, intent.threadId, intent.expectedTurnId, intent.approvalId ?? intent.requestId];
|
|
19479
|
+
if (ids.some(function invalid(id) {
|
|
19480
|
+
return typeof id !== "string" || !id || id.length > 200 || /[\\/\x00-\x1f]/u.test(id);
|
|
19481
|
+
}) || 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");
|
|
19482
|
+
}
|
|
19483
|
+
}
|
|
19484
|
+
function read(groupId) {
|
|
19485
|
+
const target = controlPath(groupId);
|
|
19486
|
+
try {
|
|
19487
|
+
const before2 = controlSignature(target);
|
|
19488
|
+
const cached = controlCache.get(target);
|
|
19489
|
+
if (cached?.signature === before2) {
|
|
19490
|
+
controlCache.delete(target);
|
|
19491
|
+
controlCache.set(target, cached);
|
|
19492
|
+
return structuredClone(cached.value);
|
|
19493
|
+
}
|
|
19494
|
+
forgetControl(target);
|
|
19495
|
+
const text = fs18.readFileSync(target, "utf8");
|
|
19496
|
+
let value;
|
|
19232
19497
|
try {
|
|
19233
|
-
|
|
19234
|
-
|
|
19235
|
-
|
|
19236
|
-
|
|
19237
|
-
|
|
19238
|
-
|
|
19239
|
-
|
|
19498
|
+
value = JSON.parse(text);
|
|
19499
|
+
} catch {
|
|
19500
|
+
throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19501
|
+
}
|
|
19502
|
+
if (!value || value.group?.groupId !== groupId || !Number.isSafeInteger(value.revision) || value.revision < 0) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19503
|
+
assertInteractionControls(value);
|
|
19504
|
+
const bytes = Buffer.byteLength(text, "utf8");
|
|
19505
|
+
if (bytes <= 8 * 1024 * 1024 && before2 === controlSignature(target)) {
|
|
19506
|
+
while (controlCache.size >= 128 || controlCacheBytes + bytes > 8 * 1024 * 1024) forgetControl(controlCache.keys().next().value);
|
|
19507
|
+
controlCache.set(target, { signature: before2, value, bytes });
|
|
19508
|
+
controlCacheBytes += bytes;
|
|
19509
|
+
return structuredClone(value);
|
|
19510
|
+
}
|
|
19511
|
+
return value;
|
|
19512
|
+
} catch (error) {
|
|
19513
|
+
forgetControl(target);
|
|
19514
|
+
if (error.code === "ENOENT") return null;
|
|
19515
|
+
throw error;
|
|
19516
|
+
}
|
|
19517
|
+
}
|
|
19518
|
+
function messagePath(groupId, threadId, seq2) {
|
|
19519
|
+
if (!Number.isSafeInteger(seq2) || seq2 < 1) throw new Error("THREAD_CURSOR_INVALID");
|
|
19520
|
+
const dir = path16.join(safeFilePath(groups, groupId, ""), "messages");
|
|
19521
|
+
const threadDir = safeFilePath(dir, threadId, "");
|
|
19522
|
+
const target = safeFilePath(threadDir, String(seq2), ".json");
|
|
19523
|
+
assertSafeNodePath(stateRoot, target);
|
|
19524
|
+
return target;
|
|
19525
|
+
}
|
|
19526
|
+
function readMessage(groupId, threadId, seq2) {
|
|
19527
|
+
let value;
|
|
19528
|
+
try {
|
|
19529
|
+
value = JSON.parse(fs18.readFileSync(messagePath(groupId, threadId, seq2), "utf8"));
|
|
19530
|
+
} catch (error) {
|
|
19531
|
+
if (error.code === "ENOENT") return null;
|
|
19532
|
+
throw new Error("THREAD_MESSAGE_CORRUPTED");
|
|
19533
|
+
}
|
|
19534
|
+
if (!value || value.groupId !== groupId || value.toThreadId !== threadId || value.deliverySeq !== seq2) throw new Error("THREAD_MESSAGE_CORRUPTED");
|
|
19535
|
+
return value;
|
|
19536
|
+
}
|
|
19537
|
+
function eventPath(groupId, seq2) {
|
|
19538
|
+
if (!Number.isSafeInteger(seq2) || seq2 < 1) throw new Error("THREAD_CURSOR_INVALID");
|
|
19539
|
+
const dir = path16.join(safeFilePath(groups, groupId, ""), "events");
|
|
19540
|
+
const target = safeFilePath(dir, String(seq2), ".json");
|
|
19541
|
+
assertSafeNodePath(stateRoot, target);
|
|
19542
|
+
return target;
|
|
19543
|
+
}
|
|
19544
|
+
function readEvent(groupId, seq2) {
|
|
19545
|
+
let value;
|
|
19546
|
+
try {
|
|
19547
|
+
value = JSON.parse(fs18.readFileSync(eventPath(groupId, seq2), "utf8"));
|
|
19548
|
+
} catch (error) {
|
|
19549
|
+
if (error.code === "ENOENT") return null;
|
|
19550
|
+
throw new Error("THREAD_EVENT_CORRUPTED");
|
|
19551
|
+
}
|
|
19552
|
+
if (!value || value.groupId !== groupId || value.groupSeq !== seq2) throw new Error("THREAD_EVENT_CORRUPTED");
|
|
19553
|
+
return value;
|
|
19554
|
+
}
|
|
19555
|
+
function readRequest(id) {
|
|
19556
|
+
const target = safeFilePath(path16.join(stateRoot, "threads", "requests"), id, ".json");
|
|
19557
|
+
assertSafeNodePath(stateRoot, target);
|
|
19558
|
+
try {
|
|
19559
|
+
return JSON.parse(fs18.readFileSync(target, "utf8"));
|
|
19560
|
+
} catch (error) {
|
|
19561
|
+
if (error.code === "ENOENT") return null;
|
|
19562
|
+
throw new Error("THREAD_REQUEST_CORRUPTED");
|
|
19563
|
+
}
|
|
19564
|
+
}
|
|
19565
|
+
return {
|
|
19566
|
+
/** 只读检查,和预留中的最终检查共同处理并发。 */
|
|
19567
|
+
async verifyRequest(id, groupId, payloadDigest) {
|
|
19568
|
+
assertTargetRoot();
|
|
19569
|
+
const prior = readRequest(id);
|
|
19570
|
+
if (prior && (prior.groupId !== groupId || prior.payloadDigest !== payloadDigest)) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19240
19571
|
},
|
|
19241
|
-
/**
|
|
19242
|
-
async
|
|
19243
|
-
|
|
19244
|
-
|
|
19245
|
-
|
|
19246
|
-
|
|
19247
|
-
|
|
19248
|
-
|
|
19249
|
-
|
|
19572
|
+
/** 请求身份独立于组,跨进程锁内持久预留,冲突不得重绑。 */
|
|
19573
|
+
async reserveRequest(id, groupId, payloadDigest) {
|
|
19574
|
+
assertTargetRoot();
|
|
19575
|
+
const target = safeFilePath(path16.join(stateRoot, "threads", "requests"), id, ".json");
|
|
19576
|
+
assertSafeNodePath(stateRoot, target);
|
|
19577
|
+
await withFileLock(target, function reserveLocked() {
|
|
19578
|
+
if (fs18.existsSync(target)) {
|
|
19579
|
+
let prior;
|
|
19580
|
+
try {
|
|
19581
|
+
prior = JSON.parse(fs18.readFileSync(target, "utf8"));
|
|
19582
|
+
} catch {
|
|
19583
|
+
throw new Error("THREAD_REQUEST_CORRUPTED");
|
|
19584
|
+
}
|
|
19585
|
+
if (prior.groupId !== groupId || prior.payloadDigest !== payloadDigest) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19586
|
+
return;
|
|
19250
19587
|
}
|
|
19251
|
-
|
|
19252
|
-
}
|
|
19253
|
-
|
|
19588
|
+
atomicReplace(target, JSON.stringify({ groupId, payloadDigest }));
|
|
19589
|
+
}, { requireExitedOwner: true });
|
|
19590
|
+
},
|
|
19591
|
+
/** 同序号重放幂等,不同事件冲突。 */
|
|
19592
|
+
async writeEvent(event) {
|
|
19593
|
+
assertTargetRoot();
|
|
19594
|
+
const target = eventPath(event.groupId, event.groupSeq);
|
|
19595
|
+
const serialized = JSON.stringify(event);
|
|
19596
|
+
if (Buffer.byteLength(serialized, "utf8") > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
19597
|
+
await withFileLock(target, function writeEventLocked() {
|
|
19598
|
+
const previous = readEvent(event.groupId, event.groupSeq);
|
|
19599
|
+
if (previous && JSON.stringify(previous) !== serialized) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19600
|
+
if (!previous) atomicReplace(target, serialized);
|
|
19601
|
+
}, { requireExitedOwner: true });
|
|
19602
|
+
},
|
|
19603
|
+
/** 查询不创建锁或目录。 */
|
|
19604
|
+
async readEvent(groupId, seq2) {
|
|
19605
|
+
assertTargetRoot();
|
|
19606
|
+
return readEvent(groupId, seq2);
|
|
19607
|
+
},
|
|
19608
|
+
/** 短期 Session 锁只覆盖元数据变更与删除,不覆盖 Turn 执行。 */
|
|
19609
|
+
async withSessionLock(threadId, operation) {
|
|
19610
|
+
assertTargetRoot();
|
|
19611
|
+
const target = safeFilePath(path16.join(stateRoot, "threads", "session-locks"), threadId, "");
|
|
19612
|
+
assertSafeNodePath(stateRoot, target);
|
|
19613
|
+
return withFileLock(target, operation, { requireExitedOwner: true });
|
|
19614
|
+
},
|
|
19615
|
+
/** 检查全部组控制记录;损坏记录明确报错,不遗漏受管引用。 */
|
|
19616
|
+
async hasMembership(threadId) {
|
|
19617
|
+
assertTargetRoot();
|
|
19618
|
+
if (!fs18.existsSync(groups)) return false;
|
|
19619
|
+
for (const groupId of fs18.readdirSync(groups)) {
|
|
19620
|
+
const control = read(groupId);
|
|
19621
|
+
if (!control) throw new Error("THREAD_CONTROL_CORRUPTED");
|
|
19622
|
+
if (control.members.some(function member(item) {
|
|
19623
|
+
return item.threadId === threadId;
|
|
19624
|
+
}) || control.creates.some(function intent(item) {
|
|
19625
|
+
return item.threadId === threadId || item.parentThreadId === threadId;
|
|
19626
|
+
})) return true;
|
|
19254
19627
|
}
|
|
19628
|
+
return false;
|
|
19255
19629
|
},
|
|
19256
|
-
/**
|
|
19257
|
-
async
|
|
19258
|
-
|
|
19259
|
-
|
|
19260
|
-
|
|
19261
|
-
|
|
19262
|
-
|
|
19263
|
-
|
|
19264
|
-
|
|
19630
|
+
/** 目标格式与稳定身份校验后按消息锁幂等写入。 */
|
|
19631
|
+
async writeMessage(message) {
|
|
19632
|
+
assertTargetRoot();
|
|
19633
|
+
const target = messagePath(message.groupId, message.toThreadId, message.deliverySeq);
|
|
19634
|
+
const serialized = JSON.stringify(message);
|
|
19635
|
+
if (Buffer.byteLength(serialized, "utf8") > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
19636
|
+
await withFileLock(target, function writeLocked() {
|
|
19637
|
+
const prior = readMessage(message.groupId, message.toThreadId, message.deliverySeq);
|
|
19638
|
+
if (prior && JSON.stringify(prior) !== serialized) throw new Error("THREAD_REQUEST_CONFLICT");
|
|
19639
|
+
if (!prior) atomicReplace(target, serialized);
|
|
19640
|
+
}, { requireExitedOwner: true });
|
|
19641
|
+
},
|
|
19642
|
+
/** 按序号读取,不创建目录或锁文件。 */
|
|
19643
|
+
async readMessage(groupId, threadId, seq2) {
|
|
19644
|
+
assertTargetRoot();
|
|
19645
|
+
return readMessage(groupId, threadId, seq2);
|
|
19646
|
+
},
|
|
19647
|
+
/** 查询不触发状态根初始化或执行恢复。 */
|
|
19648
|
+
async readControl(groupId) {
|
|
19649
|
+
assertTargetRoot();
|
|
19650
|
+
return read(groupId);
|
|
19651
|
+
},
|
|
19652
|
+
/** 只列出已有 control.json 的组,半初始化目录不冒充可执行目标。 */
|
|
19653
|
+
async listGroups() {
|
|
19654
|
+
assertTargetRoot();
|
|
19655
|
+
if (!fs18.existsSync(groups)) return [];
|
|
19656
|
+
return fs18.readdirSync(groups).filter(function hasControl(name) {
|
|
19657
|
+
return fs18.existsSync(controlPath(name));
|
|
19658
|
+
}).sort();
|
|
19659
|
+
},
|
|
19660
|
+
/**
|
|
19661
|
+
* 本进程内的文件变化唤醒;watchFile 只做 stat 轮询,不创建锁或文件。
|
|
19662
|
+
* 跨进程写入同样会改变 mtime,因此订阅不依赖同一进程的 CAS 回调。
|
|
19663
|
+
*/
|
|
19664
|
+
subscribe(groupId, listener) {
|
|
19665
|
+
const target = controlPath(groupId);
|
|
19666
|
+
const onChange = function changed() {
|
|
19667
|
+
try {
|
|
19668
|
+
listener();
|
|
19669
|
+
} catch {
|
|
19670
|
+
}
|
|
19671
|
+
};
|
|
19672
|
+
fs18.watchFile(target, { interval: 200, persistent: false }, onChange);
|
|
19673
|
+
return () => {
|
|
19674
|
+
fs18.unwatchFile(target, onChange);
|
|
19675
|
+
};
|
|
19676
|
+
},
|
|
19677
|
+
/** 加锁后重新读取和校验版本,原子替换而不跨 Session 持锁执行。 */
|
|
19678
|
+
async compareAndSetControl(groupId, expectedRevision, value) {
|
|
19679
|
+
assertTargetRoot();
|
|
19680
|
+
if (value.group.groupId !== groupId || value.revision !== (expectedRevision === null ? 0 : expectedRevision + 1)) throw new Error("THREAD_CONTROL_INVALID");
|
|
19681
|
+
assertInteractionControls(value);
|
|
19682
|
+
const serialized = JSON.stringify(value);
|
|
19683
|
+
if (Buffer.byteLength(serialized, "utf8") > 4 * 1024 * 1024) throw new Error("THREAD_STORAGE_FULL");
|
|
19684
|
+
return withFileLock(controlPath(groupId), function updateUnderLock() {
|
|
19685
|
+
const current = read(groupId);
|
|
19686
|
+
if (expectedRevision === null ? current !== null : current?.revision !== expectedRevision) return false;
|
|
19687
|
+
atomicReplace(controlPath(groupId), serialized);
|
|
19688
|
+
return true;
|
|
19689
|
+
}, { requireExitedOwner: true });
|
|
19690
|
+
}
|
|
19691
|
+
};
|
|
19692
|
+
}
|
|
19693
|
+
|
|
19694
|
+
// src/node/stores/node-session-store.ts
|
|
19695
|
+
import fs20 from "node:fs";
|
|
19696
|
+
|
|
19697
|
+
// src/node/stores/session-directory.ts
|
|
19698
|
+
import fs19 from "node:fs";
|
|
19699
|
+
var DIRECTORY_FIELDS = /* @__PURE__ */ new Set(["id", "title", "productMode", "projectId", "chatRetrievalMode", "createdAt", "updatedAt", "status", "activeTurnId"]);
|
|
19700
|
+
async function readSessionDirectoryRecord(filePath, id) {
|
|
19701
|
+
const fields2 = {};
|
|
19702
|
+
const stack = [];
|
|
19703
|
+
let root = false;
|
|
19704
|
+
let finished = false;
|
|
19705
|
+
let token;
|
|
19706
|
+
let text = "";
|
|
19707
|
+
let capture = false;
|
|
19708
|
+
let keyToken = false;
|
|
19709
|
+
let target;
|
|
19710
|
+
let escaped = false;
|
|
19711
|
+
let unicode = 0;
|
|
19712
|
+
function invalid() {
|
|
19713
|
+
throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
19714
|
+
}
|
|
19715
|
+
function beginValue() {
|
|
19716
|
+
if (!stack.length) {
|
|
19717
|
+
if (root) invalid();
|
|
19718
|
+
root = true;
|
|
19719
|
+
return void 0;
|
|
19720
|
+
}
|
|
19721
|
+
const frame = stack[stack.length - 1];
|
|
19722
|
+
if (frame.expect !== "value" && frame.expect !== "valueOrEnd") invalid();
|
|
19723
|
+
frame.expect = "commaOrEnd";
|
|
19724
|
+
return stack.length === 1 && frame.kind === "object" && frame.key && DIRECTORY_FIELDS.has(frame.key) ? frame.key : void 0;
|
|
19725
|
+
}
|
|
19726
|
+
function finishToken() {
|
|
19727
|
+
if (keyToken) {
|
|
19728
|
+
const frame = stack[stack.length - 1];
|
|
19729
|
+
frame.key = stack.length === 1 ? JSON.parse(text) : void 0;
|
|
19730
|
+
frame.expect = "colon";
|
|
19731
|
+
} else if (target) fields2[target] = JSON.parse(text);
|
|
19732
|
+
token = void 0;
|
|
19733
|
+
text = "";
|
|
19734
|
+
target = void 0;
|
|
19735
|
+
}
|
|
19736
|
+
const stream = fs19.createReadStream(filePath, { encoding: "utf8", highWaterMark: 16 * 1024 });
|
|
19737
|
+
for await (const chunk of stream) {
|
|
19738
|
+
for (const character of chunk) {
|
|
19739
|
+
if (token === "string") {
|
|
19740
|
+
if (capture) text += character;
|
|
19741
|
+
if (unicode) {
|
|
19742
|
+
if (!/[0-9a-f]/iu.test(character)) invalid();
|
|
19743
|
+
unicode--;
|
|
19744
|
+
continue;
|
|
19745
|
+
}
|
|
19746
|
+
if (escaped) {
|
|
19747
|
+
if (character === "u") unicode = 4;
|
|
19748
|
+
else if (!/["\\/bfnrt]/u.test(character)) invalid();
|
|
19749
|
+
escaped = false;
|
|
19750
|
+
continue;
|
|
19751
|
+
}
|
|
19752
|
+
if (character === "\\") {
|
|
19753
|
+
escaped = true;
|
|
19754
|
+
continue;
|
|
19755
|
+
}
|
|
19756
|
+
if (character === '"') {
|
|
19757
|
+
finishToken();
|
|
19758
|
+
continue;
|
|
19759
|
+
}
|
|
19760
|
+
if (character.charCodeAt(0) < 32) invalid();
|
|
19761
|
+
continue;
|
|
19762
|
+
}
|
|
19763
|
+
if (token === "primitive") {
|
|
19764
|
+
if (!/[ \t\r\n,}\]]/u.test(character)) {
|
|
19765
|
+
text += character;
|
|
19766
|
+
if (text.length > 128) invalid();
|
|
19767
|
+
continue;
|
|
19768
|
+
}
|
|
19769
|
+
if (!/^(?:null|true|false|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)$/u.test(text)) invalid();
|
|
19770
|
+
finishToken();
|
|
19771
|
+
}
|
|
19772
|
+
if (/[ \t\r\n]/u.test(character)) continue;
|
|
19773
|
+
if (finished) invalid();
|
|
19774
|
+
const frame = stack[stack.length - 1];
|
|
19775
|
+
if (character === '"') {
|
|
19776
|
+
keyToken = frame?.kind === "object" && (frame.expect === "key" || frame.expect === "keyOrEnd");
|
|
19777
|
+
target = keyToken ? void 0 : beginValue();
|
|
19778
|
+
capture = keyToken ? stack.length === 1 : target !== void 0;
|
|
19779
|
+
text = capture ? '"' : "";
|
|
19780
|
+
token = "string";
|
|
19781
|
+
continue;
|
|
19782
|
+
}
|
|
19783
|
+
if (character === "{" || character === "[") {
|
|
19784
|
+
const topLevel = !root;
|
|
19785
|
+
if (topLevel && character !== "{") invalid();
|
|
19786
|
+
beginValue();
|
|
19787
|
+
if (stack.length >= 128) invalid();
|
|
19788
|
+
stack.push({ kind: character === "{" ? "object" : "array", expect: character === "{" ? "keyOrEnd" : "valueOrEnd" });
|
|
19789
|
+
continue;
|
|
19790
|
+
}
|
|
19791
|
+
if (character === "}" || character === "]") {
|
|
19792
|
+
if (!frame || frame.kind !== (character === "}" ? "object" : "array") || !["commaOrEnd", character === "}" ? "keyOrEnd" : "valueOrEnd"].includes(frame.expect)) invalid();
|
|
19793
|
+
stack.pop();
|
|
19794
|
+
if (!stack.length) finished = true;
|
|
19795
|
+
continue;
|
|
19796
|
+
}
|
|
19797
|
+
if (character === ":") {
|
|
19798
|
+
if (frame?.expect !== "colon") invalid();
|
|
19799
|
+
frame.expect = "value";
|
|
19800
|
+
continue;
|
|
19801
|
+
}
|
|
19802
|
+
if (character === ",") {
|
|
19803
|
+
if (frame?.expect !== "commaOrEnd") invalid();
|
|
19804
|
+
frame.expect = frame.kind === "object" ? "key" : "value";
|
|
19805
|
+
continue;
|
|
19806
|
+
}
|
|
19807
|
+
target = beginValue();
|
|
19808
|
+
keyToken = false;
|
|
19809
|
+
capture = true;
|
|
19810
|
+
text = character;
|
|
19811
|
+
token = "primitive";
|
|
19812
|
+
}
|
|
19813
|
+
}
|
|
19814
|
+
if (!finished || token || stack.length) invalid();
|
|
19815
|
+
if (fields2.title !== void 0 && typeof fields2.title !== "string") invalid();
|
|
19816
|
+
return normalizeNodeSession(fields2, id);
|
|
19817
|
+
}
|
|
19818
|
+
|
|
19819
|
+
// src/node/stores/node-session-store.ts
|
|
19820
|
+
function createNodeSessionStore(options) {
|
|
19821
|
+
const paths = getNodeStatePaths(options.stateRoot);
|
|
19822
|
+
const productMode = options.productMode ?? "work";
|
|
19823
|
+
function ensureDir() {
|
|
19824
|
+
const state = ensureNodeStateRoot(options.stateRoot);
|
|
19825
|
+
assertSafeNodePath(state.root, state.sessionsDir);
|
|
19826
|
+
fs20.mkdirSync(state.sessionsDir, { recursive: true });
|
|
19827
|
+
}
|
|
19828
|
+
function filePath(sessionId) {
|
|
19829
|
+
const target = safeFilePath(paths.sessionsDir, sessionId, ".json");
|
|
19830
|
+
assertSafeNodePath(paths.root, target);
|
|
19831
|
+
return target;
|
|
19832
|
+
}
|
|
19833
|
+
function read(id) {
|
|
19834
|
+
const target = filePath(id);
|
|
19835
|
+
if (!fs20.existsSync(target)) return null;
|
|
19836
|
+
let value;
|
|
19837
|
+
const content = fs20.readFileSync(target, "utf8");
|
|
19838
|
+
try {
|
|
19839
|
+
value = JSON.parse(content);
|
|
19840
|
+
} catch {
|
|
19841
|
+
throw new NodeStateError("STATE_SESSION_CORRUPTED");
|
|
19842
|
+
}
|
|
19843
|
+
const session = normalizeNodeSession(value, id);
|
|
19844
|
+
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19845
|
+
return session;
|
|
19846
|
+
}
|
|
19847
|
+
return {
|
|
19848
|
+
/** 在文件锁内校验并读取当前产品域的 Session。 */
|
|
19849
|
+
async get(id) {
|
|
19850
|
+
try {
|
|
19851
|
+
assertNodeStateSchema(paths.root);
|
|
19852
|
+
return read(id);
|
|
19853
|
+
} catch (error) {
|
|
19854
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19855
|
+
}
|
|
19856
|
+
},
|
|
19857
|
+
/** 单个关联目标也复用流式元数据边界,不读取完整Session正文。 */
|
|
19858
|
+
async getDirectoryEntry(id) {
|
|
19859
|
+
try {
|
|
19860
|
+
assertNodeStateSchema(paths.root);
|
|
19861
|
+
const target = filePath(id);
|
|
19862
|
+
if (!fs20.existsSync(target)) return null;
|
|
19863
|
+
const session = await readSessionDirectoryRecord(target, id);
|
|
19864
|
+
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19865
|
+
return session;
|
|
19866
|
+
} catch (error) {
|
|
19867
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19868
|
+
}
|
|
19869
|
+
},
|
|
19870
|
+
/** 逐项加锁读取,损坏记录不能从列表中无声消失。 */
|
|
19871
|
+
async list() {
|
|
19872
|
+
try {
|
|
19873
|
+
assertNodeStateSchema(paths.root);
|
|
19874
|
+
const sessions = [];
|
|
19875
|
+
if (!fs20.existsSync(paths.sessionsDir)) return sessions;
|
|
19876
|
+
for (const file of fs20.readdirSync(paths.sessionsDir)) {
|
|
19877
|
+
if (!file.endsWith(".json")) continue;
|
|
19878
|
+
const session = await this.get(file.slice(0, -5));
|
|
19879
|
+
if (session) sessions.push(session);
|
|
19880
|
+
}
|
|
19881
|
+
return sessions.sort((left, right) => right.updatedAt - left.updatedAt);
|
|
19882
|
+
} catch (error) {
|
|
19883
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19884
|
+
}
|
|
19885
|
+
},
|
|
19886
|
+
/** 每页只扫描limit个稳定UUID记录;流式跳过正文,不回退完整get/list。 */
|
|
19887
|
+
async listDirectoryPage(query2) {
|
|
19888
|
+
try {
|
|
19889
|
+
assertNodeStateSchema(paths.root);
|
|
19890
|
+
if (!Number.isInteger(query2.limit) || query2.limit < 1 || query2.limit > 100 || !query2.projectId.trim()) throw new Error("SESSION_CURSOR_INVALID");
|
|
19891
|
+
let after2 = "";
|
|
19892
|
+
if (query2.cursor) {
|
|
19893
|
+
try {
|
|
19894
|
+
const value = JSON.parse(Buffer.from(query2.cursor, "base64url").toString("utf8"));
|
|
19895
|
+
if (value.view !== "session-directory" || value.root !== paths.root || value.mode !== productMode || value.projectId !== query2.projectId || typeof value.after !== "string") throw new Error();
|
|
19896
|
+
after2 = value.after;
|
|
19897
|
+
} catch {
|
|
19898
|
+
throw new Error("SESSION_CURSOR_INVALID");
|
|
19899
|
+
}
|
|
19900
|
+
}
|
|
19901
|
+
const names = fs20.existsSync(paths.sessionsDir) ? fs20.readdirSync(paths.sessionsDir).filter(function session(file) {
|
|
19902
|
+
return file.endsWith(".json") && file.slice(0, -5) > after2;
|
|
19903
|
+
}).sort() : [];
|
|
19904
|
+
const items = [];
|
|
19905
|
+
for (const name of names.slice(0, query2.limit)) {
|
|
19906
|
+
after2 = name.slice(0, -5);
|
|
19907
|
+
const session = await readSessionDirectoryRecord(filePath(after2), after2);
|
|
19908
|
+
if (session.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19909
|
+
if (session.projectId === query2.projectId) items.push({ id: session.id, ...session.title !== void 0 ? { title: session.title } : {} });
|
|
19910
|
+
}
|
|
19911
|
+
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;
|
|
19912
|
+
return { items, ...nextCursor ? { nextCursor } : {} };
|
|
19913
|
+
} catch (error) {
|
|
19914
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19915
|
+
}
|
|
19916
|
+
},
|
|
19917
|
+
/** 跨进程锁内确认不存在再创建,防止并发覆盖已有 Session。 */
|
|
19918
|
+
async createIfAbsent(session) {
|
|
19919
|
+
try {
|
|
19920
|
+
ensureDir();
|
|
19921
|
+
const next = normalizeNodeSession(session, session.id);
|
|
19922
|
+
if (next.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19923
|
+
return await withFileLock(filePath(session.id), function createLocked() {
|
|
19924
|
+
if (read(session.id)) return false;
|
|
19265
19925
|
atomicReplace(filePath(session.id), JSON.stringify(next, null, 2));
|
|
19266
|
-
|
|
19926
|
+
return true;
|
|
19927
|
+
}, { requireExitedOwner: true });
|
|
19267
19928
|
} catch (error) {
|
|
19268
19929
|
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE");
|
|
19269
19930
|
}
|
|
19270
19931
|
},
|
|
19932
|
+
/** 在同一临界区比较持久化身份并原子替换,拒绝底层直接越权写入。 */
|
|
19933
|
+
async save(session) {
|
|
19934
|
+
let phase = "prepare";
|
|
19935
|
+
try {
|
|
19936
|
+
ensureDir();
|
|
19937
|
+
phase = "identity";
|
|
19938
|
+
const next = normalizeNodeSession(session, session.id);
|
|
19939
|
+
if (next.productMode !== productMode) throw createNodeIdentityError("SESSION_MODE_MISMATCH");
|
|
19940
|
+
phase = "lock";
|
|
19941
|
+
await withFileLock(filePath(session.id), function saveLocked() {
|
|
19942
|
+
phase = "identity";
|
|
19943
|
+
const previous = read(session.id);
|
|
19944
|
+
if (previous) assertNodeSessionIdentity(previous, next);
|
|
19945
|
+
return replaceSessionFile(filePath(session.id), JSON.stringify(next, null, 2));
|
|
19946
|
+
});
|
|
19947
|
+
} catch (error) {
|
|
19948
|
+
throw toNodeBoundaryError(error, "STATE_STORAGE_UNAVAILABLE", { operation: "session_save", target: "session", phase, ...getFileOperationDiagnostic(error) });
|
|
19949
|
+
}
|
|
19950
|
+
},
|
|
19271
19951
|
/** 只删除当前产品域记录;外围资源仍由 SessionResourceStore 先行清理。 */
|
|
19272
19952
|
async delete(id) {
|
|
19273
19953
|
try {
|
|
@@ -19275,7 +19955,7 @@ function createNodeSessionStore(options) {
|
|
|
19275
19955
|
const target = filePath(id);
|
|
19276
19956
|
return await withFileLock(target, function deleteLocked() {
|
|
19277
19957
|
if (!read(id)) return false;
|
|
19278
|
-
|
|
19958
|
+
fs20.unlinkSync(target);
|
|
19279
19959
|
return true;
|
|
19280
19960
|
});
|
|
19281
19961
|
} catch (error) {
|
|
@@ -19287,11 +19967,16 @@ function createNodeSessionStore(options) {
|
|
|
19287
19967
|
|
|
19288
19968
|
// src/node/stores/node-transcript-store.ts
|
|
19289
19969
|
import fsp2 from "node:fs/promises";
|
|
19290
|
-
import
|
|
19970
|
+
import path17 from "node:path";
|
|
19291
19971
|
var transcriptIndexes = /* @__PURE__ */ new Map();
|
|
19292
19972
|
var transcriptRootInitializations = /* @__PURE__ */ new Map();
|
|
19973
|
+
function parseTranscriptFileIdentity(value) {
|
|
19974
|
+
if (typeof value === "string" && /^\d{1,20}$/.test(value)) return BigInt(value).toString();
|
|
19975
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return String(value);
|
|
19976
|
+
throw new Error("THREAD_CURSOR_INVALID");
|
|
19977
|
+
}
|
|
19293
19978
|
function getTranscriptIndex(filePath) {
|
|
19294
|
-
const key2 =
|
|
19979
|
+
const key2 = path17.resolve(filePath);
|
|
19295
19980
|
const existing = transcriptIndexes.get(key2);
|
|
19296
19981
|
if (existing) return existing;
|
|
19297
19982
|
const created = { initialized: false, offset: 0, pendingBytes: Buffer.alloc(0), endsWithNewline: true, keys: /* @__PURE__ */ new Set() };
|
|
@@ -19302,7 +19987,7 @@ function getEnvelopeKey(envelope) {
|
|
|
19302
19987
|
return `${envelope.sessionId}\0${envelope.turnId}\0${envelope.seq}`;
|
|
19303
19988
|
}
|
|
19304
19989
|
function ensureTranscriptDirectory(stateRoot) {
|
|
19305
|
-
const key2 =
|
|
19990
|
+
const key2 = path17.resolve(stateRoot);
|
|
19306
19991
|
const existing = transcriptRootInitializations.get(key2);
|
|
19307
19992
|
if (existing) return existing;
|
|
19308
19993
|
const initialization = Promise.resolve().then(async function initializeTranscriptDirectory() {
|
|
@@ -19324,7 +20009,7 @@ async function readTranscriptBuffer(filePath) {
|
|
|
19324
20009
|
}
|
|
19325
20010
|
}
|
|
19326
20011
|
function reportCorruptedLine(filePath) {
|
|
19327
|
-
console.warn(`[DURABLE_JSONL_CORRUPTED] file=${
|
|
20012
|
+
console.warn(`[DURABLE_JSONL_CORRUPTED] file=${path17.basename(filePath)} records=1 lines=unknown`);
|
|
19328
20013
|
}
|
|
19329
20014
|
function parseTranscriptLine(filePath, line, index, parsed) {
|
|
19330
20015
|
if (line.length === 0) return;
|
|
@@ -19388,26 +20073,28 @@ async function readTranscriptTail(filePath, offset) {
|
|
|
19388
20073
|
}
|
|
19389
20074
|
}
|
|
19390
20075
|
async function refreshTranscriptIndex(filePath, index) {
|
|
19391
|
-
if (!index.initialized) {
|
|
19392
|
-
rebuildTranscriptIndex(filePath, await readTranscriptBuffer(filePath), index);
|
|
19393
|
-
return;
|
|
19394
|
-
}
|
|
19395
20076
|
let stats;
|
|
19396
20077
|
try {
|
|
19397
|
-
stats = await fsp2.stat(filePath);
|
|
20078
|
+
stats = await fsp2.stat(filePath, { bigint: true });
|
|
19398
20079
|
} catch (error) {
|
|
19399
20080
|
if (error.code !== "ENOENT") throw error;
|
|
19400
20081
|
rebuildTranscriptIndex(filePath, Buffer.alloc(0), index);
|
|
20082
|
+
index.identity = void 0;
|
|
20083
|
+
index.signature = void 0;
|
|
19401
20084
|
return;
|
|
19402
20085
|
}
|
|
19403
|
-
|
|
20086
|
+
const identity = `${stats.dev}:${stats.ino}:${stats.birthtimeNs}`;
|
|
20087
|
+
const signature = `${identity}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
|
|
20088
|
+
const size = Number(stats.size);
|
|
20089
|
+
if (!index.initialized || index.identity !== identity || size < index.offset || size === index.offset && index.signature !== signature) {
|
|
19404
20090
|
rebuildTranscriptIndex(filePath, await readTranscriptBuffer(filePath), index);
|
|
19405
|
-
|
|
20091
|
+
} else if (size > index.offset) {
|
|
20092
|
+
const tail = await readTranscriptTail(filePath, index.offset);
|
|
20093
|
+
consumeTranscriptBytes(filePath, tail.bytes, index);
|
|
20094
|
+
index.offset = tail.size;
|
|
19406
20095
|
}
|
|
19407
|
-
|
|
19408
|
-
|
|
19409
|
-
consumeTranscriptBytes(filePath, tail.bytes, index);
|
|
19410
|
-
index.offset = tail.size;
|
|
20096
|
+
index.identity = identity;
|
|
20097
|
+
index.signature = signature;
|
|
19411
20098
|
}
|
|
19412
20099
|
async function appendTranscriptEnvelope(filePath, envelope) {
|
|
19413
20100
|
const index = getTranscriptIndex(filePath);
|
|
@@ -19424,6 +20111,9 @@ async function appendTranscriptEnvelope(filePath, envelope) {
|
|
|
19424
20111
|
index.endsWithNewline = true;
|
|
19425
20112
|
index.offset += bytes.length;
|
|
19426
20113
|
index.keys.add(key2);
|
|
20114
|
+
const stats = await fsp2.stat(filePath, { bigint: true });
|
|
20115
|
+
index.identity = `${stats.dev}:${stats.ino}:${stats.birthtimeNs}`;
|
|
20116
|
+
index.signature = `${index.identity}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
|
|
19427
20117
|
});
|
|
19428
20118
|
}
|
|
19429
20119
|
function removeAdjacentDuplicateEnvelopes(parsed) {
|
|
@@ -19440,7 +20130,9 @@ function removeAdjacentDuplicateEnvelopes(parsed) {
|
|
|
19440
20130
|
function createNodeTranscriptStore(options) {
|
|
19441
20131
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19442
20132
|
function filePath(sessionId) {
|
|
19443
|
-
|
|
20133
|
+
const target = safeFilePath(paths.transcriptsDir, sessionId, ".jsonl");
|
|
20134
|
+
assertSafeNodePath(paths.root, target);
|
|
20135
|
+
return target;
|
|
19444
20136
|
}
|
|
19445
20137
|
return {
|
|
19446
20138
|
async append(sessionId, envelope) {
|
|
@@ -19455,6 +20147,88 @@ function createNodeTranscriptStore(options) {
|
|
|
19455
20147
|
return removeAdjacentDuplicateEnvelopes(rebuildTranscriptIndex(target, await readTranscriptBuffer(target), index));
|
|
19456
20148
|
});
|
|
19457
20149
|
},
|
|
20150
|
+
/** 从字节游标增量读取 JSONL,不初始化目录、不持有写锁。 */
|
|
20151
|
+
async readPage(sessionId, options2) {
|
|
20152
|
+
if (!Number.isInteger(options2.limit) || options2.limit < 1 || options2.limit > 100) throw new Error("THREAD_CURSOR_INVALID");
|
|
20153
|
+
assertNodeStateSchema(paths.root);
|
|
20154
|
+
let offset = 0;
|
|
20155
|
+
let identity;
|
|
20156
|
+
if (options2.cursor) {
|
|
20157
|
+
try {
|
|
20158
|
+
const data = JSON.parse(Buffer.from(options2.cursor, "base64url").toString("utf8"));
|
|
20159
|
+
if (data.sessionId !== sessionId || !Number.isSafeInteger(data.offset) || data.offset < 0) throw new Error();
|
|
20160
|
+
offset = data.offset;
|
|
20161
|
+
identity = { dev: parseTranscriptFileIdentity(data.dev), ino: parseTranscriptFileIdentity(data.ino), size: data.size, stamp: data.stamp };
|
|
20162
|
+
if (data.size !== void 0 && (!Number.isSafeInteger(data.size) || data.size < offset) || data.stamp !== void 0 && typeof data.stamp !== "string") throw new Error();
|
|
20163
|
+
} catch {
|
|
20164
|
+
throw new Error("THREAD_CURSOR_INVALID");
|
|
20165
|
+
}
|
|
20166
|
+
}
|
|
20167
|
+
let handle;
|
|
20168
|
+
try {
|
|
20169
|
+
handle = await fsp2.open(filePath(sessionId), "r");
|
|
20170
|
+
} catch (error) {
|
|
20171
|
+
if (error.code === "ENOENT") {
|
|
20172
|
+
if (offset === 0) return { items: [] };
|
|
20173
|
+
throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20174
|
+
}
|
|
20175
|
+
throw error;
|
|
20176
|
+
}
|
|
20177
|
+
try {
|
|
20178
|
+
const stats = await handle.stat({ bigint: true });
|
|
20179
|
+
const size = Number(stats.size);
|
|
20180
|
+
const dev = stats.dev.toString();
|
|
20181
|
+
const ino = stats.ino.toString();
|
|
20182
|
+
if (!Number.isSafeInteger(size)) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20183
|
+
const stamp = `${stats.mtimeNs}:${stats.ctimeNs}:${stats.birthtimeNs}`;
|
|
20184
|
+
if (identity && (identity.dev !== dev || identity.ino !== ino || identity.size === size && identity.stamp !== void 0 && identity.stamp !== stamp)) throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20185
|
+
if (offset > size) throw new Error("THREAD_CURSOR_EXPIRED");
|
|
20186
|
+
if (offset > 0) {
|
|
20187
|
+
const previous = Buffer.alloc(1);
|
|
20188
|
+
await handle.read(previous, 0, 1, offset - 1);
|
|
20189
|
+
if (previous[0] !== 10) throw new Error("THREAD_CURSOR_INVALID");
|
|
20190
|
+
}
|
|
20191
|
+
const items = [];
|
|
20192
|
+
let position = offset;
|
|
20193
|
+
let lineStart = offset;
|
|
20194
|
+
let pending = Buffer.alloc(0);
|
|
20195
|
+
const chunk = Buffer.alloc(16 * 1024);
|
|
20196
|
+
while (position < size && items.length < options2.limit) {
|
|
20197
|
+
const result = await handle.read(chunk, 0, Math.min(chunk.length, size - position), position);
|
|
20198
|
+
if (!result.bytesRead) break;
|
|
20199
|
+
let start = 0;
|
|
20200
|
+
for (let i = 0; i < result.bytesRead; i++) {
|
|
20201
|
+
if (chunk[i] !== 10) continue;
|
|
20202
|
+
const line = pending.length ? Buffer.concat([pending, chunk.subarray(start, i)]) : chunk.subarray(start, i);
|
|
20203
|
+
if (line.length > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20204
|
+
let item;
|
|
20205
|
+
try {
|
|
20206
|
+
item = JSON.parse(line.toString("utf8"));
|
|
20207
|
+
} catch {
|
|
20208
|
+
throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20209
|
+
}
|
|
20210
|
+
if (item.sessionId !== sessionId) throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20211
|
+
items.push(item);
|
|
20212
|
+
lineStart = position + i + 1;
|
|
20213
|
+
pending = Buffer.alloc(0);
|
|
20214
|
+
start = i + 1;
|
|
20215
|
+
if (items.length === options2.limit) break;
|
|
20216
|
+
}
|
|
20217
|
+
if (items.length === options2.limit) {
|
|
20218
|
+
position = lineStart;
|
|
20219
|
+
break;
|
|
20220
|
+
}
|
|
20221
|
+
pending = Buffer.concat([pending, chunk.subarray(start, result.bytesRead)]);
|
|
20222
|
+
if (pending.length > 1024 * 1024) throw new Error("THREAD_PAYLOAD_TOO_LARGE");
|
|
20223
|
+
position += result.bytesRead;
|
|
20224
|
+
}
|
|
20225
|
+
if (position >= size && pending.length > 0) throw new Error("DURABLE_JSONL_CORRUPTED");
|
|
20226
|
+
const cursor = Buffer.from(JSON.stringify({ sessionId, offset: lineStart, dev, ino, size, stamp })).toString("base64url");
|
|
20227
|
+
return { items, cursor, ...lineStart < size ? { nextCursor: cursor } : {} };
|
|
20228
|
+
} finally {
|
|
20229
|
+
await handle.close();
|
|
20230
|
+
}
|
|
20231
|
+
},
|
|
19458
20232
|
async deleteBySession(sessionId) {
|
|
19459
20233
|
await ensureTranscriptDirectory(paths.root);
|
|
19460
20234
|
const target = filePath(sessionId);
|
|
@@ -19476,20 +20250,20 @@ function createNodeTranscriptStore(options) {
|
|
|
19476
20250
|
}
|
|
19477
20251
|
|
|
19478
20252
|
// src/node/stores/node-turn-store.ts
|
|
19479
|
-
import
|
|
20253
|
+
import fs21 from "node:fs";
|
|
19480
20254
|
function createNodeTurnStore(options) {
|
|
19481
20255
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19482
20256
|
function ensureDir() {
|
|
19483
20257
|
const state = ensureNodeStateRoot(paths.root);
|
|
19484
|
-
|
|
20258
|
+
fs21.mkdirSync(state.turnsDir, { recursive: true });
|
|
19485
20259
|
}
|
|
19486
20260
|
function filePath(turnId) {
|
|
19487
20261
|
return safeFilePath(paths.turnsDir, turnId, ".json");
|
|
19488
20262
|
}
|
|
19489
20263
|
return {
|
|
19490
20264
|
async get(id) {
|
|
19491
|
-
|
|
19492
|
-
return
|
|
20265
|
+
assertNodeStateSchema(paths.root);
|
|
20266
|
+
return readJsonFile(filePath(id));
|
|
19493
20267
|
},
|
|
19494
20268
|
async save(turn) {
|
|
19495
20269
|
ensureDir();
|
|
@@ -19498,9 +20272,10 @@ function createNodeTurnStore(options) {
|
|
|
19498
20272
|
});
|
|
19499
20273
|
},
|
|
19500
20274
|
async list(sessionId) {
|
|
19501
|
-
|
|
20275
|
+
assertNodeStateSchema(paths.root);
|
|
19502
20276
|
const turns = [];
|
|
19503
|
-
|
|
20277
|
+
if (!fs21.existsSync(paths.turnsDir)) return turns;
|
|
20278
|
+
for (const file of fs21.readdirSync(paths.turnsDir).filter((entry) => entry.endsWith(".json"))) {
|
|
19504
20279
|
const turn = readJsonFile(filePath(file.slice(0, -5)));
|
|
19505
20280
|
if (turn?.sessionId === sessionId) turns.push(turn);
|
|
19506
20281
|
}
|
|
@@ -19517,7 +20292,7 @@ function createNodeTurnStore(options) {
|
|
|
19517
20292
|
for (const turn of turns) {
|
|
19518
20293
|
const target = filePath(turn.id);
|
|
19519
20294
|
await withFileLock(target, () => {
|
|
19520
|
-
if (
|
|
20295
|
+
if (fs21.existsSync(target)) fs21.unlinkSync(target);
|
|
19521
20296
|
});
|
|
19522
20297
|
}
|
|
19523
20298
|
}
|
|
@@ -19525,12 +20300,12 @@ function createNodeTurnStore(options) {
|
|
|
19525
20300
|
}
|
|
19526
20301
|
|
|
19527
20302
|
// src/node/stores/node-lease-store.ts
|
|
19528
|
-
import
|
|
20303
|
+
import fs22 from "node:fs";
|
|
19529
20304
|
function createNodeLeaseStore(options) {
|
|
19530
20305
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19531
20306
|
function ensureDir() {
|
|
19532
20307
|
const state = ensureNodeStateRoot(paths.root);
|
|
19533
|
-
|
|
20308
|
+
fs22.mkdirSync(state.leasesDir, { recursive: true });
|
|
19534
20309
|
}
|
|
19535
20310
|
function filePath(sessionId) {
|
|
19536
20311
|
return safeFilePath(paths.leasesDir, sessionId, ".json");
|
|
@@ -19539,6 +20314,11 @@ function createNodeLeaseStore(options) {
|
|
|
19539
20314
|
return now - record.lease.heartbeatAt <= staleAfterMs;
|
|
19540
20315
|
}
|
|
19541
20316
|
return {
|
|
20317
|
+
/** 原子替换文件允许无锁只读;禁止在状态查询中初始化或迁移存储。 */
|
|
20318
|
+
async readCurrent(sessionId) {
|
|
20319
|
+
const current = readJsonFile(filePath(sessionId));
|
|
20320
|
+
return current ? { turnId: current.turnId, lease: { ...current.lease } } : null;
|
|
20321
|
+
},
|
|
19542
20322
|
async acquire(input) {
|
|
19543
20323
|
ensureDir();
|
|
19544
20324
|
const target = filePath(input.sessionId);
|
|
@@ -19567,7 +20347,7 @@ function createNodeLeaseStore(options) {
|
|
|
19567
20347
|
return withFileLock(target, () => {
|
|
19568
20348
|
const current = readJsonFile(target);
|
|
19569
20349
|
if (!current || current.lease.leaseId !== input.lease.leaseId || current.lease.ownerId !== input.lease.ownerId) return false;
|
|
19570
|
-
if (
|
|
20350
|
+
if (fs22.existsSync(target)) fs22.unlinkSync(target);
|
|
19571
20351
|
return true;
|
|
19572
20352
|
});
|
|
19573
20353
|
},
|
|
@@ -19575,7 +20355,7 @@ function createNodeLeaseStore(options) {
|
|
|
19575
20355
|
ensureDir();
|
|
19576
20356
|
const target = filePath(sessionId);
|
|
19577
20357
|
await withFileLock(target, () => {
|
|
19578
|
-
if (
|
|
20358
|
+
if (fs22.existsSync(target)) fs22.unlinkSync(target);
|
|
19579
20359
|
});
|
|
19580
20360
|
}
|
|
19581
20361
|
};
|
|
@@ -19590,26 +20370,26 @@ function createNodeClock() {
|
|
|
19590
20370
|
}
|
|
19591
20371
|
|
|
19592
20372
|
// src/node/stores/node-job-store.ts
|
|
19593
|
-
import
|
|
19594
|
-
import
|
|
20373
|
+
import fs23 from "node:fs";
|
|
20374
|
+
import path18 from "node:path";
|
|
19595
20375
|
function createNodeJobStore(options) {
|
|
19596
20376
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19597
20377
|
function ensureDir() {
|
|
19598
20378
|
const state = ensureNodeStateRoot(paths.root);
|
|
19599
|
-
|
|
20379
|
+
fs23.mkdirSync(state.jobsDir, { recursive: true });
|
|
19600
20380
|
}
|
|
19601
20381
|
function filePath(id) {
|
|
19602
20382
|
return safeFilePath(paths.jobsDir, id, ".json");
|
|
19603
20383
|
}
|
|
19604
20384
|
function sessionLockPath(sessionId) {
|
|
19605
|
-
return safeFilePath(
|
|
20385
|
+
return safeFilePath(path18.join(paths.jobsDir, ".session-locks"), sessionId, ".guard");
|
|
19606
20386
|
}
|
|
19607
20387
|
function sameOwner(first, second) {
|
|
19608
20388
|
return first?.runtimeInstanceId === second.runtimeInstanceId && first.hostProcessId === second.hostProcessId;
|
|
19609
20389
|
}
|
|
19610
20390
|
function readAll() {
|
|
19611
20391
|
ensureDir();
|
|
19612
|
-
return
|
|
20392
|
+
return fs23.readdirSync(paths.jobsDir).filter((file) => file.endsWith(".json")).flatMap((file) => {
|
|
19613
20393
|
const job = readJsonFile(filePath(file.slice(0, -5)));
|
|
19614
20394
|
return job ? [job] : [];
|
|
19615
20395
|
});
|
|
@@ -19622,7 +20402,7 @@ function createNodeJobStore(options) {
|
|
|
19622
20402
|
async create(job) {
|
|
19623
20403
|
ensureDir();
|
|
19624
20404
|
return withFileLock(filePath(job.id), function createIfMissing() {
|
|
19625
|
-
if (
|
|
20405
|
+
if (fs23.existsSync(filePath(job.id))) return false;
|
|
19626
20406
|
atomicReplace(filePath(job.id), JSON.stringify(job, null, 2));
|
|
19627
20407
|
return true;
|
|
19628
20408
|
});
|
|
@@ -19651,7 +20431,7 @@ function createNodeJobStore(options) {
|
|
|
19651
20431
|
for (const job of await this.listBySession(sessionId)) {
|
|
19652
20432
|
const target = filePath(job.id);
|
|
19653
20433
|
await withFileLock(target, () => {
|
|
19654
|
-
if (
|
|
20434
|
+
if (fs23.existsSync(target)) fs23.unlinkSync(target);
|
|
19655
20435
|
});
|
|
19656
20436
|
}
|
|
19657
20437
|
},
|
|
@@ -19679,43 +20459,43 @@ function createNodeJobOwnerProbe() {
|
|
|
19679
20459
|
}
|
|
19680
20460
|
|
|
19681
20461
|
// src/node/stores/node-file-mutation-store.ts
|
|
19682
|
-
import { createHash as
|
|
19683
|
-
import
|
|
19684
|
-
import
|
|
20462
|
+
import { createHash as createHash4, randomUUID as randomUUID5 } from "node:crypto";
|
|
20463
|
+
import fs24 from "node:fs";
|
|
20464
|
+
import path19 from "node:path";
|
|
19685
20465
|
var MAX_FILE_SNAPSHOT_BYTES = 512 * 1024;
|
|
19686
20466
|
var MAX_SESSION_SNAPSHOT_BYTES = 5 * 1024 * 1024;
|
|
19687
20467
|
function sha256(content) {
|
|
19688
|
-
return
|
|
20468
|
+
return createHash4("sha256").update(content).digest("hex");
|
|
19689
20469
|
}
|
|
19690
20470
|
function writeBlob(blobPath, content) {
|
|
19691
|
-
if (
|
|
19692
|
-
|
|
20471
|
+
if (fs24.existsSync(blobPath)) return;
|
|
20472
|
+
fs24.mkdirSync(path19.dirname(blobPath), { recursive: true });
|
|
19693
20473
|
const temporary = `${blobPath}.${process.pid}.${randomUUID5()}.tmp`;
|
|
19694
20474
|
try {
|
|
19695
|
-
const descriptor =
|
|
20475
|
+
const descriptor = fs24.openSync(temporary, "wx");
|
|
19696
20476
|
try {
|
|
19697
|
-
|
|
19698
|
-
|
|
20477
|
+
fs24.writeFileSync(descriptor, content);
|
|
20478
|
+
fs24.fsyncSync(descriptor);
|
|
19699
20479
|
} finally {
|
|
19700
|
-
|
|
20480
|
+
fs24.closeSync(descriptor);
|
|
19701
20481
|
}
|
|
19702
20482
|
try {
|
|
19703
|
-
|
|
20483
|
+
fs24.renameSync(temporary, blobPath);
|
|
19704
20484
|
} catch (error) {
|
|
19705
|
-
if (!
|
|
20485
|
+
if (!fs24.existsSync(blobPath)) throw error;
|
|
19706
20486
|
}
|
|
19707
20487
|
} finally {
|
|
19708
|
-
if (
|
|
20488
|
+
if (fs24.existsSync(temporary)) fs24.unlinkSync(temporary);
|
|
19709
20489
|
}
|
|
19710
20490
|
}
|
|
19711
20491
|
function createNodeFileMutationStore(options) {
|
|
19712
20492
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19713
20493
|
function ensureDir() {
|
|
19714
20494
|
const state = ensureNodeStateRoot(paths.root);
|
|
19715
|
-
|
|
19716
|
-
|
|
19717
|
-
|
|
19718
|
-
|
|
20495
|
+
fs24.mkdirSync(state.mutationsDir, { recursive: true });
|
|
20496
|
+
fs24.mkdirSync(state.mutationBlobsDir, { recursive: true });
|
|
20497
|
+
fs24.mkdirSync(state.mutationLocksDir, { recursive: true });
|
|
20498
|
+
fs24.mkdirSync(state.undoTransactionsDir, { recursive: true });
|
|
19719
20499
|
}
|
|
19720
20500
|
function mutationPath(id) {
|
|
19721
20501
|
return safeFilePath(paths.mutationsDir, id, ".json");
|
|
@@ -19729,9 +20509,9 @@ function createNodeFileMutationStore(options) {
|
|
|
19729
20509
|
}
|
|
19730
20510
|
function readAll() {
|
|
19731
20511
|
ensureDir();
|
|
19732
|
-
return
|
|
20512
|
+
return fs24.readdirSync(paths.mutationsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
|
|
19733
20513
|
try {
|
|
19734
|
-
return [JSON.parse(
|
|
20514
|
+
return [JSON.parse(fs24.readFileSync(mutationPath(entry.slice(0, -5)), "utf8"))];
|
|
19735
20515
|
} catch {
|
|
19736
20516
|
return [];
|
|
19737
20517
|
}
|
|
@@ -19739,9 +20519,9 @@ function createNodeFileMutationStore(options) {
|
|
|
19739
20519
|
}
|
|
19740
20520
|
function readTransactions() {
|
|
19741
20521
|
ensureDir();
|
|
19742
|
-
return
|
|
20522
|
+
return fs24.readdirSync(paths.undoTransactionsDir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
|
|
19743
20523
|
try {
|
|
19744
|
-
return [JSON.parse(
|
|
20524
|
+
return [JSON.parse(fs24.readFileSync(transactionPath(entry.slice(0, -5)), "utf8"))];
|
|
19745
20525
|
} catch {
|
|
19746
20526
|
return [];
|
|
19747
20527
|
}
|
|
@@ -19749,7 +20529,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19749
20529
|
}
|
|
19750
20530
|
function sessionBlobBytes(sessionId) {
|
|
19751
20531
|
const refs3 = new Set(readAll().filter((item) => item.sessionId === sessionId).flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
|
|
19752
|
-
return [...refs3].reduce((total, ref) => total + (
|
|
20532
|
+
return [...refs3].reduce((total, ref) => total + (fs24.statSync(blobPath(ref), { throwIfNoEntry: false })?.size ?? 0), 0);
|
|
19753
20533
|
}
|
|
19754
20534
|
return {
|
|
19755
20535
|
async prepare(input) {
|
|
@@ -19759,7 +20539,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19759
20539
|
const refs3 = /* @__PURE__ */ new Map();
|
|
19760
20540
|
if (input.before) refs3.set(beforeRef, input.before);
|
|
19761
20541
|
if (input.after) refs3.set(afterRef, input.after);
|
|
19762
|
-
const additionalBytes = [...refs3.entries()].filter(([ref]) => !
|
|
20542
|
+
const additionalBytes = [...refs3.entries()].filter(([ref]) => !fs24.existsSync(blobPath(ref))).reduce((total, [, content]) => total + content.byteLength, 0);
|
|
19763
20543
|
const byteCount = (input.before?.byteLength ?? 0) + (input.after?.byteLength ?? 0);
|
|
19764
20544
|
const binary2 = Boolean(input.before?.includes(0) || input.after?.includes(0));
|
|
19765
20545
|
const reversible = !binary2 && byteCount <= MAX_FILE_SNAPSHOT_BYTES && sessionBlobBytes(input.sessionId) + additionalBytes <= MAX_SESSION_SNAPSHOT_BYTES;
|
|
@@ -19790,7 +20570,7 @@ function createNodeFileMutationStore(options) {
|
|
|
19790
20570
|
async getBlob(ref) {
|
|
19791
20571
|
ensureDir();
|
|
19792
20572
|
try {
|
|
19793
|
-
const content =
|
|
20573
|
+
const content = fs24.readFileSync(blobPath(ref));
|
|
19794
20574
|
return sha256(content) === ref ? content : null;
|
|
19795
20575
|
} catch {
|
|
19796
20576
|
return null;
|
|
@@ -19808,14 +20588,14 @@ function createNodeFileMutationStore(options) {
|
|
|
19808
20588
|
},
|
|
19809
20589
|
async deleteBySession(sessionId) {
|
|
19810
20590
|
ensureDir();
|
|
19811
|
-
for (const mutation of readAll().filter((item) => item.sessionId === sessionId))
|
|
19812
|
-
for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId))
|
|
20591
|
+
for (const mutation of readAll().filter((item) => item.sessionId === sessionId)) fs24.rmSync(mutationPath(mutation.id), { force: true });
|
|
20592
|
+
for (const transaction of readTransactions().filter((item) => item.sessionId === sessionId)) fs24.rmSync(transactionPath(transaction.id), { force: true });
|
|
19813
20593
|
const referenced = new Set(readAll().flatMap((item) => [item.beforeRef, item.afterRef]).filter((ref) => Boolean(ref)));
|
|
19814
|
-
for (const entry of
|
|
20594
|
+
for (const entry of fs24.readdirSync(paths.mutationBlobsDir).filter((item) => item.endsWith(".blob"))) if (!referenced.has(entry.slice(0, -5))) fs24.rmSync(path19.join(paths.mutationBlobsDir, entry), { force: true });
|
|
19815
20595
|
},
|
|
19816
20596
|
async withWorkspaceLock(workspaceRoot, operation, canonicalTargets = []) {
|
|
19817
20597
|
ensureDir();
|
|
19818
|
-
const lockId =
|
|
20598
|
+
const lockId = createHash4("sha256").update(path19.resolve(workspaceRoot)).digest("hex");
|
|
19819
20599
|
return withFileLock(safeFilePath(paths.mutationLocksDir, lockId, ".lock-target"), function lockTargets() {
|
|
19820
20600
|
return withNodeFileMutationLocks(canonicalTargets, operation);
|
|
19821
20601
|
}, { requireExitedOwner: true });
|
|
@@ -19824,32 +20604,94 @@ function createNodeFileMutationStore(options) {
|
|
|
19824
20604
|
}
|
|
19825
20605
|
|
|
19826
20606
|
// src/node/stores/node-session-resource-store.ts
|
|
19827
|
-
import
|
|
19828
|
-
import
|
|
20607
|
+
import fs25 from "node:fs";
|
|
20608
|
+
import path20 from "node:path";
|
|
19829
20609
|
function isAttachmentSessionId(sessionId) {
|
|
19830
20610
|
return /^[0-9a-f-]{36}$/iu.test(sessionId);
|
|
19831
20611
|
}
|
|
19832
20612
|
function createNodeSessionResourceStore(workspaceRoot) {
|
|
19833
20613
|
const root = canonicalizeNodePath(workspaceRoot);
|
|
19834
|
-
const uploadsRoot =
|
|
20614
|
+
const uploadsRoot = path20.join(root, ".local", "session-uploads");
|
|
19835
20615
|
return {
|
|
19836
20616
|
async deleteBySession(sessionId) {
|
|
19837
20617
|
if (!isAttachmentSessionId(sessionId)) return;
|
|
19838
|
-
const target =
|
|
19839
|
-
if (!target.startsWith(`${uploadsRoot}${
|
|
19840
|
-
|
|
20618
|
+
const target = path20.join(uploadsRoot, sessionId);
|
|
20619
|
+
if (!target.startsWith(`${uploadsRoot}${path20.sep}`)) throw new Error("SESSION_RESOURCE_PATH_INVALID");
|
|
20620
|
+
fs25.rmSync(target, { recursive: true, force: true, maxRetries: 2 });
|
|
20621
|
+
}
|
|
20622
|
+
};
|
|
20623
|
+
}
|
|
20624
|
+
|
|
20625
|
+
// src/node/stores/node-session-image-store.ts
|
|
20626
|
+
import crypto3 from "node:crypto";
|
|
20627
|
+
import fs26 from "node:fs";
|
|
20628
|
+
import path21 from "node:path";
|
|
20629
|
+
import { normalizeWorkImage } from "@autopilot-agent/core";
|
|
20630
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
20631
|
+
function sessionDirectory(root, sessionId, create3) {
|
|
20632
|
+
if (!UUID.test(sessionId)) throw new Error("SESSION_IMAGE_INVALID");
|
|
20633
|
+
let current = fs26.realpathSync(root);
|
|
20634
|
+
for (const part of [".local", "session-uploads", sessionId]) {
|
|
20635
|
+
current = path21.join(current, part);
|
|
20636
|
+
if (create3) {
|
|
20637
|
+
try {
|
|
20638
|
+
fs26.mkdirSync(current);
|
|
20639
|
+
} catch (error) {
|
|
20640
|
+
if (error.code !== "EEXIST") throw error;
|
|
20641
|
+
}
|
|
20642
|
+
}
|
|
20643
|
+
const stat = fs26.lstatSync(current);
|
|
20644
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("SESSION_IMAGE_INVALID");
|
|
20645
|
+
}
|
|
20646
|
+
return current;
|
|
20647
|
+
}
|
|
20648
|
+
function createNodeSessionImageStore(workspaceRoot) {
|
|
20649
|
+
return {
|
|
20650
|
+
/** 校验并保存规范化副本与不可变元数据。 */
|
|
20651
|
+
async put(input) {
|
|
20652
|
+
let normalized;
|
|
20653
|
+
try {
|
|
20654
|
+
normalized = await normalizeWorkImage({ bytes: input.bytes, mimeType: input.mimeType });
|
|
20655
|
+
} catch {
|
|
20656
|
+
throw new Error("SESSION_IMAGE_INVALID");
|
|
20657
|
+
}
|
|
20658
|
+
const directory = sessionDirectory(workspaceRoot, input.sessionId, true);
|
|
20659
|
+
const id = crypto3.randomUUID();
|
|
20660
|
+
const extension = normalized.mimeType === "image/jpeg" ? ".jpg" : normalized.mimeType === "image/png" ? ".png" : normalized.mimeType === "image/webp" ? ".webp" : ".gif";
|
|
20661
|
+
const bytes = Buffer.from(normalized.bytes);
|
|
20662
|
+
const image = { id, name: path21.basename(input.name), mimeType: normalized.mimeType, relativePath: `.local/session-uploads/${input.sessionId}/${id}${extension}`, sha256: crypto3.createHash("sha256").update(bytes).digest("hex"), width: normalized.width, height: normalized.height, bytes: bytes.length, gifFirstFrame: normalized.gifFirstFrame };
|
|
20663
|
+
fs26.writeFileSync(path21.join(directory, `${id}${extension}`), bytes, { flag: "wx" });
|
|
20664
|
+
fs26.writeFileSync(path21.join(directory, `${id}.json`), JSON.stringify(image), { flag: "wx" });
|
|
20665
|
+
return image;
|
|
20666
|
+
},
|
|
20667
|
+
/** 按会话和图片标识读取并复核文件哈希。 */
|
|
20668
|
+
async read(input) {
|
|
20669
|
+
if (!UUID.test(input.id)) throw new Error("SESSION_IMAGE_INVALID");
|
|
20670
|
+
const directory = sessionDirectory(workspaceRoot, input.sessionId, false);
|
|
20671
|
+
const metadataPath = path21.join(directory, `${input.id}.json`);
|
|
20672
|
+
const metadataStat = fs26.lstatSync(metadataPath);
|
|
20673
|
+
if (!metadataStat.isFile() || metadataStat.isSymbolicLink() || metadataStat.size > 4096) throw new Error("SESSION_IMAGE_INVALID");
|
|
20674
|
+
const image = JSON.parse(fs26.readFileSync(metadataPath, "utf8"));
|
|
20675
|
+
const extension = image.mimeType === "image/jpeg" ? ".jpg" : image.mimeType === "image/png" ? ".png" : image.mimeType === "image/webp" ? ".webp" : image.mimeType === "image/gif" ? ".gif" : "";
|
|
20676
|
+
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");
|
|
20677
|
+
const filePath = path21.join(directory, `${input.id}${extension}`);
|
|
20678
|
+
const stat = fs26.lstatSync(filePath);
|
|
20679
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== image.bytes) throw new Error("SESSION_IMAGE_INVALID");
|
|
20680
|
+
const bytes = fs26.readFileSync(filePath);
|
|
20681
|
+
if (bytes.length !== image.bytes || crypto3.createHash("sha256").update(bytes).digest("hex") !== image.sha256) throw new Error("SESSION_IMAGE_INVALID");
|
|
20682
|
+
return { image, bytes };
|
|
19841
20683
|
}
|
|
19842
20684
|
};
|
|
19843
20685
|
}
|
|
19844
20686
|
|
|
19845
20687
|
// src/node/stores/node-user-question-store.ts
|
|
19846
|
-
import
|
|
20688
|
+
import fs27 from "node:fs";
|
|
19847
20689
|
function createNodeUserQuestionStore(options) {
|
|
19848
20690
|
const paths = getNodeStatePaths(options.stateRoot);
|
|
19849
20691
|
const recordsFile = `${paths.questionsDir}/requests.jsonl`;
|
|
19850
20692
|
function ensureDir() {
|
|
19851
20693
|
const state = ensureNodeStateRoot(paths.root);
|
|
19852
|
-
|
|
20694
|
+
fs27.mkdirSync(state.questionsDir, { recursive: true });
|
|
19853
20695
|
}
|
|
19854
20696
|
function answersEqual(left, right) {
|
|
19855
20697
|
return JSON.stringify(left) === JSON.stringify(right);
|
|
@@ -19914,6 +20756,7 @@ function createNodeRuntimePorts(options) {
|
|
|
19914
20756
|
}
|
|
19915
20757
|
return {
|
|
19916
20758
|
hostMutationProtection: options.productMode === "chat" ? void 0 : createNodeHostMutationProtection(options),
|
|
20759
|
+
threadStore: createNodeThreadStore(options.stateRoot),
|
|
19917
20760
|
sessionStore: createNodeSessionStore({ ...storeOptions, productMode: options.productMode }),
|
|
19918
20761
|
checkpointStore: createNodeCheckpointStore(storeOptions),
|
|
19919
20762
|
transcriptStore: createNodeTranscriptStore(storeOptions),
|
|
@@ -19937,6 +20780,7 @@ function createNodeRuntimePorts(options) {
|
|
|
19937
20780
|
throw new NodeChatError("CHAT_ATTACHMENT_STORE_REQUIRED");
|
|
19938
20781
|
}
|
|
19939
20782
|
} : createNodeSessionResourceStore(options.workspaceRoot ?? options.cwd ?? process.cwd()),
|
|
20783
|
+
sessionImageStore: options.productMode === "chat" || !options.workspaceRoot ? void 0 : createNodeSessionImageStore(options.workspaceRoot),
|
|
19940
20784
|
userQuestionStore: createNodeUserQuestionStore(storeOptions),
|
|
19941
20785
|
/**
|
|
19942
20786
|
* Stage 2:Work 模式装配真实 SRT adapter(绑定 canonical workspaceRoot;tempRoot
|
|
@@ -19953,10 +20797,16 @@ function createNodeRuntimePorts(options) {
|
|
|
19953
20797
|
};
|
|
19954
20798
|
}
|
|
19955
20799
|
|
|
20800
|
+
// src/node/runtime-owner.ts
|
|
20801
|
+
import { join } from "node:path";
|
|
20802
|
+
function withNodeRuntimeOwner(stateRoot, operation) {
|
|
20803
|
+
return withFileLock(join(stateRoot, "managed-runtime-owner"), operation, { requireExitedOwner: true });
|
|
20804
|
+
}
|
|
20805
|
+
|
|
19956
20806
|
// src/node/stores/node-chat-attachment-store.ts
|
|
19957
|
-
import
|
|
19958
|
-
import
|
|
19959
|
-
import { createHash as
|
|
20807
|
+
import fs28 from "node:fs";
|
|
20808
|
+
import path22 from "node:path";
|
|
20809
|
+
import { createHash as createHash5, randomUUID as randomUUID6 } from "node:crypto";
|
|
19960
20810
|
var CHAT_ATTACHMENT_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
19961
20811
|
var MAX_BYTES = 20 * 1024 * 1024;
|
|
19962
20812
|
var IMAGE_BYTES = 5 * 1024 * 1024;
|
|
@@ -19969,7 +20819,7 @@ function sessionKey(id) {
|
|
|
19969
20819
|
return id;
|
|
19970
20820
|
}
|
|
19971
20821
|
function digest(bytes) {
|
|
19972
|
-
return
|
|
20822
|
+
return createHash5("sha256").update(bytes).digest("hex");
|
|
19973
20823
|
}
|
|
19974
20824
|
function detectMime(bytes) {
|
|
19975
20825
|
if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png";
|
|
@@ -19995,12 +20845,12 @@ function createNodeChatAttachmentStore(options) {
|
|
|
19995
20845
|
const { paths, sessionStore } = options;
|
|
19996
20846
|
const now = options.now ?? Date.now;
|
|
19997
20847
|
const root = paths.attachmentsRoot;
|
|
19998
|
-
const dataRoot =
|
|
19999
|
-
const retiredRoot =
|
|
20000
|
-
const deletingRoot =
|
|
20001
|
-
const lock =
|
|
20848
|
+
const dataRoot = path22.join(root, "sessions");
|
|
20849
|
+
const retiredRoot = path22.join(root, "retired");
|
|
20850
|
+
const deletingRoot = path22.join(root, "deleting");
|
|
20851
|
+
const lock = path22.join(root, "lifecycle");
|
|
20002
20852
|
function ensure() {
|
|
20003
|
-
assertSafeNodePath(
|
|
20853
|
+
assertSafeNodePath(path22.dirname(paths.root), paths.root);
|
|
20004
20854
|
for (const directory of [root, dataRoot, retiredRoot, deletingRoot]) ensureChatDirectory(paths.root, directory);
|
|
20005
20855
|
assertSafeNodePath(root, `${lock}.lock`);
|
|
20006
20856
|
}
|
|
@@ -20022,9 +20872,9 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20022
20872
|
}
|
|
20023
20873
|
function isSessionDeleting(sessionId) {
|
|
20024
20874
|
try {
|
|
20025
|
-
const target =
|
|
20875
|
+
const target = path22.join(deletingRoot, `${sessionKey(sessionId)}.json`);
|
|
20026
20876
|
assertSafeNodePath(root, target);
|
|
20027
|
-
return
|
|
20877
|
+
return fs28.existsSync(target);
|
|
20028
20878
|
} catch (error) {
|
|
20029
20879
|
throw toNodeBoundaryError(error, "CHAT_ATTACHMENT_UNAVAILABLE");
|
|
20030
20880
|
}
|
|
@@ -20041,16 +20891,16 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20041
20891
|
if (session?.productMode !== "chat" || !["none", "web"].includes(session.chatRetrievalMode ?? "")) throw new NodeChatError("CHAT_UPLOAD_MODE_MISMATCH");
|
|
20042
20892
|
}
|
|
20043
20893
|
function records(sessionId) {
|
|
20044
|
-
const directory =
|
|
20894
|
+
const directory = path22.join(dataRoot, sessionKey(sessionId));
|
|
20045
20895
|
assertSafeNodePath(root, directory);
|
|
20046
|
-
if (!
|
|
20896
|
+
if (!fs28.existsSync(directory)) return [];
|
|
20047
20897
|
const result = [];
|
|
20048
|
-
for (const ref of
|
|
20898
|
+
for (const ref of fs28.readdirSync(directory)) {
|
|
20049
20899
|
if (!opaque.test(ref)) unavailable();
|
|
20050
|
-
const target =
|
|
20900
|
+
const target = path22.join(directory, ref, "metadata.json");
|
|
20051
20901
|
assertSafeNodePath(root, target);
|
|
20052
|
-
if (!
|
|
20053
|
-
const record = JSON.parse(
|
|
20902
|
+
if (!fs28.statSync(target).isFile() || fs28.statSync(target).size > 16384) unavailable();
|
|
20903
|
+
const record = JSON.parse(fs28.readFileSync(target, "utf8"));
|
|
20054
20904
|
if (record.ref !== ref || record.sessionId !== sessionId || record.status !== "active" || !["image", "document"].includes(record.kind) || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0 || record.expiresAt !== record.createdAt + CHAT_ATTACHMENT_TTL_MS || !Array.isArray(record.pages) || record.pages.length > 20) unavailable();
|
|
20055
20905
|
for (const page of record.pages) if (!opaque.test(page.ref)) unavailable();
|
|
20056
20906
|
result.push(record);
|
|
@@ -20061,7 +20911,7 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20061
20911
|
return { ref: record.ref, sessionId: record.sessionId, kind: record.kind, expiresAt: record.expiresAt };
|
|
20062
20912
|
}
|
|
20063
20913
|
function active(record) {
|
|
20064
|
-
return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !
|
|
20914
|
+
return record.expiresAt > now() && !isSessionDeleting(record.sessionId) && !fs28.existsSync(path22.join(retiredRoot, `${record.ref}.json`));
|
|
20065
20915
|
}
|
|
20066
20916
|
function sanitizeSession(session) {
|
|
20067
20917
|
try {
|
|
@@ -20100,17 +20950,17 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20100
20950
|
return !opaque.test(ref);
|
|
20101
20951
|
}
|
|
20102
20952
|
)) unavailable();
|
|
20103
|
-
const directory =
|
|
20953
|
+
const directory = path22.join(dataRoot, item.sessionId, item.ref);
|
|
20104
20954
|
assertSafeNodePath(root, directory);
|
|
20105
|
-
|
|
20955
|
+
fs28.rmSync(directory, { recursive: true, force: true });
|
|
20106
20956
|
await removePresentationRefs(item.sessionId, item.refs);
|
|
20107
|
-
|
|
20957
|
+
fs28.rmSync(path22.join(retiredRoot, `${item.ref}.json`), { force: true });
|
|
20108
20958
|
}
|
|
20109
20959
|
async function retire(record) {
|
|
20110
20960
|
const item = { sessionId: record.sessionId, ref: record.ref, refs: [record.ref, ...record.pages.map(function pageRef(page) {
|
|
20111
20961
|
return page.ref;
|
|
20112
20962
|
})] };
|
|
20113
|
-
atomicReplace(
|
|
20963
|
+
atomicReplace(path22.join(retiredRoot, `${record.ref}.json`), JSON.stringify(item));
|
|
20114
20964
|
await finishRetirement(item);
|
|
20115
20965
|
}
|
|
20116
20966
|
async function put(input) {
|
|
@@ -20143,13 +20993,13 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20143
20993
|
const createdAt = now();
|
|
20144
20994
|
if (!Number.isSafeInteger(createdAt) || createdAt < 0) unavailable();
|
|
20145
20995
|
const ref = randomUUID6();
|
|
20146
|
-
const parent =
|
|
20996
|
+
const parent = path22.join(dataRoot, sessionKey(input.sessionId));
|
|
20147
20997
|
ensureChatDirectory(root, parent);
|
|
20148
|
-
const staging =
|
|
20998
|
+
const staging = path22.join(root, `staging-${ref}`);
|
|
20149
20999
|
const record = { ref, sessionId: input.sessionId, kind, mimeType, byteLength: bytes.length, sha256: digest(bytes), createdAt, expiresAt: createdAt + CHAT_ATTACHMENT_TTL_MS, status: "active", displayName: input.displayName.split(/[\\/]/).at(-1).replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 120) || "\u9644\u4EF6", pages: [] };
|
|
20150
21000
|
try {
|
|
20151
21001
|
ensureChatDirectory(root, staging);
|
|
20152
|
-
|
|
21002
|
+
fs28.writeFileSync(path22.join(staging, "content"), bytes, { flag: "wx", mode: 384 });
|
|
20153
21003
|
let pageBytes = 0;
|
|
20154
21004
|
for (const inputPage of parsed?.pages ?? []) {
|
|
20155
21005
|
const page = Buffer.from(inputPage);
|
|
@@ -20157,17 +21007,17 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20157
21007
|
pageBytes += page.length;
|
|
20158
21008
|
if (!type2.startsWith("image/") || !page.length || page.length > IMAGE_BYTES || pageBytes > MAX_BYTES) unavailable();
|
|
20159
21009
|
const pageRef = randomUUID6();
|
|
20160
|
-
|
|
21010
|
+
fs28.writeFileSync(path22.join(staging, pageRef), page, { flag: "wx", mode: 384 });
|
|
20161
21011
|
record.pages.push({ ref: pageRef, mimeType: type2, byteLength: page.length, sha256: digest(page) });
|
|
20162
21012
|
}
|
|
20163
|
-
if (parsed)
|
|
20164
|
-
|
|
21013
|
+
if (parsed) fs28.writeFileSync(path22.join(staging, "parsed.json"), JSON.stringify({ text: parsed.text.slice(0, 16e3) }), { flag: "wx", mode: 384 });
|
|
21014
|
+
fs28.writeFileSync(path22.join(staging, "metadata.json"), JSON.stringify(record), { flag: "wx", mode: 384 });
|
|
20165
21015
|
checkSignal(input.signal);
|
|
20166
|
-
|
|
21016
|
+
fs28.renameSync(staging, path22.join(parent, ref));
|
|
20167
21017
|
const { pages: _pages, ...view } = record;
|
|
20168
21018
|
return view;
|
|
20169
21019
|
} finally {
|
|
20170
|
-
|
|
21020
|
+
fs28.rmSync(staging, { recursive: true, force: true });
|
|
20171
21021
|
}
|
|
20172
21022
|
}, input.signal);
|
|
20173
21023
|
} catch (error) {
|
|
@@ -20209,10 +21059,10 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20209
21059
|
return locked(async function readParsed() {
|
|
20210
21060
|
const { record, page } = await find3(sessionId, ref);
|
|
20211
21061
|
if (page || record.kind !== "document") unavailable();
|
|
20212
|
-
const target =
|
|
21062
|
+
const target = path22.join(dataRoot, sessionId, ref, "parsed.json");
|
|
20213
21063
|
assertSafeNodePath(root, target);
|
|
20214
|
-
if (
|
|
20215
|
-
const parsed = JSON.parse(
|
|
21064
|
+
if (fs28.statSync(target).size > 1e5) unavailable();
|
|
21065
|
+
const parsed = JSON.parse(fs28.readFileSync(target, "utf8"));
|
|
20216
21066
|
if (typeof parsed.text !== "string") unavailable();
|
|
20217
21067
|
return { text: parsed.text.slice(0, 16e3), pageImages: record.pages.map(function pageGrant(item) {
|
|
20218
21068
|
return grant({ ...record, ref: item.ref, kind: "image" });
|
|
@@ -20222,44 +21072,44 @@ function createNodeChatAttachmentStore(options) {
|
|
|
20222
21072
|
async function readBytes(sessionId, ref, signal) {
|
|
20223
21073
|
return locked(async function readContent() {
|
|
20224
21074
|
const { record, page } = await find3(sessionId, ref);
|
|
20225
|
-
const target =
|
|
21075
|
+
const target = path22.join(dataRoot, sessionId, record.ref, page?.ref ?? "content");
|
|
20226
21076
|
assertSafeNodePath(root, target);
|
|
20227
21077
|
const metadata = page ?? record;
|
|
20228
|
-
if (
|
|
20229
|
-
const bytes =
|
|
21078
|
+
if (fs28.statSync(target).size !== metadata.byteLength || metadata.byteLength > MAX_BYTES) unavailable();
|
|
21079
|
+
const bytes = fs28.readFileSync(target);
|
|
20230
21080
|
if (digest(bytes) !== metadata.sha256) unavailable();
|
|
20231
21081
|
return { bytes: new Uint8Array(bytes), mimeType: metadata.mimeType };
|
|
20232
21082
|
}, signal);
|
|
20233
21083
|
}
|
|
20234
21084
|
async function deleteBySession(sessionId) {
|
|
20235
21085
|
await locked(async function deleteSessionAttachments() {
|
|
20236
|
-
atomicReplace(
|
|
21086
|
+
atomicReplace(path22.join(deletingRoot, `${sessionKey(sessionId)}.json`), JSON.stringify({ sessionId }));
|
|
20237
21087
|
for (const record of records(sessionId)) await retire(record);
|
|
20238
21088
|
await removePresentationRefs(sessionId);
|
|
20239
|
-
|
|
21089
|
+
fs28.rmSync(path22.join(dataRoot, sessionId), { recursive: true, force: true });
|
|
20240
21090
|
}, void 0, "CHAT_ATTACHMENT_CLEANUP_FAILED");
|
|
20241
21091
|
}
|
|
20242
21092
|
async function cleanupExpired(input = {}) {
|
|
20243
21093
|
const limit = input.limit ?? 32;
|
|
20244
21094
|
if (!Number.isInteger(limit) || limit < 1 || limit > 128) throw new NodeChatError("CHAT_ATTACHMENT_CLEANUP_FAILED");
|
|
20245
21095
|
return locked(async function cleanupBatch() {
|
|
20246
|
-
for (const file of
|
|
21096
|
+
for (const file of fs28.readdirSync(root)) {
|
|
20247
21097
|
if (!/^staging-[0-9a-f-]{36}$/.test(file)) continue;
|
|
20248
|
-
const target =
|
|
21098
|
+
const target = path22.join(root, file);
|
|
20249
21099
|
assertSafeNodePath(root, target);
|
|
20250
|
-
|
|
21100
|
+
fs28.rmSync(target, { recursive: true, force: true });
|
|
20251
21101
|
}
|
|
20252
|
-
for (const file of
|
|
21102
|
+
for (const file of fs28.readdirSync(retiredRoot)) {
|
|
20253
21103
|
if (!file.endsWith(".json")) continue;
|
|
20254
|
-
const target =
|
|
21104
|
+
const target = path22.join(retiredRoot, file);
|
|
20255
21105
|
assertSafeNodePath(root, target);
|
|
20256
21106
|
checkSignal(input.signal);
|
|
20257
|
-
const item = JSON.parse(
|
|
21107
|
+
const item = JSON.parse(fs28.readFileSync(target, "utf8"));
|
|
20258
21108
|
if (file !== `${item.ref}.json`) unavailable();
|
|
20259
21109
|
await finishRetirement(item);
|
|
20260
21110
|
}
|
|
20261
21111
|
const expired = [];
|
|
20262
|
-
for (const sessionId of
|
|
21112
|
+
for (const sessionId of fs28.readdirSync(dataRoot)) {
|
|
20263
21113
|
for (const record of records(sessionId)) if (record.expiresAt <= now() || isSessionDeleting(sessionId)) expired.push(record);
|
|
20264
21114
|
}
|
|
20265
21115
|
expired.sort(function oldestFirst(left, right) {
|
|
@@ -20369,6 +21219,7 @@ function createNodeChatCapabilityLoader(options) {
|
|
|
20369
21219
|
}
|
|
20370
21220
|
const attachments = await storage.attachments.list(binding.sessionId);
|
|
20371
21221
|
return {
|
|
21222
|
+
...(binding.retrievalMode === "none" || binding.retrievalMode === "web") && options.interactiveUi === true ? { interactiveUi: true } : {},
|
|
20372
21223
|
/** 目录只含授权字段,实际引用仍由 Core 的冻结交集和 Store 复查约束。 */
|
|
20373
21224
|
attachments: attachments.map(function grant(item) {
|
|
20374
21225
|
return { ref: item.ref, displayName: item.displayName, sessionId: item.sessionId, kind: item.kind, expiresAt: item.expiresAt };
|
|
@@ -20493,7 +21344,7 @@ function createNodeRagRuntime(options) {
|
|
|
20493
21344
|
}
|
|
20494
21345
|
|
|
20495
21346
|
// src/node/settings/node-settings-writer.ts
|
|
20496
|
-
import
|
|
21347
|
+
import fs29 from "node:fs";
|
|
20497
21348
|
import { resolveAutopilotSettings as resolveAutopilotSettings3 } from "@autopilot-agent/core";
|
|
20498
21349
|
var CONFIG_KEY_ALLOWLIST = /* @__PURE__ */ new Set([
|
|
20499
21350
|
"model",
|
|
@@ -20506,9 +21357,9 @@ function createNodeSettingsWriter(options = {}) {
|
|
|
20506
21357
|
}
|
|
20507
21358
|
function readScope(scope, workspaceRoot) {
|
|
20508
21359
|
const filePath = getPaths(workspaceRoot)[scope];
|
|
20509
|
-
if (!
|
|
21360
|
+
if (!fs29.existsSync(filePath)) return {};
|
|
20510
21361
|
try {
|
|
20511
|
-
const parsed = JSON.parse(
|
|
21362
|
+
const parsed = JSON.parse(fs29.readFileSync(filePath, "utf8"));
|
|
20512
21363
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? { ...parsed } : {};
|
|
20513
21364
|
} catch {
|
|
20514
21365
|
return {};
|
|
@@ -20604,9 +21455,9 @@ function parseConfigValue(key2, rawValue) {
|
|
|
20604
21455
|
}
|
|
20605
21456
|
|
|
20606
21457
|
// src/node/settings/node-user-settings-service.ts
|
|
20607
|
-
import { createHash as
|
|
20608
|
-
import
|
|
20609
|
-
import { isExternalPermissionDiagnostic, normalizeProviderBaseUrl, resolveAutopilotSettings as resolveAutopilotSettings4 } from "@autopilot-agent/core";
|
|
21458
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
21459
|
+
import fs30 from "node:fs";
|
|
21460
|
+
import { isExternalPermissionDiagnostic, normalizeProviderBaseUrl, resolveAutopilotSettings as resolveAutopilotSettings4, resolveRouteModelCapability } from "@autopilot-agent/core";
|
|
20610
21461
|
var RAG_ROLE_CONTRACT = Object.freeze({
|
|
20611
21462
|
textRerank: { provider: "bailian", key: "RAG_TEXT_RERANK_API_KEY", dimension: false },
|
|
20612
21463
|
visionRerank: { provider: "bailian", key: "RAG_VISION_RERANK_API_KEY", dimension: false },
|
|
@@ -20643,14 +21494,14 @@ function parseApiKey(value) {
|
|
|
20643
21494
|
return typeof value === "string" && value.length <= 4096 && !/[\s\u0000-\u001f\u007f]/u.test(value) ? value : void 0;
|
|
20644
21495
|
}
|
|
20645
21496
|
function revisionOf(content) {
|
|
20646
|
-
return
|
|
21497
|
+
return createHash6("sha256").update(content).digest("hex");
|
|
20647
21498
|
}
|
|
20648
21499
|
function readUserSettings(settingsPath) {
|
|
20649
|
-
if (!
|
|
21500
|
+
if (!fs30.existsSync(settingsPath)) return { raw: {}, original: "" };
|
|
20650
21501
|
try {
|
|
20651
|
-
const stat =
|
|
21502
|
+
const stat = fs30.lstatSync(settingsPath);
|
|
20652
21503
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw new Error();
|
|
20653
|
-
const original =
|
|
21504
|
+
const original = fs30.readFileSync(settingsPath, "utf8");
|
|
20654
21505
|
const raw = JSON.parse(original);
|
|
20655
21506
|
if (!isRecord4(raw) || raw.env !== void 0 && !isRecord4(raw.env)) throw new Error();
|
|
20656
21507
|
return { raw: { ...raw }, original };
|
|
@@ -20663,7 +21514,13 @@ function assertRevision(original, revision) {
|
|
|
20663
21514
|
}
|
|
20664
21515
|
function readEnvironmentKey(environment, key2) {
|
|
20665
21516
|
if (!key2) return void 0;
|
|
20666
|
-
return parseApiKey(environment[key2]);
|
|
21517
|
+
return parseApiKey(environment[key2] ?? (key2.startsWith("USER_SETTINGS_") ? environment[key2.slice("USER_SETTINGS_".length)] : void 0));
|
|
21518
|
+
}
|
|
21519
|
+
function readMainCredential(environment, ref, env) {
|
|
21520
|
+
const configured = readEnvironmentKey(environment, ref.key);
|
|
21521
|
+
if (configured || ref.key.startsWith("USER_SETTINGS_")) return configured;
|
|
21522
|
+
const envKey = `${ref.provider.toUpperCase().replace(/[^A-Z0-9_]/gu, "_")}_${ref.key.toUpperCase()}`;
|
|
21523
|
+
return parseApiKey(env[envKey]);
|
|
20667
21524
|
}
|
|
20668
21525
|
function collectMainCredentialCandidates(raw, environment) {
|
|
20669
21526
|
const candidates = [];
|
|
@@ -20711,30 +21568,108 @@ function removeLegacyPrimaryRoutes(raw, environment) {
|
|
|
20711
21568
|
for (const key2 of removedKeys) if (!hasCredentialReference(raw, key2)) delete environment[key2];
|
|
20712
21569
|
}
|
|
20713
21570
|
function normalizeMainInput(input) {
|
|
21571
|
+
const apiProtocol = input.apiProtocol ?? "anthropic-messages";
|
|
20714
21572
|
const baseUrl = normalizeProviderBaseUrl(input.baseUrl);
|
|
20715
21573
|
const model = parseSettingString(input.model);
|
|
20716
21574
|
const apiKey = parseApiKey(input.apiKey);
|
|
20717
21575
|
const availableModels = input.availableModels?.map(function parseModel(value) {
|
|
20718
21576
|
return parseSettingString(value);
|
|
20719
21577
|
});
|
|
20720
|
-
if (!baseUrl || !model || input.apiKey !== void 0 && input.apiKey !== "" && !apiKey || availableModels && (availableModels.length === 0 || availableModels.some(function missing(value) {
|
|
21578
|
+
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) {
|
|
20721
21579
|
return !value;
|
|
20722
|
-
}) || 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");
|
|
21580
|
+
}) || 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");
|
|
20723
21581
|
for (const value of [input.opusModel, input.sonnetModel, input.haikuModel, input.subagentModel]) {
|
|
20724
21582
|
if (value !== void 0 && !parseSettingString(value)) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
20725
21583
|
}
|
|
20726
|
-
return { ...input, baseUrl, model, ...apiKey ? { apiKey } : {}, ...availableModels ? { availableModels } : {} };
|
|
21584
|
+
return { ...input, apiProtocol, baseUrl, model, ...apiKey ? { apiKey } : {}, ...availableModels ? { availableModels } : {} };
|
|
21585
|
+
}
|
|
21586
|
+
function createMainRoute(raw, input) {
|
|
21587
|
+
const previous = resolveAutopilotSettings4([{ scope: "user", value: raw }]);
|
|
21588
|
+
const selected = previous.modelRef && previous.providerRoutes[previous.modelRef.provider];
|
|
21589
|
+
const apiProtocol = input.apiProtocol ?? "anthropic-messages";
|
|
21590
|
+
const sameConnection = selected?.apiProtocol === apiProtocol && selected.baseUrl === input.baseUrl;
|
|
21591
|
+
const matches3 = sameConnection && selected.compatibilityPreset === input.compatibilityPreset;
|
|
21592
|
+
let id = selected?.id ?? "web-main";
|
|
21593
|
+
for (let suffix = 2; !selected && previous.providerRoutes[id]; suffix += 1) id = `web-main-${suffix}`;
|
|
21594
|
+
const ids = [.../* @__PURE__ */ new Set([...input.availableModels ?? (matches3 ? selected.models.map(function modelId(model) {
|
|
21595
|
+
return model.id;
|
|
21596
|
+
}) : []), input.model])];
|
|
21597
|
+
return {
|
|
21598
|
+
id,
|
|
21599
|
+
apiProtocol,
|
|
21600
|
+
baseUrl: input.baseUrl,
|
|
21601
|
+
credentialRef: sameConnection ? selected.credentialRef : { provider: id, key: `USER_SETTINGS_WEB_MAIN_${revisionOf(`${id}/${apiProtocol}/${input.baseUrl}`).slice(0, 16).toUpperCase()}` },
|
|
21602
|
+
...selected?.displayName ? { displayName: selected.displayName } : {},
|
|
21603
|
+
...input.compatibilityPreset ? { compatibilityPreset: input.compatibilityPreset } : {},
|
|
21604
|
+
...matches3 && selected.protocolProfile ? { protocolProfile: selected.protocolProfile } : {},
|
|
21605
|
+
models: ids.map(function modelEntry(modelId) {
|
|
21606
|
+
return matches3 ? selected.models.find(function matchesId(model) {
|
|
21607
|
+
return model.id === modelId;
|
|
21608
|
+
}) ?? { id: modelId } : { id: modelId };
|
|
21609
|
+
})
|
|
21610
|
+
};
|
|
21611
|
+
}
|
|
21612
|
+
function resolveMainCapabilities(route, model) {
|
|
21613
|
+
try {
|
|
21614
|
+
const capability = resolveRouteModelCapability(route, model);
|
|
21615
|
+
return { supportedReasoningEfforts: capability.supportedReasoningEfforts ?? [], supportsToolCalls: capability.supportsToolCalls !== false };
|
|
21616
|
+
} catch {
|
|
21617
|
+
throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
21618
|
+
}
|
|
20727
21619
|
}
|
|
20728
|
-
function
|
|
21620
|
+
function applyRoutedMainCategory(raw, input, env) {
|
|
21621
|
+
const route = createMainRoute(raw, input);
|
|
21622
|
+
const capabilities = resolveMainCapabilities(route, input.model);
|
|
21623
|
+
if (!capabilities.supportsToolCalls) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID", { scope: "user", code: "MODEL_NOT_SUPPORTED", field: "model" });
|
|
21624
|
+
if (input.effort && input.effort !== "auto" && !capabilities.supportedReasoningEfforts.includes(input.effort)) {
|
|
21625
|
+
throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID", { scope: "user", code: "SETTINGS_EFFORT_INVALID", field: "effortLevel" });
|
|
21626
|
+
}
|
|
21627
|
+
const environment = { ...isRecord4(raw.env) ? raw.env : {} };
|
|
21628
|
+
const previous = resolveAutopilotSettings4([{ scope: "user", value: raw }]);
|
|
21629
|
+
const selected = previous.modelRef && previous.providerRoutes[previous.modelRef.provider];
|
|
21630
|
+
const sameConnection = selected?.apiProtocol === route.apiProtocol && selected.baseUrl === route.baseUrl;
|
|
21631
|
+
if (!input.apiKey && !sameConnection) throw new NodeUserSettingsError("SETTINGS_KEY_REQUIRED");
|
|
21632
|
+
const key2 = input.apiKey ?? readMainCredential(environment, route.credentialRef, env);
|
|
21633
|
+
if (!key2) throw new NodeUserSettingsError("SETTINGS_KEY_REQUIRED");
|
|
21634
|
+
if (input.apiKey) environment[route.credentialRef.key] = input.apiKey;
|
|
21635
|
+
delete environment.ANTHROPIC_MODEL;
|
|
21636
|
+
delete environment.CLAUDE_CODE_EFFORT_LEVEL;
|
|
21637
|
+
raw.env = environment;
|
|
21638
|
+
raw.providerRoutes = { ...isRecord4(raw.providerRoutes) ? raw.providerRoutes : {}, [route.id]: route };
|
|
21639
|
+
raw.model = `${route.id}/${input.model}`;
|
|
21640
|
+
if (input.effort && input.effort !== "auto") raw.effortLevel = input.effort;
|
|
21641
|
+
else delete raw.effortLevel;
|
|
21642
|
+
}
|
|
21643
|
+
function applyMainCategory(raw, input, env) {
|
|
20729
21644
|
const normalized = normalizeMainInput(input);
|
|
21645
|
+
const previous = resolveAutopilotSettings4([{ scope: "user", value: raw }]);
|
|
21646
|
+
const previousRoute = previous.modelRef && previous.providerRoutes[previous.modelRef.provider];
|
|
21647
|
+
if (normalized.apiProtocol !== "anthropic-messages" || input.apiProtocol !== void 0 && previousRoute) {
|
|
21648
|
+
applyRoutedMainCategory(raw, normalized, env);
|
|
21649
|
+
if (normalized.maxOutputTokens === void 0) delete raw.maxOutputTokens;
|
|
21650
|
+
else raw.maxOutputTokens = normalized.maxOutputTokens;
|
|
21651
|
+
const environment2 = raw.env;
|
|
21652
|
+
const optional2 = {
|
|
21653
|
+
ANTHROPIC_DEFAULT_OPUS_MODEL: normalized.opusModel,
|
|
21654
|
+
ANTHROPIC_DEFAULT_SONNET_MODEL: normalized.sonnetModel,
|
|
21655
|
+
ANTHROPIC_DEFAULT_HAIKU_MODEL: normalized.haikuModel,
|
|
21656
|
+
CLAUDE_CODE_AUTO_COMPACT_WINDOW: normalized.compactWindow?.toString(),
|
|
21657
|
+
API_TIMEOUT_MS: normalized.timeoutMs?.toString(),
|
|
21658
|
+
CLAUDE_CODE_SUBAGENT_MODEL: normalized.subagentModel
|
|
21659
|
+
};
|
|
21660
|
+
for (const [key2, value] of Object.entries(optional2)) {
|
|
21661
|
+
if (value === void 0) delete environment2[key2];
|
|
21662
|
+
else environment2[key2] = value;
|
|
21663
|
+
}
|
|
21664
|
+
if (normalized.apiProtocol === "anthropic-messages" && normalized.alwaysThinkingEnabled !== void 0) raw.alwaysThinkingEnabled = normalized.alwaysThinkingEnabled;
|
|
21665
|
+
return;
|
|
21666
|
+
}
|
|
20730
21667
|
const environment = { ...isRecord4(raw.env) ? raw.env : {} };
|
|
20731
21668
|
const candidates = collectMainCredentialCandidates(raw, environment);
|
|
20732
21669
|
const distinct = [...new Set(candidates.map(function value(candidate) {
|
|
20733
21670
|
return candidate.value;
|
|
20734
21671
|
}))];
|
|
20735
21672
|
if (!normalized.apiKey && distinct.length > 1) throw new NodeUserSettingsError("SETTINGS_MIGRATION_CONFLICT");
|
|
20736
|
-
const previous = resolveAutopilotSettings4([{ scope: "user", value: raw }]);
|
|
20737
|
-
const previousRoute = previous.modelRef && previous.providerRoutes[previous.modelRef.provider];
|
|
20738
21673
|
const previousBaseUrl = normalizeProviderBaseUrl(previousRoute?.baseUrl ?? previous.firstParty.baseUrl);
|
|
20739
21674
|
const officialDeepSeekMigration = previousBaseUrl === "https://api.deepseek.com" && normalized.baseUrl === "https://api.deepseek.com/anthropic";
|
|
20740
21675
|
if (!normalized.apiKey && previousBaseUrl !== normalized.baseUrl && !officialDeepSeekMigration) throw new NodeUserSettingsError("SETTINGS_KEY_REQUIRED");
|
|
@@ -20761,6 +21696,7 @@ function applyMainCategory(raw, input) {
|
|
|
20761
21696
|
}
|
|
20762
21697
|
raw.env = environment;
|
|
20763
21698
|
delete raw.model;
|
|
21699
|
+
delete raw.effortLevel;
|
|
20764
21700
|
raw.availableModels = normalized.availableModels ?? [...new Set([normalized.model, normalized.opusModel, normalized.sonnetModel, normalized.haikuModel, normalized.subagentModel].filter(function present(value) {
|
|
20765
21701
|
return Boolean(value);
|
|
20766
21702
|
}))];
|
|
@@ -20769,7 +21705,7 @@ function applyMainCategory(raw, input) {
|
|
|
20769
21705
|
if (normalized.alwaysThinkingEnabled === void 0) delete raw.alwaysThinkingEnabled;
|
|
20770
21706
|
else raw.alwaysThinkingEnabled = normalized.alwaysThinkingEnabled;
|
|
20771
21707
|
}
|
|
20772
|
-
function applyWebSearch(raw, input) {
|
|
21708
|
+
function applyWebSearch(raw, input, env) {
|
|
20773
21709
|
if (typeof input.enabled !== "boolean" || typeof input.useMainKey !== "boolean") throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
20774
21710
|
if (!input.enabled) {
|
|
20775
21711
|
raw.webSearch = false;
|
|
@@ -20779,15 +21715,19 @@ function applyWebSearch(raw, input) {
|
|
|
20779
21715
|
const baseUrl = normalizeProviderBaseUrl(input.baseUrl);
|
|
20780
21716
|
const model = parseSettingString(input.model);
|
|
20781
21717
|
const environment = { ...isRecord4(raw.env) ? raw.env : {} };
|
|
20782
|
-
const
|
|
20783
|
-
const
|
|
21718
|
+
const settings = resolveAutopilotSettings4([{ scope: "user", value: raw }]);
|
|
21719
|
+
const mainRoute = settings.modelRef && settings.providerRoutes[settings.modelRef.provider];
|
|
21720
|
+
const mainBaseUrl = mainRoute?.baseUrl ?? normalizeProviderBaseUrl(environment.ANTHROPIC_BASE_URL);
|
|
21721
|
+
const mainRef = mainRoute?.credentialRef ?? { provider: "deepseek", key: "USER_SETTINGS_ANTHROPIC_AUTH_TOKEN" };
|
|
21722
|
+
const mainKey = mainRoute ? readMainCredential(environment, mainRef, env) : readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY");
|
|
21723
|
+
const canReuseMainKey = (!mainRoute || mainRoute.apiProtocol === "anthropic-messages") && mainBaseUrl === "https://api.deepseek.com/anthropic" && Boolean(mainKey);
|
|
20784
21724
|
if (input.useMainKey) {
|
|
20785
21725
|
if (!canReuseMainKey) throw new NodeUserSettingsError("SETTINGS_INPUT_INVALID");
|
|
20786
21726
|
raw.webSearch = {
|
|
20787
21727
|
provider: "deepseek",
|
|
20788
21728
|
baseUrl: "https://api.deepseek.com/anthropic",
|
|
20789
21729
|
model: "deepseek-flash",
|
|
20790
|
-
credentialRef:
|
|
21730
|
+
credentialRef: mainRef
|
|
20791
21731
|
};
|
|
20792
21732
|
return;
|
|
20793
21733
|
}
|
|
@@ -20832,6 +21772,7 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20832
21772
|
const homeDirectory = options.homeDirectory;
|
|
20833
21773
|
const settingsPath = resolveNodeUserSettingsPath(homeDirectory);
|
|
20834
21774
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
21775
|
+
const env = options.env ?? process.env;
|
|
20835
21776
|
async function save(update2, revision) {
|
|
20836
21777
|
return withFileLock(settingsPath, function writeSettings() {
|
|
20837
21778
|
ensureUserConfigDirectory({ ...homeDirectory ? { homeDirectory } : {} });
|
|
@@ -20847,6 +21788,11 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20847
21788
|
});
|
|
20848
21789
|
}
|
|
20849
21790
|
return {
|
|
21791
|
+
/** 预览草稿模型在当前 route 覆盖下的能力,不读取或返回 API Key。 */
|
|
21792
|
+
getMainModelCapabilities(input) {
|
|
21793
|
+
const normalized = normalizeMainInput(input);
|
|
21794
|
+
return resolveMainCapabilities(createMainRoute(readUserSettings(settingsPath).raw, normalized), normalized.model);
|
|
21795
|
+
},
|
|
20850
21796
|
/** 用户主动刷新时调用 DeepSeek 官方目录;无凭据、失败或异常响应均使用维护目录。 */
|
|
20851
21797
|
async refreshMainModelCatalog() {
|
|
20852
21798
|
const maintained = ["deepseek-v4-pro[1m]", "deepseek-v4-flash"];
|
|
@@ -20878,10 +21824,11 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20878
21824
|
const resolved = resolveAutopilotSettings4([{ scope: "user", value: raw }]);
|
|
20879
21825
|
const { blocking, permissions } = splitDiagnostics(resolved.diagnostics);
|
|
20880
21826
|
if (blocking.length > 0) throw new NodeUserSettingsError("SETTINGS_INVALID", safeDiagnostic(blocking[0]));
|
|
20881
|
-
const
|
|
21827
|
+
const mainRoute = resolved.modelRef && resolved.providerRoutes[resolved.modelRef.provider];
|
|
21828
|
+
const mainBaseUrl = mainRoute?.baseUrl ?? resolved.firstParty.baseUrl ?? "https://api.deepseek.com/anthropic";
|
|
20882
21829
|
const mainModel = resolved.modelRef?.modelId ?? "deepseek-v4-flash";
|
|
20883
|
-
const mainKey = readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY");
|
|
20884
|
-
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);
|
|
21830
|
+
const mainKey = mainRoute ? readMainCredential(environment, mainRoute.credentialRef, env) : readEnvironmentKey(environment, "ANTHROPIC_AUTH_TOKEN") ?? readEnvironmentKey(environment, "ANTHROPIC_API_KEY");
|
|
21831
|
+
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);
|
|
20885
21832
|
const searchKeyName = search?.credentialRef.key;
|
|
20886
21833
|
const searchKey = readEnvironmentKey(environment, searchKeyName) ?? (searchKeyName === "USER_SETTINGS_ANTHROPIC_AUTH_TOKEN" ? mainKey : void 0);
|
|
20887
21834
|
const rag = {};
|
|
@@ -20899,16 +21846,20 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20899
21846
|
return {
|
|
20900
21847
|
revision: revisionOf(current.original),
|
|
20901
21848
|
main: {
|
|
20902
|
-
provider: mainBaseUrl === "https://api.deepseek.com/anthropic" ? "deepseek" : "custom",
|
|
21849
|
+
provider: mainBaseUrl === "https://api.deepseek.com/anthropic" || mainRoute?.compatibilityPreset === "deepseek" ? "deepseek" : "custom",
|
|
21850
|
+
apiProtocol: mainRoute?.apiProtocol ?? "anthropic-messages",
|
|
21851
|
+
...mainRoute?.compatibilityPreset ? { compatibilityPreset: mainRoute.compatibilityPreset } : {},
|
|
20903
21852
|
baseUrl: mainBaseUrl,
|
|
20904
21853
|
model: mainModel,
|
|
20905
21854
|
configured: Boolean(mainKey),
|
|
20906
|
-
availableModels:
|
|
21855
|
+
availableModels: mainRoute ? mainRoute.models.map(function modelId(model) {
|
|
21856
|
+
return model.id;
|
|
21857
|
+
}) : resolved.availableModels.length > 0 ? [...resolved.availableModels] : ["deepseek-v4-flash", "deepseek-v4-pro[1m]"],
|
|
20907
21858
|
opusModel: typeof environment.ANTHROPIC_DEFAULT_OPUS_MODEL === "string" ? environment.ANTHROPIC_DEFAULT_OPUS_MODEL : void 0,
|
|
20908
21859
|
sonnetModel: typeof environment.ANTHROPIC_DEFAULT_SONNET_MODEL === "string" ? environment.ANTHROPIC_DEFAULT_SONNET_MODEL : void 0,
|
|
20909
21860
|
haikuModel: typeof environment.ANTHROPIC_DEFAULT_HAIKU_MODEL === "string" ? environment.ANTHROPIC_DEFAULT_HAIKU_MODEL : void 0,
|
|
20910
21861
|
subagentModel: resolved.firstParty.subagentModelId,
|
|
20911
|
-
effort:
|
|
21862
|
+
effort: resolved.reasoningProfile?.effort ?? "auto",
|
|
20912
21863
|
maxOutputTokens: resolved.firstParty.maxOutputTokens,
|
|
20913
21864
|
compactWindow: resolved.firstParty.compactWindow,
|
|
20914
21865
|
timeoutMs: resolved.firstParty.timeoutMs,
|
|
@@ -20916,7 +21867,7 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20916
21867
|
},
|
|
20917
21868
|
search: {
|
|
20918
21869
|
enabled: Boolean(search),
|
|
20919
|
-
useMainKey: searchKeyName === "USER_SETTINGS_ANTHROPIC_AUTH_TOKEN",
|
|
21870
|
+
useMainKey: mainRoute ? mainRoute.apiProtocol === "anthropic-messages" && mainRoute.baseUrl === "https://api.deepseek.com/anthropic" && searchKeyName === mainRoute.credentialRef.key : searchKeyName === "USER_SETTINGS_ANTHROPIC_AUTH_TOKEN",
|
|
20920
21871
|
provider: search?.provider ?? "deepseek",
|
|
20921
21872
|
baseUrl: search?.baseUrl ?? "https://api.deepseek.com",
|
|
20922
21873
|
model: search?.model ?? "deepseek-v4-flash",
|
|
@@ -20934,7 +21885,7 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20934
21885
|
/** 保存主模型分类并执行旧 route/哈希凭据迁移。 */
|
|
20935
21886
|
saveMain(input, revision) {
|
|
20936
21887
|
return save(function updateMain(raw) {
|
|
20937
|
-
applyMainCategory(raw, input);
|
|
21888
|
+
applyMainCategory(raw, input, env);
|
|
20938
21889
|
}, revision);
|
|
20939
21890
|
},
|
|
20940
21891
|
/** 原子保存设置中心的主模型分类,包含已经独立化的 Search 连接。 */
|
|
@@ -20943,8 +21894,8 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20943
21894
|
return key2 !== "main" && key2 !== "search";
|
|
20944
21895
|
})) return Promise.reject(new NodeUserSettingsError("SETTINGS_INPUT_INVALID"));
|
|
20945
21896
|
return save(function updateMainAndSearch(raw) {
|
|
20946
|
-
applyMainCategory(raw, input.main);
|
|
20947
|
-
applyWebSearch(raw, input.search);
|
|
21897
|
+
applyMainCategory(raw, input.main, env);
|
|
21898
|
+
applyWebSearch(raw, input.search, env);
|
|
20948
21899
|
}, revision);
|
|
20949
21900
|
},
|
|
20950
21901
|
/** 增量保存 RAG 分类;未提交角色保持不变。 */
|
|
@@ -20960,36 +21911,36 @@ function createNodeUserSettingsService(options = {}) {
|
|
|
20960
21911
|
}
|
|
20961
21912
|
|
|
20962
21913
|
// src/node/capabilities/memory-retriever.ts
|
|
20963
|
-
import
|
|
20964
|
-
import
|
|
20965
|
-
import
|
|
21914
|
+
import crypto4 from "node:crypto";
|
|
21915
|
+
import fs31 from "node:fs";
|
|
21916
|
+
import path23 from "node:path";
|
|
20966
21917
|
function getNodeMemoryWorkspaceId(workspaceRoot) {
|
|
20967
|
-
return
|
|
21918
|
+
return crypto4.createHash("sha256").update(fs31.realpathSync.native(workspaceRoot).toLowerCase()).digest("hex").slice(0, 24);
|
|
20968
21919
|
}
|
|
20969
21920
|
function getNodeMemoryDirectory(stateRoot, workspaceRoot) {
|
|
20970
|
-
return
|
|
21921
|
+
return path23.join(path23.resolve(stateRoot), "memory", getNodeMemoryWorkspaceId(workspaceRoot));
|
|
20971
21922
|
}
|
|
20972
21923
|
function getLegacyWebMemoryDirectory(workspaceRoot, cwd = process.cwd()) {
|
|
20973
|
-
return
|
|
21924
|
+
return path23.join(path23.resolve(cwd), ".local", "agent", "workspaces", getNodeMemoryWorkspaceId(workspaceRoot), "memory");
|
|
20974
21925
|
}
|
|
20975
21926
|
function retrieveNodeMemories(_stateRoot, _workspaceRoot, _query, _maxItems = 5) {
|
|
20976
21927
|
return [];
|
|
20977
21928
|
}
|
|
20978
21929
|
|
|
20979
21930
|
// src/node/trust-policy.ts
|
|
20980
|
-
import
|
|
20981
|
-
import
|
|
21931
|
+
import fs32 from "node:fs";
|
|
21932
|
+
import path24 from "node:path";
|
|
20982
21933
|
function createNodeTrustStore(options) {
|
|
20983
21934
|
const trustRoot = resolveNodeTrustRoot({ stateRoot: options.stateRoot, trustRoot: options.trustRoot });
|
|
20984
|
-
const trustFile =
|
|
21935
|
+
const trustFile = path24.join(trustRoot, "trust.json");
|
|
20985
21936
|
const now = options.now ?? (() => Date.now());
|
|
20986
21937
|
function ensureDir() {
|
|
20987
|
-
|
|
21938
|
+
fs32.mkdirSync(trustRoot, { recursive: true });
|
|
20988
21939
|
}
|
|
20989
21940
|
function loadStore() {
|
|
20990
|
-
if (!
|
|
21941
|
+
if (!fs32.existsSync(trustFile)) return { version: 1, workspaces: {} };
|
|
20991
21942
|
try {
|
|
20992
|
-
const parsed = JSON.parse(
|
|
21943
|
+
const parsed = JSON.parse(fs32.readFileSync(trustFile, "utf8"));
|
|
20993
21944
|
if (parsed.version !== 1 || !parsed.workspaces || typeof parsed.workspaces !== "object") return { version: 1, workspaces: {} };
|
|
20994
21945
|
return { version: 1, workspaces: parsed.workspaces };
|
|
20995
21946
|
} catch {
|
|
@@ -21091,16 +22042,16 @@ function createNodeTrustPolicy(options) {
|
|
|
21091
22042
|
}
|
|
21092
22043
|
|
|
21093
22044
|
// src/node/workspace-registry.ts
|
|
21094
|
-
import
|
|
21095
|
-
import
|
|
22045
|
+
import fs33 from "node:fs";
|
|
22046
|
+
import path25 from "node:path";
|
|
21096
22047
|
function createNodeWorkspaceRegistry(options = {}) {
|
|
21097
22048
|
const globalStateRoot = resolveNodeGlobalStateRoot({ globalStateRoot: options.globalStateRoot, cwd: options.cwd });
|
|
21098
|
-
const registryPath =
|
|
22049
|
+
const registryPath = path25.join(globalStateRoot, "workspace-registry.json");
|
|
21099
22050
|
const now = options.now ?? (() => Date.now());
|
|
21100
22051
|
function load2() {
|
|
21101
|
-
if (!
|
|
22052
|
+
if (!fs33.existsSync(registryPath)) return [];
|
|
21102
22053
|
try {
|
|
21103
|
-
const parsed = JSON.parse(
|
|
22054
|
+
const parsed = JSON.parse(fs33.readFileSync(registryPath, "utf8"));
|
|
21104
22055
|
if (!Array.isArray(parsed)) return [];
|
|
21105
22056
|
return parsed.filter(function isEntry(value) {
|
|
21106
22057
|
return Boolean(value) && typeof value === "object" && typeof value.workspaceId === "string" && typeof value.workspaceRoot === "string" && typeof value.displayName === "string" && typeof value.lastOpenedAt === "number";
|
|
@@ -21123,7 +22074,7 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21123
22074
|
const next = {
|
|
21124
22075
|
workspaceId,
|
|
21125
22076
|
workspaceRoot: canonicalRoot,
|
|
21126
|
-
displayName:
|
|
22077
|
+
displayName: path25.basename(canonicalRoot) || canonicalRoot,
|
|
21127
22078
|
lastOpenedAt: now()
|
|
21128
22079
|
};
|
|
21129
22080
|
const entries2 = load2().filter(function removeExisting(entry) {
|
|
@@ -21144,11 +22095,533 @@ function createNodeWorkspaceRegistry(options = {}) {
|
|
|
21144
22095
|
}
|
|
21145
22096
|
return { list: load2, get, register, remove: remove2 };
|
|
21146
22097
|
}
|
|
22098
|
+
|
|
22099
|
+
// src/node/thread-runner.ts
|
|
22100
|
+
import { sanitizeContinuationFailure as sanitizeContinuationFailure2 } from "@autopilot-agent/core";
|
|
22101
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
22102
|
+
function createNodeThreadRunner(options) {
|
|
22103
|
+
const delivery = options.delivery;
|
|
22104
|
+
const ownerId = delivery.ownerId;
|
|
22105
|
+
const pollIntervalMs = options.pollIntervalMs ?? 250;
|
|
22106
|
+
const staleMs = options.staleMs ?? 45e3;
|
|
22107
|
+
const heartbeatMs = options.heartbeatMs ?? Math.max(200, Math.min(5e3, Math.floor(staleMs / 3)));
|
|
22108
|
+
const reconcileEveryMs = options.reconcileEveryMs ?? 3e3;
|
|
22109
|
+
const active = /* @__PURE__ */ new Map();
|
|
22110
|
+
let timer;
|
|
22111
|
+
let ticking = false;
|
|
22112
|
+
let stopped = false;
|
|
22113
|
+
let lastReconcileAt = 0;
|
|
22114
|
+
let running = false;
|
|
22115
|
+
let kicked = false;
|
|
22116
|
+
let idleDelayMs = pollIntervalMs;
|
|
22117
|
+
async function hasFreshLease(threadId) {
|
|
22118
|
+
const checkpoint = await options.ports.checkpointStore.getLatest(threadId);
|
|
22119
|
+
return Boolean(checkpoint && checkpoint.status === "running" && checkpoint.lease && Date.now() - checkpoint.lease.heartbeatAt <= delivery.leaseStaleMs);
|
|
22120
|
+
}
|
|
22121
|
+
function activeMessageIds() {
|
|
22122
|
+
return [...active.values()].filter(function deliveryRecord(record) {
|
|
22123
|
+
return !record.external && Boolean(record.messageId);
|
|
22124
|
+
}).map(function id(record) {
|
|
22125
|
+
return record.messageId;
|
|
22126
|
+
});
|
|
22127
|
+
}
|
|
22128
|
+
async function safeTick(reconcileFirst = false) {
|
|
22129
|
+
if (ticking || stopped) return;
|
|
22130
|
+
if (timer) clearTimeout(timer);
|
|
22131
|
+
timer = void 0;
|
|
22132
|
+
kicked = false;
|
|
22133
|
+
ticking = true;
|
|
22134
|
+
try {
|
|
22135
|
+
const snapshot = await delivery.querySnapshot();
|
|
22136
|
+
if (reconcileFirst || Date.now() - lastReconcileAt >= reconcileEveryMs) {
|
|
22137
|
+
lastReconcileAt = Date.now();
|
|
22138
|
+
await delivery.reconcile({ staleMs, activeMessageIds: activeMessageIds(), snapshot });
|
|
22139
|
+
}
|
|
22140
|
+
await applyInterrupts(snapshot);
|
|
22141
|
+
await applyResumes(snapshot);
|
|
22142
|
+
await applyInteractionContinuations(snapshot);
|
|
22143
|
+
const claimed = await delivery.claimDeliveries({ snapshot, activeThreads: [...active.values()].filter(function controllable(record) {
|
|
22144
|
+
return record.ready;
|
|
22145
|
+
}).map(function thread(record) {
|
|
22146
|
+
return record.threadId;
|
|
22147
|
+
}) });
|
|
22148
|
+
for (const item of claimed) startDelivery(item);
|
|
22149
|
+
idleDelayMs = active.size || claimed.length ? pollIntervalMs : Math.min(Math.max(pollIntervalMs, 2e3), idleDelayMs * 2);
|
|
22150
|
+
} catch (error) {
|
|
22151
|
+
options.onError?.(error);
|
|
22152
|
+
} finally {
|
|
22153
|
+
ticking = false;
|
|
22154
|
+
if (running && !stopped) {
|
|
22155
|
+
timer = setTimeout(function poll() {
|
|
22156
|
+
void safeTick();
|
|
22157
|
+
}, kicked ? 0 : idleDelayMs);
|
|
22158
|
+
timer.unref?.();
|
|
22159
|
+
}
|
|
22160
|
+
}
|
|
22161
|
+
}
|
|
22162
|
+
async function applyInterrupts(snapshot) {
|
|
22163
|
+
for (const intent of await delivery.pendingInterrupts(snapshot)) {
|
|
22164
|
+
const task = active.get(intent.threadId);
|
|
22165
|
+
if (!task || !task.ready || task.turnId !== intent.expectedTurnId) {
|
|
22166
|
+
const turn = await options.ports.turnStore.get(intent.expectedTurnId);
|
|
22167
|
+
if (turn && (turn.status === "waiting_approval" || turn.status === "waiting_user_input")) {
|
|
22168
|
+
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)]);
|
|
22169
|
+
const checkpointStatus = turn.status === "waiting_approval" ? "awaiting_approval" : "awaiting_user_input";
|
|
22170
|
+
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) {
|
|
22171
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22172
|
+
continue;
|
|
22173
|
+
}
|
|
22174
|
+
try {
|
|
22175
|
+
await options.runtime.turns.cancel({ sessionId: intent.threadId, turnId: intent.expectedTurnId });
|
|
22176
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: true });
|
|
22177
|
+
} catch {
|
|
22178
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22179
|
+
}
|
|
22180
|
+
continue;
|
|
22181
|
+
}
|
|
22182
|
+
const terminal = turn && turn.status !== "running" && turn.status !== "waiting_approval" && turn.status !== "waiting_user_input";
|
|
22183
|
+
if (terminal) await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22184
|
+
else if (!turn && !await hasFreshLease(intent.threadId)) {
|
|
22185
|
+
const control = await delivery.readGroup(intent.groupId);
|
|
22186
|
+
const recorded = control?.controls.find(function match(item) {
|
|
22187
|
+
return item.controlId === intent.controlId;
|
|
22188
|
+
});
|
|
22189
|
+
if (recorded && Date.now() - recorded.createdAt > staleMs) await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22190
|
+
}
|
|
22191
|
+
continue;
|
|
22192
|
+
}
|
|
22193
|
+
try {
|
|
22194
|
+
if (task.cancelExecution) await task.cancelExecution();
|
|
22195
|
+
else await options.runtime.turns.cancel({ sessionId: intent.threadId, turnId: intent.expectedTurnId });
|
|
22196
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: true });
|
|
22197
|
+
} catch {
|
|
22198
|
+
await delivery.settleInterrupt({ groupId: intent.groupId, controlId: intent.controlId, applied: false });
|
|
22199
|
+
}
|
|
22200
|
+
}
|
|
22201
|
+
}
|
|
22202
|
+
async function applyResumes(snapshot) {
|
|
22203
|
+
for (const intent of await delivery.pendingResumes(snapshot)) {
|
|
22204
|
+
if (active.has(intent.threadId) || await hasFreshLease(intent.threadId)) continue;
|
|
22205
|
+
if (!await delivery.claimResume(intent)) continue;
|
|
22206
|
+
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)]);
|
|
22207
|
+
if (!session || session.status !== "interrupted" || latest?.id !== intent.expectedTurnId || checkpoint?.turnId !== intent.expectedTurnId || createHash7("sha256").update(JSON.stringify(checkpoint)).digest("hex") !== intent.checkpointDigest) {
|
|
22208
|
+
await delivery.rejectResume(intent);
|
|
22209
|
+
continue;
|
|
22210
|
+
}
|
|
22211
|
+
const record = { threadId: intent.threadId, turnId: intent.expectedTurnId, groupId: intent.groupId, messageId: "", cancelled: false, task: Promise.resolve() };
|
|
22212
|
+
active.set(intent.threadId, record);
|
|
22213
|
+
record.task = continueOriginal().finally(function settled() {
|
|
22214
|
+
if (active.get(intent.threadId) === record) active.delete(intent.threadId);
|
|
22215
|
+
kick();
|
|
22216
|
+
});
|
|
22217
|
+
async function continueOriginal() {
|
|
22218
|
+
let started = false;
|
|
22219
|
+
try {
|
|
22220
|
+
for await (const event of options.runtime.turns.continue({ sessionId: intent.threadId, turnId: intent.expectedTurnId })) {
|
|
22221
|
+
if (event.type === "turn_started") {
|
|
22222
|
+
started = true;
|
|
22223
|
+
record.ready = true;
|
|
22224
|
+
}
|
|
22225
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) record.ready = false;
|
|
22226
|
+
}
|
|
22227
|
+
} catch (error) {
|
|
22228
|
+
if (!started) await delivery.rejectResume(intent);
|
|
22229
|
+
options.onError?.(error);
|
|
22230
|
+
} finally {
|
|
22231
|
+
await notifySettled(record);
|
|
22232
|
+
}
|
|
22233
|
+
}
|
|
22234
|
+
}
|
|
22235
|
+
}
|
|
22236
|
+
async function applyInteractionContinuations(snapshot) {
|
|
22237
|
+
for (const intent of await delivery.pendingInteractionContinuations(snapshot)) {
|
|
22238
|
+
if (active.has(intent.threadId) || await hasFreshLease(intent.threadId)) continue;
|
|
22239
|
+
if (!await delivery.claimInteractionContinuation(intent)) continue;
|
|
22240
|
+
const record = { threadId: intent.threadId, turnId: intent.expectedTurnId, groupId: intent.groupId, messageId: "", cancelled: false, task: Promise.resolve() };
|
|
22241
|
+
active.set(intent.threadId, record);
|
|
22242
|
+
record.task = continueInteraction().finally(function settled() {
|
|
22243
|
+
if (active.get(intent.threadId) === record) active.delete(intent.threadId);
|
|
22244
|
+
kick();
|
|
22245
|
+
}).catch(function report(error) {
|
|
22246
|
+
options.onError?.(error);
|
|
22247
|
+
});
|
|
22248
|
+
async function continueInteraction() {
|
|
22249
|
+
const beat = setInterval(function heartbeat() {
|
|
22250
|
+
delivery.settleInteractionContinuation({ groupId: intent.groupId, controlId: intent.controlId }).catch(function failed(error) {
|
|
22251
|
+
options.onError?.(error);
|
|
22252
|
+
});
|
|
22253
|
+
}, heartbeatMs);
|
|
22254
|
+
let stage = "read_decision";
|
|
22255
|
+
let started = false;
|
|
22256
|
+
try {
|
|
22257
|
+
const decision = intent.approvalId ? await options.ports.approvalStore.getDecision({ sessionId: intent.threadId, turnId: intent.expectedTurnId, approvalId: intent.approvalId }) : void 0;
|
|
22258
|
+
if (intent.approvalId && !decision) throw Object.assign(new Error("INTERACTION_DECISION_REQUIRED"), { code: "INTERACTION_DECISION_REQUIRED" });
|
|
22259
|
+
if (stopped || record.cancelled) {
|
|
22260
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "pending" });
|
|
22261
|
+
return;
|
|
22262
|
+
}
|
|
22263
|
+
stage = "continue";
|
|
22264
|
+
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" } } : {} })) {
|
|
22265
|
+
if (event.type === "turn_started") {
|
|
22266
|
+
started = true;
|
|
22267
|
+
stage = "after_started";
|
|
22268
|
+
record.ready = true;
|
|
22269
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "executing" });
|
|
22270
|
+
}
|
|
22271
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) record.ready = false;
|
|
22272
|
+
}
|
|
22273
|
+
await notifySettled(record);
|
|
22274
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "completed" });
|
|
22275
|
+
} catch (error) {
|
|
22276
|
+
const file = getFileOperationDiagnostic(error) ?? (error instanceof NodeStateError ? error.getStorageDiagnostic() : void 0);
|
|
22277
|
+
const code = file?.osCode ?? (error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : "CONTINUE_UNKNOWN");
|
|
22278
|
+
const failureDiagnostic = sanitizeContinuationFailure2({ stage, started, category: "unknown", code, ...file && ["lock", "temporary_write", "rename", "cleanup"].includes(file.phase) ? { filePhase: file.phase } : {} });
|
|
22279
|
+
await delivery.settleInteractionContinuation({ ...intent, status: "failed", failureCode: "CONTINUE_FAILED", failureDiagnostic });
|
|
22280
|
+
options.onError?.(error, { threadId: intent.threadId, expectedTurnId: intent.expectedTurnId, controlId: intent.controlId, approvalId: intent.approvalId, requestId: intent.requestId, failureDiagnostic });
|
|
22281
|
+
await notifySettled(record);
|
|
22282
|
+
} finally {
|
|
22283
|
+
clearInterval(beat);
|
|
22284
|
+
}
|
|
22285
|
+
}
|
|
22286
|
+
}
|
|
22287
|
+
}
|
|
22288
|
+
function startDelivery(item) {
|
|
22289
|
+
const threadId = item.delivery.threadId;
|
|
22290
|
+
const turnId = item.delivery.reservedTurnId;
|
|
22291
|
+
if (!turnId) {
|
|
22292
|
+
void delivery.failDelivery({ groupId: item.groupId, messageId: item.delivery.messageId, reason: "start_failed" });
|
|
22293
|
+
return;
|
|
22294
|
+
}
|
|
22295
|
+
if (active.has(threadId)) {
|
|
22296
|
+
void delivery.releaseDelivery({ groupId: item.groupId, messageId: item.delivery.messageId });
|
|
22297
|
+
return;
|
|
22298
|
+
}
|
|
22299
|
+
const record = { threadId, turnId, groupId: item.groupId, messageId: item.delivery.messageId, cancelled: false, task: Promise.resolve() };
|
|
22300
|
+
record.task = runDelivery(item, record).catch(function ignore() {
|
|
22301
|
+
}).finally(function finish() {
|
|
22302
|
+
if (active.get(threadId) === record) active.delete(threadId);
|
|
22303
|
+
kick();
|
|
22304
|
+
});
|
|
22305
|
+
active.set(threadId, record);
|
|
22306
|
+
}
|
|
22307
|
+
async function notifyStarted(record, message) {
|
|
22308
|
+
if (!options.onTurnStarted) return;
|
|
22309
|
+
try {
|
|
22310
|
+
await options.onTurnStarted({
|
|
22311
|
+
threadId: record.threadId,
|
|
22312
|
+
turnId: record.turnId,
|
|
22313
|
+
prompt: { content: message.content, messageId: message.messageId, from: message.from, ...message.handoff ? { handoff: message.handoff } : {}, ...message.handoffDisplay ? { handoffDisplay: message.handoffDisplay } : {} }
|
|
22314
|
+
});
|
|
22315
|
+
} catch (error) {
|
|
22316
|
+
options.onError?.(error);
|
|
22317
|
+
}
|
|
22318
|
+
}
|
|
22319
|
+
async function notifySettled(record) {
|
|
22320
|
+
if (!options.onTurnSettled) return;
|
|
22321
|
+
try {
|
|
22322
|
+
await options.onTurnSettled({ threadId: record.threadId, turnId: record.turnId });
|
|
22323
|
+
} catch (error) {
|
|
22324
|
+
options.onError?.(error);
|
|
22325
|
+
}
|
|
22326
|
+
}
|
|
22327
|
+
async function runDelivery(item, record) {
|
|
22328
|
+
const { groupId, delivery: claimed, message } = item;
|
|
22329
|
+
const turnId = record.turnId;
|
|
22330
|
+
const existing = await options.ports.turnStore.get(turnId);
|
|
22331
|
+
if (existing) {
|
|
22332
|
+
await settle(item, record, turnId);
|
|
22333
|
+
return;
|
|
22334
|
+
}
|
|
22335
|
+
if (await hasFreshLease(record.threadId)) {
|
|
22336
|
+
await delivery.releaseDelivery({ groupId, messageId: claimed.messageId });
|
|
22337
|
+
return;
|
|
22338
|
+
}
|
|
22339
|
+
let failure;
|
|
22340
|
+
const beat = setInterval(function heartbeat() {
|
|
22341
|
+
void delivery.heartbeat({ groupId, messageId: claimed.messageId });
|
|
22342
|
+
}, heartbeatMs);
|
|
22343
|
+
beat.unref?.();
|
|
22344
|
+
let controlEnded = false;
|
|
22345
|
+
try {
|
|
22346
|
+
await delivery.heartbeat({ groupId, messageId: claimed.messageId });
|
|
22347
|
+
await notifyStarted(record, message);
|
|
22348
|
+
for await (const event of options.runtime.turns.start({
|
|
22349
|
+
sessionId: record.threadId,
|
|
22350
|
+
turnId,
|
|
22351
|
+
content: message.content,
|
|
22352
|
+
// 与页面队列同语义:这是目标空闲后的下一轮,不是新话题。
|
|
22353
|
+
continuity: { source: "claimed_queue" }
|
|
22354
|
+
})) {
|
|
22355
|
+
if (["turn_completed", "turn_failed", "turn_limit_reached", "turn_interrupted", "question_required", "approval_required"].includes(event.type)) controlEnded = true;
|
|
22356
|
+
record.ready = !controlEnded;
|
|
22357
|
+
if (record.cancelled) break;
|
|
22358
|
+
}
|
|
22359
|
+
} catch (error) {
|
|
22360
|
+
failure = error;
|
|
22361
|
+
} finally {
|
|
22362
|
+
clearInterval(beat);
|
|
22363
|
+
}
|
|
22364
|
+
await settle(item, record, turnId, failure);
|
|
22365
|
+
}
|
|
22366
|
+
async function settle(item, record, turnId, failure) {
|
|
22367
|
+
const groupId = item.groupId;
|
|
22368
|
+
const messageId = item.delivery.messageId;
|
|
22369
|
+
const turn = await options.ports.turnStore.get(turnId);
|
|
22370
|
+
if (failure) {
|
|
22371
|
+
options.onError?.(failure);
|
|
22372
|
+
}
|
|
22373
|
+
if (turn) {
|
|
22374
|
+
await delivery.completeDelivery({ groupId, messageId, turnId });
|
|
22375
|
+
await notifySettled(record);
|
|
22376
|
+
return;
|
|
22377
|
+
}
|
|
22378
|
+
const code = failure?.code;
|
|
22379
|
+
if (code === "TURN_ALREADY_RUNNING") {
|
|
22380
|
+
await delivery.releaseDelivery({ groupId, messageId });
|
|
22381
|
+
return;
|
|
22382
|
+
}
|
|
22383
|
+
await delivery.failDelivery({ groupId, messageId, reason: "start_failed" });
|
|
22384
|
+
}
|
|
22385
|
+
async function stop() {
|
|
22386
|
+
stopped = true;
|
|
22387
|
+
running = false;
|
|
22388
|
+
if (timer) {
|
|
22389
|
+
clearTimeout(timer);
|
|
22390
|
+
timer = void 0;
|
|
22391
|
+
}
|
|
22392
|
+
const cancelledTurnIds = [];
|
|
22393
|
+
const unconfirmedTurnIds = [];
|
|
22394
|
+
const releasedMessageIds = [];
|
|
22395
|
+
const waitingTurnIds = [];
|
|
22396
|
+
const pendingMessageIds = [];
|
|
22397
|
+
const recoverableTurnIds = [];
|
|
22398
|
+
const tasks = [...active.values()].filter(function ownDelivery(record) {
|
|
22399
|
+
return !record.external;
|
|
22400
|
+
});
|
|
22401
|
+
for (const record of tasks) {
|
|
22402
|
+
if (record.cancelled) continue;
|
|
22403
|
+
const actual = await options.ports.turnStore.get(record.turnId);
|
|
22404
|
+
if (actual && actual.status !== "running") {
|
|
22405
|
+
if (actual.status === "waiting_approval" || actual.status === "waiting_user_input") waitingTurnIds.push(actual.id);
|
|
22406
|
+
continue;
|
|
22407
|
+
}
|
|
22408
|
+
record.cancelled = true;
|
|
22409
|
+
try {
|
|
22410
|
+
await options.runtime.turns.cancel({ sessionId: record.threadId, turnId: record.turnId });
|
|
22411
|
+
cancelledTurnIds.push(record.turnId);
|
|
22412
|
+
} catch {
|
|
22413
|
+
unconfirmedTurnIds.push(record.turnId);
|
|
22414
|
+
}
|
|
22415
|
+
}
|
|
22416
|
+
await Promise.allSettled(tasks.map(function task(record) {
|
|
22417
|
+
return record.task;
|
|
22418
|
+
}));
|
|
22419
|
+
for (const groupId of await delivery.listGroups()) {
|
|
22420
|
+
const control = await delivery.readGroup(groupId);
|
|
22421
|
+
if (!control) continue;
|
|
22422
|
+
for (const item of control.deliveries) {
|
|
22423
|
+
if (item.status === "pending" || item.status === "blocked") pendingMessageIds.push(item.messageId);
|
|
22424
|
+
const turnId = item.turnId ?? item.reservedTurnId;
|
|
22425
|
+
const turn = turnId ? await options.ports.turnStore.get(turnId) : void 0;
|
|
22426
|
+
if (turn?.status === "waiting_approval" || turn?.status === "waiting_user_input") waitingTurnIds.push(turn.id);
|
|
22427
|
+
if (turn?.status === "interrupted") recoverableTurnIds.push(turn.id);
|
|
22428
|
+
if (item.ownerId === ownerId && item.status === "claimed" && turn?.status === "running" && !cancelledTurnIds.includes(turn.id)) unconfirmedTurnIds.push(turn.id);
|
|
22429
|
+
if (item.status === "claimed" && item.ownerId === ownerId && !turn) {
|
|
22430
|
+
await delivery.releaseDelivery({ groupId, messageId: item.messageId });
|
|
22431
|
+
releasedMessageIds.push(item.messageId);
|
|
22432
|
+
pendingMessageIds.push(item.messageId);
|
|
22433
|
+
}
|
|
22434
|
+
}
|
|
22435
|
+
if (control.deliveries.some(function pending(item) {
|
|
22436
|
+
return item.status === "pending" || item.status === "blocked";
|
|
22437
|
+
})) await delivery.recordHostOffline(groupId);
|
|
22438
|
+
}
|
|
22439
|
+
for (const turnId of cancelledTurnIds) {
|
|
22440
|
+
const turn = await options.ports.turnStore.get(turnId);
|
|
22441
|
+
if (!turn || turn.status === "running") unconfirmedTurnIds.push(turnId);
|
|
22442
|
+
}
|
|
22443
|
+
return { stopped: true, cancelledTurnIds: cancelledTurnIds.filter(function confirmed(id) {
|
|
22444
|
+
return !unconfirmedTurnIds.includes(id);
|
|
22445
|
+
}), unconfirmedTurnIds: [...new Set(unconfirmedTurnIds)], releasedMessageIds, waitingTurnIds: [...new Set(waitingTurnIds)], pendingMessageIds: [...new Set(pendingMessageIds)], recoverableTurnIds: [...new Set(recoverableTurnIds)] };
|
|
22446
|
+
}
|
|
22447
|
+
function kick() {
|
|
22448
|
+
if (!running || stopped) return;
|
|
22449
|
+
idleDelayMs = pollIntervalMs;
|
|
22450
|
+
kicked = true;
|
|
22451
|
+
if (!ticking) void safeTick();
|
|
22452
|
+
}
|
|
22453
|
+
function registerExecution(input) {
|
|
22454
|
+
const previous = active.get(input.threadId);
|
|
22455
|
+
if (previous && (previous.ready || previous.turnId !== input.turnId)) throw Object.assign(new Error("TURN_ALREADY_RUNNING"), { code: "TURN_ALREADY_RUNNING" });
|
|
22456
|
+
const record = { threadId: input.threadId, turnId: input.turnId, groupId: "", messageId: "", cancelled: false, task: Promise.resolve(), external: true, ready: false, cancelExecution: input.cancel };
|
|
22457
|
+
active.set(input.threadId, record);
|
|
22458
|
+
return {
|
|
22459
|
+
activate: function activate() {
|
|
22460
|
+
if (active.get(input.threadId) === record) {
|
|
22461
|
+
record.ready = true;
|
|
22462
|
+
kick();
|
|
22463
|
+
}
|
|
22464
|
+
},
|
|
22465
|
+
release: function release() {
|
|
22466
|
+
if (active.get(input.threadId) === record) {
|
|
22467
|
+
active.delete(input.threadId);
|
|
22468
|
+
kick();
|
|
22469
|
+
}
|
|
22470
|
+
}
|
|
22471
|
+
};
|
|
22472
|
+
}
|
|
22473
|
+
async function start() {
|
|
22474
|
+
if (running) return;
|
|
22475
|
+
stopped = false;
|
|
22476
|
+
running = true;
|
|
22477
|
+
await safeTick(true);
|
|
22478
|
+
}
|
|
22479
|
+
return {
|
|
22480
|
+
start,
|
|
22481
|
+
stop,
|
|
22482
|
+
kick,
|
|
22483
|
+
registerExecution,
|
|
22484
|
+
listExecutions: function listExecutions() {
|
|
22485
|
+
return [...active.values()].map(function identity(record) {
|
|
22486
|
+
return { threadId: record.threadId, turnId: record.turnId };
|
|
22487
|
+
});
|
|
22488
|
+
},
|
|
22489
|
+
isRunning: function isRunning() {
|
|
22490
|
+
return running;
|
|
22491
|
+
},
|
|
22492
|
+
reconcile: function converge() {
|
|
22493
|
+
return delivery.reconcile({ staleMs, activeMessageIds: activeMessageIds() });
|
|
22494
|
+
}
|
|
22495
|
+
};
|
|
22496
|
+
}
|
|
22497
|
+
|
|
22498
|
+
// src/node/desktop-status-protocol.ts
|
|
22499
|
+
var DESKTOP_STATUS_VERSION = 1;
|
|
22500
|
+
var DESKTOP_STATUS_FRAME_BYTES = 64 * 1024;
|
|
22501
|
+
var DESKTOP_STATUS_QUEUE_BYTES = 256 * 1024;
|
|
22502
|
+
function isDesktopStatusId(value) {
|
|
22503
|
+
return typeof value === "string" && /^[a-zA-Z0-9:_-]{1,160}$/.test(value);
|
|
22504
|
+
}
|
|
22505
|
+
function fields(value, required, optional = []) {
|
|
22506
|
+
return !!value && typeof value === "object" && !Array.isArray(value) && required.every(function present(key2) {
|
|
22507
|
+
return Object.prototype.hasOwnProperty.call(value, key2);
|
|
22508
|
+
}) && Object.keys(value).every(function allowed(key2) {
|
|
22509
|
+
return required.includes(key2) || optional.includes(key2);
|
|
22510
|
+
});
|
|
22511
|
+
}
|
|
22512
|
+
function optionalEnum(value, values) {
|
|
22513
|
+
return value === void 0 || typeof value === "string" && values.includes(value);
|
|
22514
|
+
}
|
|
22515
|
+
function isDesktopSessionStatus(value) {
|
|
22516
|
+
if (!fields(value, ["sessionId", "selected", "relation", "freshness", "status", "lastSeq"], ["turnId", "execution", "waiting", "result", "interaction", "continuation", "recoverable"])) return false;
|
|
22517
|
+
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");
|
|
22518
|
+
}
|
|
22519
|
+
function workspace(value) {
|
|
22520
|
+
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);
|
|
22521
|
+
}
|
|
22522
|
+
function isDesktopStatusFrame(value) {
|
|
22523
|
+
if (!value || typeof value !== "object") return false;
|
|
22524
|
+
const v = value;
|
|
22525
|
+
const common2 = ["protocolVersion", "desktopInstanceId", "paneId", "generation", "apInstanceId", "seq", "type"];
|
|
22526
|
+
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;
|
|
22527
|
+
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);
|
|
22528
|
+
if (v.type === "heartbeat" || v.type === "ap_exiting") return fields(v, common2);
|
|
22529
|
+
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);
|
|
22530
|
+
}
|
|
22531
|
+
function isDesktopStatusReply(value) {
|
|
22532
|
+
return fields(value, ["type", "seq"]) && ["accepted", "ack", "resync_required"].includes(value.type) && Number.isSafeInteger(value.seq) && value.seq >= 0;
|
|
22533
|
+
}
|
|
22534
|
+
var DesktopStatusLines = class {
|
|
22535
|
+
constructor() {
|
|
22536
|
+
this.pending = Buffer.alloc(0);
|
|
22537
|
+
}
|
|
22538
|
+
push(chunk) {
|
|
22539
|
+
const values = [];
|
|
22540
|
+
let offset = 0;
|
|
22541
|
+
while (offset < chunk.length) {
|
|
22542
|
+
const newline = chunk.indexOf(10, offset);
|
|
22543
|
+
const end = newline < 0 ? chunk.length : newline;
|
|
22544
|
+
if (this.pending.length + end - offset > DESKTOP_STATUS_FRAME_BYTES) throw new Error("STATUS_FRAME_INVALID");
|
|
22545
|
+
this.pending = Buffer.concat([this.pending, chunk.subarray(offset, end)]);
|
|
22546
|
+
if (newline < 0) break;
|
|
22547
|
+
const line = new TextDecoder("utf-8", { fatal: true }).decode(this.pending);
|
|
22548
|
+
this.pending = Buffer.alloc(0);
|
|
22549
|
+
values.push(JSON.parse(line));
|
|
22550
|
+
offset = newline + 1;
|
|
22551
|
+
}
|
|
22552
|
+
return values;
|
|
22553
|
+
}
|
|
22554
|
+
};
|
|
22555
|
+
|
|
22556
|
+
// src/node/thread-handoff.ts
|
|
22557
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
22558
|
+
import fs34 from "node:fs";
|
|
22559
|
+
import path26 from "node:path";
|
|
22560
|
+
var HANDOFF_DIRECTORY = ".autopilot";
|
|
22561
|
+
function assertWithinRoot(root, candidate) {
|
|
22562
|
+
const relative = path26.relative(root, candidate);
|
|
22563
|
+
if (!relative || relative.startsWith(`..${path26.sep}`) || relative === ".." || path26.isAbsolute(relative)) {
|
|
22564
|
+
throw new Error("THREAD_HANDOFF_WRITE_FAILED");
|
|
22565
|
+
}
|
|
22566
|
+
}
|
|
22567
|
+
function sha2562(content) {
|
|
22568
|
+
return createHash8("sha256").update(content, "utf8").digest("hex");
|
|
22569
|
+
}
|
|
22570
|
+
function createNodeThreadHandoffWriter(options) {
|
|
22571
|
+
const workspaceRoot = path26.resolve(options.workspaceRoot);
|
|
22572
|
+
function resolveTarget(handoffId) {
|
|
22573
|
+
if (!/^[0-9a-f]{16,64}$/.test(handoffId)) throw new Error("THREAD_HANDOFF_WRITE_FAILED");
|
|
22574
|
+
const realRoot = fs34.realpathSync(workspaceRoot);
|
|
22575
|
+
const directory = path26.resolve(realRoot, HANDOFF_DIRECTORY);
|
|
22576
|
+
assertWithinRoot(realRoot, directory);
|
|
22577
|
+
const filePath = path26.join(directory, `thread-passdown-${handoffId}.md`);
|
|
22578
|
+
assertWithinRoot(realRoot, filePath);
|
|
22579
|
+
return { directory, filePath };
|
|
22580
|
+
}
|
|
22581
|
+
async function write(input) {
|
|
22582
|
+
const { directory, filePath } = resolveTarget(input.handoffId);
|
|
22583
|
+
const content = `# Handoff\uFF1A${input.title}
|
|
22584
|
+
|
|
22585
|
+
${input.markdown}
|
|
22586
|
+
`;
|
|
22587
|
+
fs34.mkdirSync(directory, { recursive: true });
|
|
22588
|
+
const realDirectory = fs34.realpathSync(directory);
|
|
22589
|
+
assertWithinRoot(fs34.realpathSync(workspaceRoot), realDirectory);
|
|
22590
|
+
await withAsyncFileLock(filePath, function writeLocked() {
|
|
22591
|
+
if (fs34.existsSync(filePath)) {
|
|
22592
|
+
const existing = fs34.readFileSync(filePath, "utf8");
|
|
22593
|
+
if (existing !== content) throw new Error("THREAD_HANDOFF_CONFLICT");
|
|
22594
|
+
return;
|
|
22595
|
+
}
|
|
22596
|
+
atomicReplace(filePath, content);
|
|
22597
|
+
});
|
|
22598
|
+
const written = fs34.readFileSync(filePath, "utf8");
|
|
22599
|
+
if (written !== content) throw new Error("THREAD_HANDOFF_CONFLICT");
|
|
22600
|
+
return {
|
|
22601
|
+
handoffId: input.handoffId,
|
|
22602
|
+
relativePath: `${HANDOFF_DIRECTORY}/thread-passdown-${input.handoffId}.md`,
|
|
22603
|
+
sha256: sha2562(content)
|
|
22604
|
+
};
|
|
22605
|
+
}
|
|
22606
|
+
return { write };
|
|
22607
|
+
}
|
|
22608
|
+
|
|
22609
|
+
// src/node/host-identity.ts
|
|
22610
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
22611
|
+
var LOCAL_HUMAN_PRINCIPAL_ID = "web-local-user";
|
|
22612
|
+
function createNodeStateRootId(stateRoot) {
|
|
22613
|
+
return createHash9("sha256").update(stateRoot).digest("hex");
|
|
22614
|
+
}
|
|
21147
22615
|
export {
|
|
21148
22616
|
CHAT_ATTACHMENT_TTL_MS,
|
|
21149
22617
|
DEFAULT_COMPACT_TARGET_RATIO,
|
|
21150
22618
|
DEFAULT_COMPACT_TRIGGER_RATIO,
|
|
21151
22619
|
DEFAULT_CONTEXT_WINDOW_TOKENS,
|
|
22620
|
+
DESKTOP_STATUS_FRAME_BYTES,
|
|
22621
|
+
DESKTOP_STATUS_QUEUE_BYTES,
|
|
22622
|
+
DESKTOP_STATUS_VERSION,
|
|
22623
|
+
DesktopStatusLines,
|
|
22624
|
+
LOCAL_HUMAN_PRINCIPAL_ID,
|
|
21152
22625
|
NODE_CHAT_KNOWLEDGE_SPACE_ID,
|
|
21153
22626
|
NODE_STATE_SCHEMA_VERSION,
|
|
21154
22627
|
NODE_WORKSPACE_ID_VERSION,
|
|
@@ -21180,11 +22653,15 @@ export {
|
|
|
21180
22653
|
createNodeRagRuntime,
|
|
21181
22654
|
createNodeRuntimePorts,
|
|
21182
22655
|
createNodeSandboxPort,
|
|
22656
|
+
createNodeSessionImageStore,
|
|
21183
22657
|
createNodeSessionResourceStore,
|
|
21184
22658
|
createNodeSessionStore,
|
|
21185
22659
|
createNodeSettingsLoader,
|
|
21186
22660
|
createNodeSettingsWriter,
|
|
22661
|
+
createNodeStateRootId,
|
|
21187
22662
|
createNodeStateSchemaManager,
|
|
22663
|
+
createNodeThreadHandoffWriter,
|
|
22664
|
+
createNodeThreadRunner,
|
|
21188
22665
|
createNodeTranscriptStore,
|
|
21189
22666
|
createNodeTrustPolicy,
|
|
21190
22667
|
createNodeTrustStore,
|
|
@@ -21206,6 +22683,10 @@ export {
|
|
|
21206
22683
|
getNodeStatePaths,
|
|
21207
22684
|
getNodeStateSchemaDiagnostic,
|
|
21208
22685
|
initializeNodeStateRoot,
|
|
22686
|
+
isDesktopSessionStatus,
|
|
22687
|
+
isDesktopStatusFrame,
|
|
22688
|
+
isDesktopStatusId,
|
|
22689
|
+
isDesktopStatusReply,
|
|
21209
22690
|
isSafeSettingsFile,
|
|
21210
22691
|
loadMcpConfigFromWorkspace,
|
|
21211
22692
|
resolveNodeChatStatePaths,
|
|
@@ -21215,5 +22696,6 @@ export {
|
|
|
21215
22696
|
resolveNodeTrustRoot,
|
|
21216
22697
|
resolveNodeUserSettingsPath,
|
|
21217
22698
|
retrieveNodeMemories,
|
|
21218
|
-
serializePosixCommand
|
|
22699
|
+
serializePosixCommand,
|
|
22700
|
+
withNodeRuntimeOwner
|
|
21219
22701
|
};
|