@theokit/sdk 5.9.1 → 5.10.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/CHANGELOG.md +119 -0
- package/dist/{agent-enXXu447.d.ts → agent-CmKwSyyD.d.ts} +27 -0
- package/dist/{agent-5M7WLUWH.cjs → agent-TLRURB7W.cjs} +18 -16
- package/dist/{agent-5M7WLUWH.cjs.map → agent-TLRURB7W.cjs.map} +1 -1
- package/dist/{agent-Dh2YHSLj.d.cts → agent-XMkGzff_.d.cts} +27 -0
- package/dist/{agent-R5RERYFU.js → agent-XTLAVVYC.js} +17 -15
- package/dist/{agent-R5RERYFU.js.map → agent-XTLAVVYC.js.map} +1 -1
- package/dist/agent-session-store-ODD3IZCW.js +6 -0
- package/dist/{agent-session-store-AFML3AXC.js.map → agent-session-store-ODD3IZCW.js.map} +1 -1
- package/dist/agent-session-store-SVEJHSUA.cjs +23 -0
- package/dist/{agent-session-store-MTSIY3MH.cjs.map → agent-session-store-SVEJHSUA.cjs.map} +1 -1
- package/dist/auth/index.cjs +8 -7
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.js +3 -2
- package/dist/auth/index.js.map +1 -1
- package/dist/{chunk-QCIARBLS.js → chunk-523O5UYB.js} +3 -3
- package/dist/{chunk-QCIARBLS.js.map → chunk-523O5UYB.js.map} +1 -1
- package/dist/chunk-7KIN3L2S.js +103 -0
- package/dist/chunk-7KIN3L2S.js.map +1 -0
- package/dist/chunk-ASK2OQM5.cjs +84 -0
- package/dist/chunk-ASK2OQM5.cjs.map +1 -0
- package/dist/{chunk-56BCEM26.cjs → chunk-CVEQ5366.cjs} +105 -91
- package/dist/chunk-CVEQ5366.cjs.map +1 -0
- package/dist/{chunk-R2C3HXR3.js → chunk-DPY2M74T.js} +3 -3
- package/dist/{chunk-R2C3HXR3.js.map → chunk-DPY2M74T.js.map} +1 -1
- package/dist/chunk-EHD25JBZ.cjs +10 -0
- package/dist/chunk-EHD25JBZ.cjs.map +1 -0
- package/dist/{chunk-NOO6GZTZ.js → chunk-EVH3OUMY.js} +13 -12
- package/dist/chunk-EVH3OUMY.js.map +1 -0
- package/dist/{chunk-5522X223.js → chunk-EXI7EHDN.js} +4 -4
- package/dist/{chunk-5522X223.js.map → chunk-EXI7EHDN.js.map} +1 -1
- package/dist/{chunk-PSLCVSCS.cjs → chunk-FR6COQXZ.cjs} +6 -6
- package/dist/{chunk-PSLCVSCS.cjs.map → chunk-FR6COQXZ.cjs.map} +1 -1
- package/dist/{chunk-JOFVLOFY.js → chunk-FTZTZBCU.js} +12 -4
- package/dist/chunk-FTZTZBCU.js.map +1 -0
- package/dist/{chunk-T5KOSR5Y.cjs → chunk-FYEHYQ7T.cjs} +8 -8
- package/dist/{chunk-T5KOSR5Y.cjs.map → chunk-FYEHYQ7T.cjs.map} +1 -1
- package/dist/{chunk-HOHR75KF.js → chunk-HI3W37FY.js} +4 -3
- package/dist/chunk-HI3W37FY.js.map +1 -0
- package/dist/chunk-HU666T3Q.cjs +1891 -0
- package/dist/chunk-HU666T3Q.cjs.map +1 -0
- package/dist/{chunk-53RDNK3H.js → chunk-I2ORT6QD.js} +3 -3
- package/dist/{chunk-53RDNK3H.js.map → chunk-I2ORT6QD.js.map} +1 -1
- package/dist/{chunk-UNZOJVVC.js → chunk-IZDDSLL2.js} +5 -4
- package/dist/chunk-IZDDSLL2.js.map +1 -0
- package/dist/{chunk-TTBIQTO5.cjs → chunk-L3C6CCBG.cjs} +15 -15
- package/dist/{chunk-TTBIQTO5.cjs.map → chunk-L3C6CCBG.cjs.map} +1 -1
- package/dist/{chunk-B3XXQX6L.cjs → chunk-NQVWSSX2.cjs} +10 -9
- package/dist/chunk-NQVWSSX2.cjs.map +1 -0
- package/dist/{chunk-LL4QA3DI.cjs → chunk-PCLRIQPX.cjs} +4 -4
- package/dist/{chunk-LL4QA3DI.cjs.map → chunk-PCLRIQPX.cjs.map} +1 -1
- package/dist/chunk-Q7GYMXVC.js +8 -0
- package/dist/chunk-Q7GYMXVC.js.map +1 -0
- package/dist/{chunk-ARMFXTY6.cjs → chunk-QY3CIMUV.cjs} +34 -33
- package/dist/chunk-QY3CIMUV.cjs.map +1 -0
- package/dist/chunk-R5YPDAKD.cjs +108 -0
- package/dist/chunk-R5YPDAKD.cjs.map +1 -0
- package/dist/chunk-RGQICWFU.js +82 -0
- package/dist/chunk-RGQICWFU.js.map +1 -0
- package/dist/{chunk-OOM236Z4.js → chunk-RTE2DD4S.js} +32 -18
- package/dist/chunk-RTE2DD4S.js.map +1 -0
- package/dist/chunk-SGC7LSHF.cjs +18 -0
- package/dist/{chunk-R3ZQBPA5.cjs.map → chunk-SGC7LSHF.cjs.map} +1 -1
- package/dist/{chunk-RA7IE4NK.cjs → chunk-SKDNCTXG.cjs} +4 -3
- package/dist/chunk-SKDNCTXG.cjs.map +1 -0
- package/dist/chunk-SVCPJRUB.js +1874 -0
- package/dist/chunk-SVCPJRUB.js.map +1 -0
- package/dist/{chunk-EJROML3Q.js → chunk-TX56N7FR.js} +4 -3
- package/dist/chunk-TX56N7FR.js.map +1 -0
- package/dist/{chunk-QDQQYRJI.js → chunk-W2ZVTEOD.js} +3 -3
- package/dist/{chunk-QDQQYRJI.js.map → chunk-W2ZVTEOD.js.map} +1 -1
- package/dist/{chunk-TC4RWP3Y.js → chunk-X3LOJJMO.js} +89 -29
- package/dist/chunk-X3LOJJMO.js.map +1 -0
- package/dist/{chunk-2WXHA33T.js → chunk-XERM7PDQ.js} +3 -3
- package/dist/{chunk-2WXHA33T.js.map → chunk-XERM7PDQ.js.map} +1 -1
- package/dist/{chunk-MEUBLCM4.cjs → chunk-YEHQ3SIC.cjs} +4 -3
- package/dist/chunk-YEHQ3SIC.cjs.map +1 -0
- package/dist/{chunk-YIFFF23U.cjs → chunk-ZAM7BJXJ.cjs} +5 -5
- package/dist/{chunk-YIFFF23U.cjs.map → chunk-ZAM7BJXJ.cjs.map} +1 -1
- package/dist/{chunk-76PIKR4P.cjs → chunk-ZD66GFH5.cjs} +91 -29
- package/dist/chunk-ZD66GFH5.cjs.map +1 -0
- package/dist/{chunk-GZV6AVRL.cjs → chunk-ZWACQM5U.cjs} +11 -3
- package/dist/chunk-ZWACQM5U.cjs.map +1 -0
- package/dist/{compact-session-RBPLUPCK.cjs → compact-session-4QHBBGEY.cjs} +16 -15
- package/dist/{compact-session-RBPLUPCK.cjs.map → compact-session-4QHBBGEY.cjs.map} +1 -1
- package/dist/{compact-session-2N3ZYJTW.js → compact-session-PVAWTKKL.js} +7 -6
- package/dist/{compact-session-2N3ZYJTW.js.map → compact-session-PVAWTKKL.js.map} +1 -1
- package/dist/{cron-DTuaPMVI.d.ts → cron-BPccQCO8.d.ts} +1 -1
- package/dist/{cron-QTgcwcZt.d.cts → cron-Blj6wMYg.d.cts} +1 -1
- package/dist/cron.cjs +17 -15
- package/dist/cron.d.cts +2 -2
- package/dist/cron.d.ts +2 -2
- package/dist/cron.js +16 -14
- package/dist/eval.cjs +20 -18
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +16 -14
- package/dist/eval.js.map +1 -1
- package/dist/fs-session-store-3VI4CPTX.js +11 -0
- package/dist/{fs-session-store-STZZFXH2.js.map → fs-session-store-3VI4CPTX.js.map} +1 -1
- package/dist/fs-session-store-IQ6PEHYF.cjs +20 -0
- package/dist/{fs-session-store-JHBJFKVV.cjs.map → fs-session-store-IQ6PEHYF.cjs.map} +1 -1
- package/dist/{index-manager-ONQJSWX5.js → index-manager-JVYIVTZG.js} +6 -5
- package/dist/{index-manager-ONQJSWX5.js.map → index-manager-JVYIVTZG.js.map} +1 -1
- package/dist/{index-manager-ZGJN25FD.cjs → index-manager-YGXRFJMZ.cjs} +7 -6
- package/dist/{index-manager-ZGJN25FD.cjs.map → index-manager-YGXRFJMZ.cjs.map} +1 -1
- package/dist/index.cjs +68 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +42 -6
- package/dist/index.d.ts +42 -6
- package/dist/index.js +31 -23
- package/dist/index.js.map +1 -1
- package/dist/{inject-session-YNNOE3O6.js → inject-session-O24XGRR6.js} +5 -5
- package/dist/{inject-session-YNNOE3O6.js.map → inject-session-O24XGRR6.js.map} +1 -1
- package/dist/{inject-session-3FPXJDJP.cjs → inject-session-OMLFL2V3.cjs} +7 -7
- package/dist/{inject-session-3FPXJDJP.cjs.map → inject-session-OMLFL2V3.cjs.map} +1 -1
- package/dist/internal/memory/adapters/index.cjs +3 -2
- package/dist/internal/memory/adapters/index.js +2 -1
- package/dist/internal/memory/dreaming/phases.d.ts +2 -0
- package/dist/internal/memory/dreaming/run.d.ts +5 -0
- package/dist/internal/memory/sdk-memory-peer-loader.d.ts +2 -0
- package/dist/internal/memory/storage/fact-ceiling.d.cts +19 -0
- package/dist/internal/memory/storage/fact-ceiling.d.ts +19 -0
- package/dist/internal/memory/storage/index.cjs +41 -32
- package/dist/internal/memory/storage/index.d.cts +1 -0
- package/dist/internal/memory/storage/index.d.ts +1 -0
- package/dist/internal/memory/storage/index.js +4 -3
- package/dist/internal/memory/storage/markdown-store.d.cts +3 -1
- package/dist/internal/memory/storage/markdown-store.d.ts +3 -1
- package/dist/internal/memory/types.d.ts +6 -0
- package/dist/internal/persistence/index.cjs +7 -6
- package/dist/internal/persistence/index.cjs.map +1 -1
- package/dist/internal/persistence/index.js +2 -1
- package/dist/internal/persistence/index.js.map +1 -1
- package/dist/internal/persistence/persistence-schema.d.cts +1 -1
- package/dist/internal/persistence/persistence-schema.d.ts +1 -1
- package/dist/internal/providers/catalog-loader.d.ts +30 -3
- package/dist/internal/runtime/registry/agent-registry-store.d.ts +2 -0
- package/dist/internal/runtime-fetch.d.ts +1 -0
- package/dist/models.cjs +12 -11
- package/dist/models.cjs.map +1 -1
- package/dist/models.js +4 -3
- package/dist/models.js.map +1 -1
- package/dist/persistence.cjs +14 -13
- package/dist/persistence.cjs.map +1 -1
- package/dist/persistence.js +4 -3
- package/dist/persistence.js.map +1 -1
- package/dist/providers.cjs +6 -5
- package/dist/providers.js +4 -3
- package/dist/{session-transcript-VTBTCGQX.js → session-transcript-AR7IBICT.js} +3 -3
- package/dist/{session-transcript-VTBTCGQX.js.map → session-transcript-AR7IBICT.js.map} +1 -1
- package/dist/{session-transcript-LGHSNVY5.cjs → session-transcript-RACG7BK2.cjs} +16 -16
- package/dist/{session-transcript-LGHSNVY5.cjs.map → session-transcript-RACG7BK2.cjs.map} +1 -1
- package/dist/subagents-loader.d.cts +1 -1
- package/dist/subagents-loader.d.ts +1 -1
- package/dist/subscription/index.cjs +2 -1
- package/dist/subscription/index.cjs.map +1 -1
- package/dist/subscription/index.js +2 -1
- package/dist/subscription/index.js.map +1 -1
- package/dist/types/agent.d.ts +27 -0
- package/docs/error-codes.md +40 -38
- package/docs/harness-capability-map.md +6 -1
- package/package.json +2 -2
- package/dist/agent-session-store-AFML3AXC.js +0 -6
- package/dist/agent-session-store-MTSIY3MH.cjs +0 -23
- package/dist/chunk-56BCEM26.cjs.map +0 -1
- package/dist/chunk-76PIKR4P.cjs.map +0 -1
- package/dist/chunk-ARMFXTY6.cjs.map +0 -1
- package/dist/chunk-B3XXQX6L.cjs.map +0 -1
- package/dist/chunk-BKMDRBJ7.js +0 -180
- package/dist/chunk-BKMDRBJ7.js.map +0 -1
- package/dist/chunk-EJROML3Q.js.map +0 -1
- package/dist/chunk-GZV6AVRL.cjs.map +0 -1
- package/dist/chunk-HOHR75KF.js.map +0 -1
- package/dist/chunk-JOFVLOFY.js.map +0 -1
- package/dist/chunk-MEUBLCM4.cjs.map +0 -1
- package/dist/chunk-MFZODA5Y.js +0 -583
- package/dist/chunk-MFZODA5Y.js.map +0 -1
- package/dist/chunk-NOO6GZTZ.js.map +0 -1
- package/dist/chunk-OF2CLCTH.cjs +0 -186
- package/dist/chunk-OF2CLCTH.cjs.map +0 -1
- package/dist/chunk-OOM236Z4.js.map +0 -1
- package/dist/chunk-R3ZQBPA5.cjs +0 -18
- package/dist/chunk-RA7IE4NK.cjs.map +0 -1
- package/dist/chunk-TC4RWP3Y.js.map +0 -1
- package/dist/chunk-UNZOJVVC.js.map +0 -1
- package/dist/chunk-YRJA2POB.cjs +0 -601
- package/dist/chunk-YRJA2POB.cjs.map +0 -1
- package/dist/fs-session-store-JHBJFKVV.cjs +0 -19
- package/dist/fs-session-store-STZZFXH2.js +0 -10
- package/dist/provider-catalog.json +0 -1295
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunkUNFBHV46_cjs = require('./chunk-UNFBHV46.cjs');
|
|
4
|
+
var fs = require('fs');
|
|
5
|
+
var path = require('path');
|
|
6
|
+
|
|
7
|
+
var JsonlParseError = class extends chunkUNFBHV46_cjs.TheokitAgentError {
|
|
8
|
+
constructor(message, line) {
|
|
9
|
+
super(message, { code: "jsonl_parse_failed", isRetryable: false });
|
|
10
|
+
this.line = line;
|
|
11
|
+
}
|
|
12
|
+
line;
|
|
13
|
+
name = "JsonlParseError";
|
|
14
|
+
};
|
|
15
|
+
function isPlainObject(value) {
|
|
16
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
function tryParseObjectLine(line) {
|
|
19
|
+
if (line.length === 0) return void 0;
|
|
20
|
+
let parsed;
|
|
21
|
+
try {
|
|
22
|
+
parsed = JSON.parse(line);
|
|
23
|
+
} catch {
|
|
24
|
+
return void 0;
|
|
25
|
+
}
|
|
26
|
+
return isPlainObject(parsed) ? parsed : void 0;
|
|
27
|
+
}
|
|
28
|
+
function loadJsonl(path, opts = {}) {
|
|
29
|
+
const lines = fs.readFileSync(path, "utf8").split("\n");
|
|
30
|
+
const out = [];
|
|
31
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
32
|
+
const lineNumber = i + 1;
|
|
33
|
+
const line = (lines[i] ?? "").trim();
|
|
34
|
+
if (line.length === 0) continue;
|
|
35
|
+
const parsed = parseLine(
|
|
36
|
+
line,
|
|
37
|
+
lineNumber,
|
|
38
|
+
opts.tolerateTrailingPartialLine === true && lineNumber === lines.length
|
|
39
|
+
);
|
|
40
|
+
if (parsed === void 0) break;
|
|
41
|
+
out.push(opts.map ? opts.map(parsed, lineNumber) : parsed);
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
function parseLine(line, lineNumber, tolerate) {
|
|
46
|
+
let parsed;
|
|
47
|
+
try {
|
|
48
|
+
parsed = JSON.parse(line);
|
|
49
|
+
} catch {
|
|
50
|
+
if (tolerate) return void 0;
|
|
51
|
+
throw new JsonlParseError(`line ${lineNumber}: invalid JSON`, lineNumber);
|
|
52
|
+
}
|
|
53
|
+
if (!isPlainObject(parsed)) {
|
|
54
|
+
throw new JsonlParseError(`line ${lineNumber}: not a JSON object`, lineNumber);
|
|
55
|
+
}
|
|
56
|
+
return parsed;
|
|
57
|
+
}
|
|
58
|
+
function appendJsonl(path$1, record) {
|
|
59
|
+
fs.mkdirSync(path.dirname(path$1), { recursive: true, mode: 448 });
|
|
60
|
+
const prefix = needsLineBreakBefore(path$1) ? "\n" : "";
|
|
61
|
+
const fd = fs.openSync(path$1, "a", 384);
|
|
62
|
+
try {
|
|
63
|
+
fs.writeSync(fd, `${prefix}${JSON.stringify(record)}
|
|
64
|
+
`);
|
|
65
|
+
} finally {
|
|
66
|
+
fs.closeSync(fd);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function needsLineBreakBefore(path) {
|
|
70
|
+
let fd;
|
|
71
|
+
try {
|
|
72
|
+
fd = fs.openSync(path, "r");
|
|
73
|
+
} catch {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
const size = fs.fstatSync(fd).size;
|
|
78
|
+
if (size === 0) return false;
|
|
79
|
+
const buf = Buffer.alloc(1);
|
|
80
|
+
fs.readSync(fd, buf, 0, 1, size - 1);
|
|
81
|
+
return buf[0] !== 10;
|
|
82
|
+
} finally {
|
|
83
|
+
fs.closeSync(fd);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function readJsonlIds(path, keyFn) {
|
|
87
|
+
const done = /* @__PURE__ */ new Set();
|
|
88
|
+
let text;
|
|
89
|
+
try {
|
|
90
|
+
text = fs.readFileSync(path, "utf8");
|
|
91
|
+
} catch {
|
|
92
|
+
return done;
|
|
93
|
+
}
|
|
94
|
+
for (const rawLine of text.split("\n")) {
|
|
95
|
+
const parsed = tryParseObjectLine(rawLine.trim());
|
|
96
|
+
if (parsed === void 0) continue;
|
|
97
|
+
const key = keyFn(parsed);
|
|
98
|
+
if (typeof key === "string" && key.length > 0) done.add(key);
|
|
99
|
+
}
|
|
100
|
+
return done;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
exports.JsonlParseError = JsonlParseError;
|
|
104
|
+
exports.appendJsonl = appendJsonl;
|
|
105
|
+
exports.loadJsonl = loadJsonl;
|
|
106
|
+
exports.readJsonlIds = readJsonlIds;
|
|
107
|
+
//# sourceMappingURL=chunk-R5YPDAKD.cjs.map
|
|
108
|
+
//# sourceMappingURL=chunk-R5YPDAKD.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/jsonl.ts"],"names":["TheokitAgentError","readFileSync","path","mkdirSync","dirname","openSync","writeSync","closeSync","fstatSync","readSync"],"mappings":";;;;;;AA6BO,IAAM,eAAA,GAAN,cAA8BA,mCAAA,CAAkB;AAAA,EAErD,WAAA,CACE,SACS,IAAA,EACT;AAEA,IAAA,KAAA,CAAM,SAAS,EAAE,IAAA,EAAM,oBAAA,EAAsB,WAAA,EAAa,OAAO,CAAA;AAHxD,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAIX;AAAA,EAJW,IAAA;AAAA,EAHO,IAAA,GAAO,iBAAA;AAQ3B;AAEA,SAAS,cAAc,KAAA,EAAkD;AACvE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E;AAGA,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,MAAM,GAAA,GAAM,MAAA,CAAO,KAAA,CAAM,CAAC,CAAA;AAC1B,IAAAC,WAAA,CAAS,EAAA,EAAI,GAAA,EAAK,CAAA,EAAG,CAAA,EAAG,OAAO,CAAC,CAAA;AAChC,IAAA,OAAO,GAAA,CAAI,CAAC,CAAA,KAAM,EAAA;AAAA,EACpB,CAAA,SAAE;AACA,IAAAF,YAAA,CAAU,EAAE,CAAA;AAAA,EACd;AACF;AAYO,SAAS,YAAA,CACd,MACA,KAAA,EACa;AACb,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,IAAI,IAAA;AACJ,EAAA,IAAI;AACF,IAAA,IAAA,GAAON,eAAA,CAAa,MAAM,MAAM,CAAA;AAAA,EAClC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,KAAA,MAAW,OAAA,IAAW,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA,EAAG;AAEtC,IAAA,MAAM,MAAA,GAAS,kBAAA,CAAmB,OAAA,CAAQ,IAAA,EAAM,CAAA;AAChD,IAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,IAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,IAAA,IAAI,OAAO,QAAQ,QAAA,IAAY,GAAA,CAAI,SAAS,CAAA,EAAG,IAAA,CAAK,IAAI,GAAG,CAAA;AAAA,EAC7D;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-R5YPDAKD.cjs","sourcesContent":["/**\n * Durable JSONL primitives shared by the eval harness (M6).\n *\n * - `loadJsonl` — generic dataset reader (split/trim/skip-blank/parse) with a\n * line-numbered {@link JsonlParseError}. The dataset SCHEMA is the caller's\n * concern via `map` (M6 ADR D3) — this module owns only the parse.\n * - `appendJsonl` / `readJsonlIds` — crash-durable, resumable batch persistence\n * (M6 ADR D1): each record is appended as one whole `\\n`-terminated line the\n * instant it is produced, and a re-run resumes by skipping already-keyed rows.\n *\n * reference: knowledge-base/references/theocode-eval/lib/swebench-dataset.ts:82\n * (parseJsonl + line-N error) and swebench-batch.ts:113,205 (resume + per-line\n * flush).\n *\n * @internal\n */\nimport {\n closeSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/** Raised when a JSONL line is not valid JSON or is not a JSON object. Carries the 1-based line number. */\nexport class JsonlParseError extends TheokitAgentError {\n override readonly name = \"JsonlParseError\";\n constructor(\n message: string,\n readonly line: number,\n ) {\n // Not retryable: the bytes on the line do not change between reads.\n super(message, { code: \"jsonl_parse_failed\", isRetryable: false });\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Parse a single trimmed line to a plain object, or `undefined` if blank / invalid / non-object. */\nfunction tryParseObjectLine(line: string): Record<string, unknown> | undefined {\n if (line.length === 0) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return undefined;\n }\n return isPlainObject(parsed) ? parsed : undefined;\n}\n\n/**\n * Parse a JSONL file into rows. Blank lines are skipped. A malformed or\n * non-object line throws {@link JsonlParseError} naming the 1-based line. When\n * `map` is provided, each raw object is mapped to the typed row (the SWE-bench\n * schema lives in the caller's `map`, per M6 ADR D3).\n */\nexport function loadJsonl<T = Record<string, unknown>>(\n path: string,\n opts: {\n map?: (raw: Record<string, unknown>, lineNumber: number) => T;\n /**\n * M81 — tolerate a truncated LAST line (a crash artifact: the process died mid-write).\n *\n * Opt-in on purpose. As a default it would also swallow corruption in the MIDDLE of the file,\n * turning loud data loss into silent data loss — the wrong trade for a session store.\n */\n tolerateTrailingPartialLine?: boolean;\n } = {},\n): T[] {\n const lines = readFileSync(path, \"utf8\").split(\"\\n\");\n const out: T[] = [];\n for (let i = 0; i < lines.length; i += 1) {\n const lineNumber = i + 1;\n const line = (lines[i] ?? \"\").trim();\n if (line.length === 0) continue;\n // M81 — `undefined` = a tolerated invalid line (the last one, truncated by a crash). Any other\n // invalid line has already thrown inside `parseLine`.\n const parsed = parseLine(\n line,\n lineNumber,\n opts.tolerateTrailingPartialLine === true && lineNumber === lines.length,\n );\n if (parsed === undefined) break;\n out.push(opts.map ? opts.map(parsed, lineNumber) : (parsed as unknown as T));\n }\n return out;\n}\n\n/**\n * Parses ONE line, returning `undefined` when it is a tolerated truncated last line.\n *\n * Extracted because `loadJsonl` went over the cognitive-complexity ceiling once it gained the\n * tolerance — and because parsing a line and iterating a file are two responsibilities that were\n * only together out of habit.\n */\nfunction parseLine(\n line: string,\n lineNumber: number,\n tolerate: boolean,\n): Record<string, unknown> | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n if (tolerate) return undefined;\n throw new JsonlParseError(`line ${lineNumber}: invalid JSON`, lineNumber);\n }\n if (!isPlainObject(parsed)) {\n throw new JsonlParseError(`line ${lineNumber}: not a JSON object`, lineNumber);\n }\n return parsed;\n}\n\n/**\n * Append one record as a whole `\\n`-terminated JSON line. Creates the parent dir\n * if missing. `appendFileSync` is synchronous, so within a single Node process\n * the event loop serializes writes and each call writes its line atomically —\n * interleave-safe for the bounded-concurrency batch runner.\n *\n * reference: swebench-batch.ts:192 (mkdir-before-append), :205 (per-line flush).\n */\nexport function appendJsonl(path: string, record: unknown): void {\n // T2.4 — `0o700` for the same reason the file below is `0o600`, and it is the half M93 missed. A\n // private file inside a group-writable directory can be replaced wholesale, and the replacement's\n // mode is whatever the writer chose. Under `umask 002` this directory was born `0775`.\n //\n // The directory sits under `~/.theokit`, shared with the credential and trust stores, and the\n // framework already wrote the diagnosis while fixing a sibling (`@theokit/agents\n // config/trust-store.ts:157-161`): the mode argument is a no-op on a directory that already\n // exists, \"and this one is shared with the SDK's transcript root — whoever creates it first sets\n // the permissions\". Whoever creates it first is usually THIS function, because a session writes a\n // transcript before it ever touches a credential. So `assertSecureModes` was not wrong to demand a\n // private directory; this path was wrong to produce one that fails it, depending on run order.\n //\n // Creation-time only, deliberately: repairing a pre-existing directory means `stat` + `chmod` on\n // every append, and this is the hot path of every session. The pre-existing case is what\n // `assertSecureModes` is for.\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n const prefix = needsLineBreakBefore(path) ? \"\\n\" : \"\";\n // M93 (adversarial review, H1) — `0o600`. `appendFileSync` takes no `mode`, so the permission came\n // from the umask: under `umask 022` the transcript was born `0664`, world-readable. The previous\n // path (`replaceFileAtomic`) pinned `0o600` on purpose — \"holds the FULL in-flight content\n // (credential snapshots, OAuth tokens)\" (`atomic-write.ts:107`) — and switching to append lost\n // that silently. The same class had already been caught in the consumer (`atomic-sync.ts`, M88\n // HIGH-1).\n //\n // `mode` only applies on CREATION; a pre-existing file keeps whatever permission it already has.\n const fd = openSync(path, \"a\", 0o600);\n try {\n writeSync(fd, `${prefix}${JSON.stringify(record)}\\n`);\n } finally {\n closeSync(fd);\n }\n}\n\n/**\n * Does the file end without a `\\n`? Then the last line is truncated — a crash mid-append.\n *\n * Without this check the next append **glues** itself onto the middle of the broken line, producing\n * an invalid line the reader discards: the NEW record disappears along with the partial one. The\n * previous path (read-modify-write) self-healed from this because it rewrote the whole file.\n * Measured in M93's adversarial review (H2): after an append over a truncated file, the\n * just-written record was no longer readable.\n *\n * Reads **one byte**, not the file.\n */\nfunction needsLineBreakBefore(path: string): boolean {\n let fd: number;\n try {\n fd = openSync(path, \"r\");\n } catch {\n return false; // the file does not exist yet: nothing to splice onto\n }\n try {\n const size = fstatSync(fd).size;\n if (size === 0) return false;\n const buf = Buffer.alloc(1);\n readSync(fd, buf, 0, 1, size - 1);\n return buf[0] !== 0x0a;\n } finally {\n closeSync(fd);\n }\n}\n\n/**\n * Read the set of keys from an existing JSONL file for which `keyFn(parsed)`\n * returns a non-empty string. Used to resume a crashed batch by skipping rows\n * already persisted with a successful result. A trailing partial line from an\n * interrupted append is tolerated (skipped, not thrown), and a missing file\n * yields an empty set.\n *\n * reference: swebench-batch.ts:113 (readDoneIds), :129 (success-only),\n * :131 (tolerate partial line).\n */\nexport function readJsonlIds(\n path: string,\n keyFn: (parsed: Record<string, unknown>) => string | undefined,\n): Set<string> {\n const done = new Set<string>();\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch {\n return done; // no file yet → nothing done\n }\n for (const rawLine of text.split(\"\\n\")) {\n // A trailing partial line from an interrupted run parses to undefined → skipped.\n const parsed = tryParseObjectLine(rawLine.trim());\n if (parsed === undefined) continue;\n const key = keyFn(parsed);\n if (typeof key === \"string\" && key.length > 0) done.add(key);\n }\n return done;\n}\n"]}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { withCwdMutex } from './chunk-Q5EWJPRY.js';
|
|
2
|
+
import { diag } from './chunk-CZJ6Q7CW.js';
|
|
3
|
+
|
|
4
|
+
// src/internal/persistence/file-lock.ts
|
|
5
|
+
var cached;
|
|
6
|
+
var warnedMissing = false;
|
|
7
|
+
var warnedStructural = false;
|
|
8
|
+
var loadFailure;
|
|
9
|
+
function isModuleAbsent(err) {
|
|
10
|
+
const code = err?.code;
|
|
11
|
+
return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
|
|
12
|
+
}
|
|
13
|
+
function describeLockLoadFailure(err) {
|
|
14
|
+
const consequence = "cross-process file lock unavailable \u2014 concurrent processes over the same file are NOT serialized.";
|
|
15
|
+
if (isModuleAbsent(err)) {
|
|
16
|
+
return `[theokit-sdk] proper-lockfile not installed; ${consequence} Install with: pnpm add proper-lockfile
|
|
17
|
+
`;
|
|
18
|
+
}
|
|
19
|
+
const code = err?.code;
|
|
20
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
21
|
+
return `[theokit-sdk] proper-lockfile could not be loaded${code !== void 0 ? ` (${String(code)})` : ""}: ${detail}. ${consequence} The package resolves for the SDK but failed to load \u2014 check bundling and module-format interop before re-checking the install.
|
|
22
|
+
`;
|
|
23
|
+
}
|
|
24
|
+
async function getProperLockfile() {
|
|
25
|
+
if (cached !== void 0) return cached;
|
|
26
|
+
try {
|
|
27
|
+
const mod = await import('proper-lockfile');
|
|
28
|
+
if (!validateLockModule(mod)) {
|
|
29
|
+
if (!warnedStructural) {
|
|
30
|
+
warnedStructural = true;
|
|
31
|
+
diag(
|
|
32
|
+
"[theokit-sdk] proper-lockfile: imported module does NOT expose the expected `lock`/`unlock` API surface. This may indicate a supply-chain compromise or an incompatible major version. Falling back to in-process mutex (no cross-process safety). Reinstall with: pnpm add proper-lockfile@^11\n"
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
cached = null;
|
|
36
|
+
return cached;
|
|
37
|
+
}
|
|
38
|
+
cached = mod;
|
|
39
|
+
} catch (err) {
|
|
40
|
+
loadFailure = err;
|
|
41
|
+
cached = null;
|
|
42
|
+
}
|
|
43
|
+
return cached;
|
|
44
|
+
}
|
|
45
|
+
function validateLockModule(mod) {
|
|
46
|
+
if (mod === null || mod === void 0 || typeof mod !== "object") return false;
|
|
47
|
+
const m = mod;
|
|
48
|
+
return typeof m.lock === "function" && typeof m.unlock === "function";
|
|
49
|
+
}
|
|
50
|
+
async function withFileLock(path, fn, options) {
|
|
51
|
+
const lib = await getProperLockfile();
|
|
52
|
+
if (lib === null) {
|
|
53
|
+
if (!warnedMissing && !warnedStructural) {
|
|
54
|
+
warnedMissing = true;
|
|
55
|
+
diag(describeLockLoadFailure(loadFailure));
|
|
56
|
+
}
|
|
57
|
+
return withCwdMutex(`file-lock:${path}`, fn);
|
|
58
|
+
}
|
|
59
|
+
return withCwdMutex(`file-lock:${path}`, async () => {
|
|
60
|
+
const release = await lib.lock(path, {
|
|
61
|
+
// EC-1: companion lockfile, target path may not exist yet.
|
|
62
|
+
lockfilePath: `${path}.lock`,
|
|
63
|
+
realpath: false,
|
|
64
|
+
stale: options?.stale ?? 3e4,
|
|
65
|
+
retries: {
|
|
66
|
+
retries: options?.retries ?? 5,
|
|
67
|
+
factor: options?.retryFactor ?? 1.5,
|
|
68
|
+
minTimeout: 100,
|
|
69
|
+
maxTimeout: 5e3
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
try {
|
|
73
|
+
return await fn();
|
|
74
|
+
} finally {
|
|
75
|
+
await release();
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export { withFileLock };
|
|
81
|
+
//# sourceMappingURL=chunk-RGQICWFU.js.map
|
|
82
|
+
//# sourceMappingURL=chunk-RGQICWFU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/file-lock.ts"],"names":[],"mappings":";;;;AAiCA,IAAI,MAAA;AACJ,IAAI,aAAA,GAAgB,KAAA;AACpB,IAAI,gBAAA,GAAmB,KAAA;AAEvB,IAAI,WAAA;AAGJ,SAAS,eAAe,GAAA,EAAuB;AAC7C,EAAA,MAAM,OAAQ,GAAA,EAA+C,IAAA;AAC7D,EAAA,OAAO,IAAA,KAAS,0BAA0B,IAAA,KAAS,kBAAA;AACrD;AAgBA,SAAS,wBAAwB,GAAA,EAAsB;AACrD,EAAA,MAAM,WAAA,GACJ,wGAAA;AACF,EAAA,IAAI,cAAA,CAAe,GAAG,CAAA,EAAG;AACvB,IAAA,OAAO,gDAAgD,WAAW,CAAA;AAAA,CAAA;AAAA,EACpE;AACA,EAAA,MAAM,OAAQ,GAAA,EAA+C,IAAA;AAC7D,EAAA,MAAM,SAAS,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC9D,EAAA,OACE,CAAA,iDAAA,EAAoD,IAAA,KAAS,MAAA,GAAY,CAAA,EAAA,EAAK,MAAA,CAAO,IAAI,CAAC,CAAA,CAAA,CAAA,GAAM,EAAE,CAAA,EAAA,EAC/F,MAAM,CAAA,EAAA,EAAK,WAAW,CAAA;AAAA,CAAA;AAG7B;AAOA,eAAe,iBAAA,GAA0D;AACvE,EAAA,IAAI,MAAA,KAAW,Q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Y;AACnD,IAAA,MAAM,OAAA,GAAU,MAAM,GAAA,CAAI,IAAA,CAAK,IAAA,EAAM;AAAA;AAAA,MAEnC,YAAA,EAAc,GAAG,IAAI,CAAA,KAAA,CAAA;AAAA,MACrB,QAAA,EAAU,KAAA;AAAA,MACV,KAAA,EAAO,SAAS,KAAA,IAAS,GAAA;AAAA,MACzB,OAAA,EAAS;AAAA,QACP,OAAA,EAAS,SAAS,OAAA,IAAW,CAAA;AAAA,QAC7B,MAAA,EAAQ,SAAS,WAAA,IAAe,GAAA;AAAA,QAChC,UAAA,EAAY,GAAA;AAAA,QACZ,UAAA,EAAY;AAAA;AACd,KACD,CAAA;AAED,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,EAAA,EAAG;AAAA,IAClB,CAAA,SAAE;AACA,MAAA,MAAM,OAAA,EAAQ;AAAA,IAChB;AAAA,EACF,CAAC,CAAA;AACH","file":"chunk-RGQICWFU.js","sourcesContent":["/**\n * Cross-process file lock helper (ADR D61).\n *\n * Uses `proper-lockfile` (optional peer dep) for cross-process locks. When\n * the peer dep is absent, falls back to `withCwdMutex` (in-process only)\n * with a one-shot stderr warning.\n *\n * EC-1 fix: uses a companion `<path>.lock` file with `realpath: false` so\n * `withFileLock` works even when the target `path` does not exist yet.\n * Without this, fresh installs that lock-then-create would crash with ENOENT.\n *\n * @internal\n */\n\nimport { diag } from \"../diagnostics.js\";\nimport { withCwdMutex } from \"./cwd-mutex.js\";\n\ninterface ProperLockfileModule {\n lock: (file: string, options: ProperLockfileOptions) => Promise<() => Promise<void>>;\n}\n\ninterface ProperLockfileOptions {\n lockfilePath?: string;\n realpath?: boolean;\n stale?: number;\n retries?: {\n retries: number;\n factor?: number;\n minTimeout?: number;\n maxTimeout?: number;\n };\n}\n\nlet cached: ProperLockfileModule | null | undefined;\nlet warnedMissing = false;\nlet warnedStructural = false;\n/** Why the import failed, kept so the warning can report the observation instead of a guess (#174). */\nlet loadFailure: unknown;\n\n/** Node reports a missing module as `ERR_MODULE_NOT_FOUND` (ESM loader) or `MODULE_NOT_FOUND` (CJS). */\nfunction isModuleAbsent(err: unknown): boolean {\n const code = (err as { code?: unknown } | null | undefined)?.code;\n return code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\";\n}\n\n/**\n * #174 — build the fallback warning from what actually happened.\n *\n * This used to always read \"proper-lockfile not installed\", because the import was wrapped in a\n * bare `catch` that discarded the error (Unbreakable Rule 8: a swallowed error is the dangerous\n * kind). A consumer whose package WAS installed, declared and resolvable spent a debugging session\n * re-verifying the install, because the message named a cause the code had never checked.\n *\n * Absence is now the only case that claims absence. Every other failure — a broken install, an\n * interop problem, a bundler that rewrote the specifier — reports its own code and message, which\n * is what points at the real cause.\n *\n * @internal\n */\nfunction describeLockLoadFailure(err: unknown): string {\n const consequence =\n \"cross-process file lock unavailable — concurrent processes over the same file are NOT serialized.\";\n if (isModuleAbsent(err)) {\n return `[theokit-sdk] proper-lockfile not installed; ${consequence} Install with: pnpm add proper-lockfile\\n`;\n }\n const code = (err as { code?: unknown } | null | undefined)?.code;\n const detail = err instanceof Error ? err.message : String(err);\n return (\n `[theokit-sdk] proper-lockfile could not be loaded${code !== undefined ? ` (${String(code)})` : \"\"}: ` +\n `${detail}. ${consequence} The package resolves for the SDK but failed to load — check bundling ` +\n \"and module-format interop before re-checking the install.\\n\"\n );\n}\n\n/** Test seam for the message builder — NOT in the public barrel. @internal */\nexport function __TESTING__describeLockLoadFailure(err: unknown): string {\n return describeLockLoadFailure(err);\n}\n\nasync function getProperLockfile(): Promise<ProperLockfileModule | null> {\n if (cached !== undefined) return cached;\n try {\n const mod = await import(\"proper-lockfile\");\n // T5.9 — supply-chain hardening: validate the imported module\n // exposes the API surface we depend on BEFORE caching it. A\n // tampered or incompatible version that lacks `lock`/`unlock`\n // functions gets treated as \"not installed\" with an advisory\n // warning — never silently used.\n if (!validateLockModule(mod)) {\n if (!warnedStructural) {\n warnedStructural = true;\n diag(\n \"[theokit-sdk] proper-lockfile: imported module does NOT expose \" +\n \"the expected `lock`/`unlock` API surface. This may indicate a \" +\n \"supply-chain compromise or an incompatible major version. \" +\n \"Falling back to in-process mutex (no cross-process safety). \" +\n \"Reinstall with: pnpm add proper-lockfile@^11\\n\",\n );\n }\n cached = null;\n return cached;\n }\n cached = mod as ProperLockfileModule;\n } catch (err) {\n // #174 — keep WHY. Discarding it here is what made the fallback warning assert a cause it had\n // never observed, and sent a consumer to re-check an install that was already correct.\n loadFailure = err;\n cached = null;\n }\n return cached;\n}\n\n/**\n * T5.9 — Structural validation of the dynamically-imported\n * `proper-lockfile` module. Verifies the API surface we depend on\n * (`lock` and `unlock` as functions) is present. Pure function —\n * never throws, never mutates, never performs I/O.\n *\n * Exported via `__TESTING__validateLockModule` seam so unit tests\n * can drive the check without spinning up the dynamic import.\n *\n * @internal\n */\nfunction validateLockModule(mod: unknown): boolean {\n if (mod === null || mod === undefined || typeof mod !== \"object\") return false;\n const m = mod as Record<string, unknown>;\n return typeof m.lock === \"function\" && typeof m.unlock === \"function\";\n}\n\n/**\n * T5.9 — Test seam: expose the structural validator for unit tests.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__validateLockModule(mod: unknown): boolean {\n return validateLockModule(mod);\n}\n\n/**\n * T5.9 — Test seam: reset the module cache + warning flags between\n * tests so each test starts fresh. NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__resetFileLockCache(): void {\n cached = undefined;\n warnedMissing = false;\n warnedStructural = false;\n loadFailure = undefined;\n}\n\n/**\n * Retry and staleness tuning for `withFileLock`.\n *\n * Every field is optional and the defaults are applied per call, so `undefined` means the default\n * rather than \"no limit\". They are handed to `proper-lockfile` and have NO effect on the fallback\n * path: when that package is absent, `withFileLock` degrades to the in-process mutex, which\n * queues indefinitely and never goes stale.\n *\n * `stale` (default 30000 ms) is how old a lock file must be before it is treated as abandoned by a\n * dead process and broken. Setting it below the longest a legitimate holder can run is what turns\n * a slow operation into two concurrent ones.\n *\n * `retries` (default 5) is the number of acquisition attempts AFTER the first, and `retryFactor`\n * (default 1.5) the backoff multiplier between them. The per-attempt wait is clamped to\n * 100–5000 ms, which the caller cannot change. Exhausting the retries rejects — it does not fall\n * through to running `fn` unlocked.\n *\n * @public — re-exported from the semver-protected `@theokit/sdk/persistence` barrel, and (for\n * back-compat) from the semver-exempt `@theokit/sdk/internal/persistence` alias.\n */\nexport interface FileLockOptions {\n /** Stale lock timeout in ms. Default 30_000 (30s). */\n stale?: number;\n /** Max retries on busy lock. Default 5. */\n retries?: number;\n /** Backoff factor between retries. Default 1.5. */\n retryFactor?: number;\n}\n\n/**\n * Run `fn` while holding an OS-level cross-process lock on `path`.\n *\n * If `proper-lockfile` is installed, uses it with a companion `<path>.lock`\n * file (`realpath: false`, so target file does NOT need to exist yet).\n * Otherwise falls back to in-process `withCwdMutex` and prints a one-shot\n * stderr warning telling the user to install `proper-lockfile` for\n * cross-process safety.\n *\n * The lock is released even when `fn` throws.\n *\n */\nexport async function withFileLock<T>(\n path: string,\n fn: () => Promise<T>,\n options?: FileLockOptions,\n): Promise<T> {\n const lib = await getProperLockfile();\n\n if (lib === null) {\n // #174 — stay silent when the structural check already explained itself. Emitting \"not\n // installed\" on top of \"does not expose lock/unlock\" would be two contradictory diagnoses of\n // one failure, and the reader has no way to tell which is true.\n if (!warnedMissing && !warnedStructural) {\n warnedMissing = true;\n diag(describeLockLoadFailure(loadFailure));\n }\n return withCwdMutex(`file-lock:${path}`, fn);\n }\n\n // proper-lockfile errors immediately on same-process concurrent acquire\n // (\"Lock file is already being held\"). Wrap with cwd-mutex first so\n // in-process callers queue and only ONE thread at a time enters the\n // cross-process acquire path. Combined: full in-process + cross-process\n // serialization.\n return withCwdMutex(`file-lock:${path}`, async () => {\n const release = await lib.lock(path, {\n // EC-1: companion lockfile, target path may not exist yet.\n lockfilePath: `${path}.lock`,\n realpath: false,\n stale: options?.stale ?? 30_000,\n retries: {\n retries: options?.retries ?? 5,\n factor: options?.retryFactor ?? 1.5,\n minTimeout: 100,\n maxTimeout: 5_000,\n },\n });\n\n try {\n return await fn();\n } finally {\n await release();\n }\n });\n}\n\n/**\n * Test helper — resets the cached proper-lockfile module + warning flag.\n * Allows tests to simulate \"module absent\" by clearing cache then\n * monkey-patching the dynamic import resolution.\n *\n * @internal\n */\nexport function _resetFileLockCacheForTesting(): void {\n cached = undefined;\n warnedMissing = false;\n}\n"]}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { submit, emitRunEvent } from './chunk-XKMVJ443.js';
|
|
2
|
-
import { enqueueSessionWrite, hydrateSession, persistTurnToTranscript, flushSessionWrites, appendSessionMessage, getSessionMessages, discardSession, clearSession } from './chunk-
|
|
3
|
-
import { IndexManager } from './chunk-
|
|
2
|
+
import { enqueueSessionWrite, hydrateSession, persistTurnToTranscript, flushSessionWrites, appendSessionMessage, getSessionMessages, discardSession, clearSession } from './chunk-EXI7EHDN.js';
|
|
3
|
+
import { IndexManager } from './chunk-DPY2M74T.js';
|
|
4
4
|
import { currentPersonalityContext, warnPersonalitySwitchInsideFork } from './chunk-ZHWKT2NI.js';
|
|
5
5
|
import { extractCodePlugins } from './chunk-2SFBB54R.js';
|
|
6
|
-
import { createOpenAiCompatibleRuntime } from './chunk-
|
|
6
|
+
import { createOpenAiCompatibleRuntime } from './chunk-HI3W37FY.js';
|
|
7
7
|
import { persistActiveMemoryTranscript } from './chunk-OR6XIWLB.js';
|
|
8
|
-
import { writeSessionSummary, resolveMemoryRoot, MEMORY_KINDS, appendFact, readFacts, legacyMemoryJsonPath, memoryMdPath, appendFactToMarkdown } from './chunk-
|
|
9
|
-
import { FsSessionStore } from './chunk-
|
|
10
|
-
import { discoverProviderPlugins, validateApiKeyShape, getConfiguredBaseUrl, httpRequest, isFixtureApiKey, presentProviderCredentialEnvVars, buildDefaultSummarizer, shouldUseRealLocalRuntime, parseSseStream, CircuitBreaker, resolveRunProvider, mergeExplicitApiKey, resolveProviderChain, abortError, tryFirstEvent, relayStream, renderToolResultContentText } from './chunk-
|
|
8
|
+
import { resolveMaxFacts, writeSessionSummary, resolveMemoryRoot, MEMORY_KINDS, appendFact, readFacts, legacyMemoryJsonPath, memoryMdPath, appendFactToMarkdown } from './chunk-X3LOJJMO.js';
|
|
9
|
+
import { FsSessionStore } from './chunk-IZDDSLL2.js';
|
|
10
|
+
import { discoverProviderPlugins, validateApiKeyShape, getConfiguredBaseUrl, httpRequest, isFixtureApiKey, presentProviderCredentialEnvVars, buildDefaultSummarizer, shouldUseRealLocalRuntime, parseSseStream, CircuitBreaker, resolveRunProvider, mergeExplicitApiKey, resolveProviderChain, abortError, tryFirstEvent, relayStream, renderToolResultContentText } from './chunk-EVH3OUMY.js';
|
|
11
11
|
import { resolveChildEnv } from './chunk-HKCKOAIO.js';
|
|
12
12
|
import { DEFAULT_MAX_BYTES_PER_FILE, runDiscovery, truncateWithMarker } from './chunk-7QJYKVP6.js';
|
|
13
13
|
import { warnFailureOnce, loadHookConfig, warnOnce } from './chunk-OPAKPEPG.js';
|
|
@@ -21,8 +21,8 @@ import { withToolWhitelist, checkToolWhitelist } from './chunk-SAGRF4IB.js';
|
|
|
21
21
|
import { validateArtifactPath, PathTraversalError, safePathJoin } from './chunk-5DD4NJN3.js';
|
|
22
22
|
import { insideRoot, atOrInsideRoot } from './chunk-UKMBRMGT.js';
|
|
23
23
|
import { mapWithConcurrency } from './chunk-7JAKO3NM.js';
|
|
24
|
-
import { expandTilde, defaultBaseDir } from './chunk-
|
|
25
|
-
import { withFileLock } from './chunk-
|
|
24
|
+
import { expandTilde, defaultBaseDir } from './chunk-FTZTZBCU.js';
|
|
25
|
+
import { withFileLock } from './chunk-RGQICWFU.js';
|
|
26
26
|
import { withCwdMutex } from './chunk-Q5EWJPRY.js';
|
|
27
27
|
import { sweepStaleAtomicTemps, atomicWriteJson } from './chunk-3JHIFQ4I.js';
|
|
28
28
|
import { loadSubagents, pluginBundleDirs } from './chunk-ZDYDBXSD.js';
|
|
@@ -30,9 +30,10 @@ import { reportUndeclaredSources, theokitConfigRoot, undefinedVariablesIn, getTh
|
|
|
30
30
|
import { readWorkspaceDir, parseSimpleYaml } from './chunk-MQGSOKR3.js';
|
|
31
31
|
import { resolveEffectiveContextWindow, CONTEXT_WINDOW_FLOOR, CONTEXT_WINDOW_MARGIN } from './chunk-GMRFAX4I.js';
|
|
32
32
|
import { parseModelId } from './chunk-R7WIIPUR.js';
|
|
33
|
-
import { getProviderProfile } from './chunk-
|
|
34
|
-
import { getCatalogModelInfo, isPatchedModelKey } from './chunk-
|
|
33
|
+
import { getProviderProfile } from './chunk-I2ORT6QD.js';
|
|
34
|
+
import { getCatalogModelInfo, isPatchedModelKey } from './chunk-SVCPJRUB.js';
|
|
35
35
|
import { globalSingleton } from './chunk-AGACYRJ2.js';
|
|
36
|
+
import { boundFetch } from './chunk-Q7GYMXVC.js';
|
|
36
37
|
import { AgentRunError, coerceToKnownAgentRunErrorCode, UnknownAgentError, ConfigurationError, AuthenticationError, AgentDisposedError, UnsupportedRunOperationError, NetworkError, TheokitAgentError } from './chunk-B5MHRQJZ.js';
|
|
37
38
|
import { diag, resolveApiKey, API_KEY_ENV_VAR, redactSecrets, diagFailure } from './chunk-CZJ6Q7CW.js';
|
|
38
39
|
import { stat, mkdir, readFile, readdir, access, unlink } from 'fs/promises';
|
|
@@ -334,6 +335,8 @@ function serializeMemory(memory) {
|
|
|
334
335
|
if (memory.scope !== void 0) out.scope = memory.scope;
|
|
335
336
|
if (memory.activeRecall !== void 0) out.activeRecall = { ...memory.activeRecall };
|
|
336
337
|
if (memory.index !== void 0) out.index = serializeMemoryIndex(memory.index);
|
|
338
|
+
if (memory.maxFacts !== void 0) out.maxFacts = memory.maxFacts;
|
|
339
|
+
if (memory.directory !== void 0) out.directory = memory.directory;
|
|
337
340
|
return out;
|
|
338
341
|
}
|
|
339
342
|
function serializeMemoryIndex(index) {
|
|
@@ -883,6 +886,7 @@ async function readMemoryFacts(cwd, config) {
|
|
|
883
886
|
}
|
|
884
887
|
async function appendMemoryFact(cwd, config, fact) {
|
|
885
888
|
if (!config.enabled) return;
|
|
889
|
+
resolveMaxFacts(config.maxFacts);
|
|
886
890
|
await migrateLegacyJson(cwd, config);
|
|
887
891
|
const sanitized = {
|
|
888
892
|
text: redactSecrets(fact.text),
|
|
@@ -1573,7 +1577,7 @@ function createRealCloudRun(options) {
|
|
|
1573
1577
|
apiKey,
|
|
1574
1578
|
baseUrl,
|
|
1575
1579
|
userText,
|
|
1576
|
-
fetchImpl: options.fetch
|
|
1580
|
+
fetchImpl: boundFetch(options.fetch),
|
|
1577
1581
|
sendOptions: options.sendOptions,
|
|
1578
1582
|
systemPrompt: options.systemPrompt,
|
|
1579
1583
|
agentConfig: options.agentConfig
|
|
@@ -3610,6 +3614,7 @@ function validateToolSchema(tool) {
|
|
|
3610
3614
|
}
|
|
3611
3615
|
function validateMemory(options) {
|
|
3612
3616
|
const memory = options.memory;
|
|
3617
|
+
resolveMaxFacts(memory?.maxFacts);
|
|
3613
3618
|
if (memory?.storePath === void 0) return;
|
|
3614
3619
|
const storePath = memory.storePath;
|
|
3615
3620
|
if (storePath.includes("..") || storePath.startsWith("/") || /^[A-Z]:/i.test(storePath)) {
|
|
@@ -10606,10 +10611,12 @@ async function rehydrateExistingAgent(agentId, existing, options) {
|
|
|
10606
10611
|
await discoverProviderPlugins();
|
|
10607
10612
|
await validateRehydratedAgent(agentId, existing);
|
|
10608
10613
|
const mergedLocal = options.local !== void 0 && existing.options.local !== void 0 ? { ...existing.options.local, ...options.local } : options.local ?? existing.options.local;
|
|
10614
|
+
const mergedMemory = mergeResumedMemory(existing.options.memory, options.memory);
|
|
10609
10615
|
const mergedOptions = {
|
|
10610
10616
|
...existing.options,
|
|
10611
10617
|
...options,
|
|
10612
10618
|
...mergedLocal !== void 0 ? { local: mergedLocal } : {},
|
|
10619
|
+
...mergedMemory !== void 0 ? { memory: mergedMemory } : {},
|
|
10613
10620
|
// SE8 — normalize a caller-supplied bare-string model override at this resume
|
|
10614
10621
|
// boundary (Agent.resume never flows through runCreateUnderSpan). Cloud resume
|
|
10615
10622
|
// honors it; local resume forces the persisted model below.
|
|
@@ -10617,6 +10624,7 @@ async function rehydrateExistingAgent(agentId, existing, options) {
|
|
|
10617
10624
|
mcpServers: void 0,
|
|
10618
10625
|
agentId
|
|
10619
10626
|
};
|
|
10627
|
+
resolveMaxFacts(mergedOptions.memory?.maxFacts);
|
|
10620
10628
|
if (existing.runtime === "cloud") {
|
|
10621
10629
|
return new CloudAgent(mergedOptions, agentId);
|
|
10622
10630
|
}
|
|
@@ -10624,6 +10632,12 @@ async function rehydrateExistingAgent(agentId, existing, options) {
|
|
|
10624
10632
|
await agent.initialize();
|
|
10625
10633
|
return agent;
|
|
10626
10634
|
}
|
|
10635
|
+
function mergeResumedMemory(persisted, override) {
|
|
10636
|
+
if (override === void 0) return persisted;
|
|
10637
|
+
if (persisted === void 0) return override;
|
|
10638
|
+
const named = Object.entries(override).filter(([, value]) => value !== void 0);
|
|
10639
|
+
return { ...persisted, ...Object.fromEntries(named) };
|
|
10640
|
+
}
|
|
10627
10641
|
async function validateRehydratedAgent(agentId, entry) {
|
|
10628
10642
|
if (entry.runtime !== "local") return;
|
|
10629
10643
|
const candidate = entry.options.local?.cwd ?? entry.cwd;
|
|
@@ -11052,7 +11066,7 @@ var Agent = class _Agent {
|
|
|
11052
11066
|
*/
|
|
11053
11067
|
static async compact(agentId, options = {}) {
|
|
11054
11068
|
const reg = await requireLocalAgent(agentId, "compact");
|
|
11055
|
-
const { compactSessionTranscript, buildDefaultSummarizer: buildDefaultSummarizer2 } = await import('./compact-session-
|
|
11069
|
+
const { compactSessionTranscript, buildDefaultSummarizer: buildDefaultSummarizer2 } = await import('./compact-session-PVAWTKKL.js');
|
|
11056
11070
|
const { cwd, model, store } = await openLocalStore(reg);
|
|
11057
11071
|
return enqueueSessionWrite(
|
|
11058
11072
|
cwd,
|
|
@@ -11082,7 +11096,7 @@ var Agent = class _Agent {
|
|
|
11082
11096
|
*/
|
|
11083
11097
|
static async injectSessionTurn(agentId, turn) {
|
|
11084
11098
|
const reg = await requireLocalAgent(agentId, "injectSessionTurn");
|
|
11085
|
-
const { injectSessionTurn } = await import('./inject-session-
|
|
11099
|
+
const { injectSessionTurn } = await import('./inject-session-O24XGRR6.js');
|
|
11086
11100
|
const { cwd, model, store } = await openLocalStore(reg);
|
|
11087
11101
|
await injectSessionTurn({
|
|
11088
11102
|
store,
|
|
@@ -11112,7 +11126,7 @@ var Agent = class _Agent {
|
|
|
11112
11126
|
*/
|
|
11113
11127
|
static async transcript(agentId) {
|
|
11114
11128
|
const reg = await requireLocalAgent(agentId, "transcript");
|
|
11115
|
-
const { readSessionMessages } = await import('./agent-session-store-
|
|
11129
|
+
const { readSessionMessages } = await import('./agent-session-store-ODD3IZCW.js');
|
|
11116
11130
|
const { store } = await openLocalStore(reg);
|
|
11117
11131
|
return readSessionMessages(store, agentId);
|
|
11118
11132
|
}
|
|
@@ -11232,13 +11246,13 @@ async function openLocalStore(reg) {
|
|
|
11232
11246
|
const cwd = reg.cwd ?? process.cwd();
|
|
11233
11247
|
const optModel = reg.options.model;
|
|
11234
11248
|
const model = reg.model?.id ?? (typeof optModel === "string" ? optModel : optModel?.id) ?? "unknown";
|
|
11235
|
-
const { FsSessionStore: FsSessionStore2 } = await import('./fs-session-store-
|
|
11236
|
-
const { defaultBaseDir: defaultBaseDir2, expandTilde: expandTilde2 } = await import('./session-transcript-
|
|
11249
|
+
const { FsSessionStore: FsSessionStore2 } = await import('./fs-session-store-3VI4CPTX.js');
|
|
11250
|
+
const { defaultBaseDir: defaultBaseDir2, expandTilde: expandTilde2 } = await import('./session-transcript-AR7IBICT.js');
|
|
11237
11251
|
const configuredSessionDir = reg.options.local?.sessionDir ?? reg.options.local?.baseDir;
|
|
11238
11252
|
const baseDir = configuredSessionDir !== void 0 ? expandTilde2(configuredSessionDir) : defaultBaseDir2();
|
|
11239
11253
|
return { cwd, model, store: new FsSessionStore2({ baseDir, cwd }) };
|
|
11240
11254
|
}
|
|
11241
11255
|
|
|
11242
11256
|
export { Agent, AgentBuilder, DEFAULT_AGENTIC_MODEL_ID, MEMORY_EMBEDDING_ADAPTERS, Tool, ToolError, UsageAccumulator, computeCost, generateCronId, getPricingEntry, managedSettingsPathFor, openRouterMemoryEmbeddingProviderAdapter, readManagedSettings, resolveSessionDir };
|
|
11243
|
-
//# sourceMappingURL=chunk-
|
|
11244
|
-
//# sourceMappingURL=chunk-
|
|
11257
|
+
//# sourceMappingURL=chunk-RTE2DD4S.js.map
|
|
11258
|
+
//# sourceMappingURL=chunk-RTE2DD4S.js.map
|