@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.
Files changed (190) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/dist/{agent-enXXu447.d.ts → agent-CmKwSyyD.d.ts} +27 -0
  3. package/dist/{agent-5M7WLUWH.cjs → agent-TLRURB7W.cjs} +18 -16
  4. package/dist/{agent-5M7WLUWH.cjs.map → agent-TLRURB7W.cjs.map} +1 -1
  5. package/dist/{agent-Dh2YHSLj.d.cts → agent-XMkGzff_.d.cts} +27 -0
  6. package/dist/{agent-R5RERYFU.js → agent-XTLAVVYC.js} +17 -15
  7. package/dist/{agent-R5RERYFU.js.map → agent-XTLAVVYC.js.map} +1 -1
  8. package/dist/agent-session-store-ODD3IZCW.js +6 -0
  9. package/dist/{agent-session-store-AFML3AXC.js.map → agent-session-store-ODD3IZCW.js.map} +1 -1
  10. package/dist/agent-session-store-SVEJHSUA.cjs +23 -0
  11. package/dist/{agent-session-store-MTSIY3MH.cjs.map → agent-session-store-SVEJHSUA.cjs.map} +1 -1
  12. package/dist/auth/index.cjs +8 -7
  13. package/dist/auth/index.cjs.map +1 -1
  14. package/dist/auth/index.js +3 -2
  15. package/dist/auth/index.js.map +1 -1
  16. package/dist/{chunk-QCIARBLS.js → chunk-523O5UYB.js} +3 -3
  17. package/dist/{chunk-QCIARBLS.js.map → chunk-523O5UYB.js.map} +1 -1
  18. package/dist/chunk-7KIN3L2S.js +103 -0
  19. package/dist/chunk-7KIN3L2S.js.map +1 -0
  20. package/dist/chunk-ASK2OQM5.cjs +84 -0
  21. package/dist/chunk-ASK2OQM5.cjs.map +1 -0
  22. package/dist/{chunk-56BCEM26.cjs → chunk-CVEQ5366.cjs} +105 -91
  23. package/dist/chunk-CVEQ5366.cjs.map +1 -0
  24. package/dist/{chunk-R2C3HXR3.js → chunk-DPY2M74T.js} +3 -3
  25. package/dist/{chunk-R2C3HXR3.js.map → chunk-DPY2M74T.js.map} +1 -1
  26. package/dist/chunk-EHD25JBZ.cjs +10 -0
  27. package/dist/chunk-EHD25JBZ.cjs.map +1 -0
  28. package/dist/{chunk-NOO6GZTZ.js → chunk-EVH3OUMY.js} +13 -12
  29. package/dist/chunk-EVH3OUMY.js.map +1 -0
  30. package/dist/{chunk-5522X223.js → chunk-EXI7EHDN.js} +4 -4
  31. package/dist/{chunk-5522X223.js.map → chunk-EXI7EHDN.js.map} +1 -1
  32. package/dist/{chunk-PSLCVSCS.cjs → chunk-FR6COQXZ.cjs} +6 -6
  33. package/dist/{chunk-PSLCVSCS.cjs.map → chunk-FR6COQXZ.cjs.map} +1 -1
  34. package/dist/{chunk-JOFVLOFY.js → chunk-FTZTZBCU.js} +12 -4
  35. package/dist/chunk-FTZTZBCU.js.map +1 -0
  36. package/dist/{chunk-T5KOSR5Y.cjs → chunk-FYEHYQ7T.cjs} +8 -8
  37. package/dist/{chunk-T5KOSR5Y.cjs.map → chunk-FYEHYQ7T.cjs.map} +1 -1
  38. package/dist/{chunk-HOHR75KF.js → chunk-HI3W37FY.js} +4 -3
  39. package/dist/chunk-HI3W37FY.js.map +1 -0
  40. package/dist/chunk-HU666T3Q.cjs +1891 -0
  41. package/dist/chunk-HU666T3Q.cjs.map +1 -0
  42. package/dist/{chunk-53RDNK3H.js → chunk-I2ORT6QD.js} +3 -3
  43. package/dist/{chunk-53RDNK3H.js.map → chunk-I2ORT6QD.js.map} +1 -1
  44. package/dist/{chunk-UNZOJVVC.js → chunk-IZDDSLL2.js} +5 -4
  45. package/dist/chunk-IZDDSLL2.js.map +1 -0
  46. package/dist/{chunk-TTBIQTO5.cjs → chunk-L3C6CCBG.cjs} +15 -15
  47. package/dist/{chunk-TTBIQTO5.cjs.map → chunk-L3C6CCBG.cjs.map} +1 -1
  48. package/dist/{chunk-B3XXQX6L.cjs → chunk-NQVWSSX2.cjs} +10 -9
  49. package/dist/chunk-NQVWSSX2.cjs.map +1 -0
  50. package/dist/{chunk-LL4QA3DI.cjs → chunk-PCLRIQPX.cjs} +4 -4
  51. package/dist/{chunk-LL4QA3DI.cjs.map → chunk-PCLRIQPX.cjs.map} +1 -1
  52. package/dist/chunk-Q7GYMXVC.js +8 -0
  53. package/dist/chunk-Q7GYMXVC.js.map +1 -0
  54. package/dist/{chunk-ARMFXTY6.cjs → chunk-QY3CIMUV.cjs} +34 -33
  55. package/dist/chunk-QY3CIMUV.cjs.map +1 -0
  56. package/dist/chunk-R5YPDAKD.cjs +108 -0
  57. package/dist/chunk-R5YPDAKD.cjs.map +1 -0
  58. package/dist/chunk-RGQICWFU.js +82 -0
  59. package/dist/chunk-RGQICWFU.js.map +1 -0
  60. package/dist/{chunk-OOM236Z4.js → chunk-RTE2DD4S.js} +32 -18
  61. package/dist/chunk-RTE2DD4S.js.map +1 -0
  62. package/dist/chunk-SGC7LSHF.cjs +18 -0
  63. package/dist/{chunk-R3ZQBPA5.cjs.map → chunk-SGC7LSHF.cjs.map} +1 -1
  64. package/dist/{chunk-RA7IE4NK.cjs → chunk-SKDNCTXG.cjs} +4 -3
  65. package/dist/chunk-SKDNCTXG.cjs.map +1 -0
  66. package/dist/chunk-SVCPJRUB.js +1874 -0
  67. package/dist/chunk-SVCPJRUB.js.map +1 -0
  68. package/dist/{chunk-EJROML3Q.js → chunk-TX56N7FR.js} +4 -3
  69. package/dist/chunk-TX56N7FR.js.map +1 -0
  70. package/dist/{chunk-QDQQYRJI.js → chunk-W2ZVTEOD.js} +3 -3
  71. package/dist/{chunk-QDQQYRJI.js.map → chunk-W2ZVTEOD.js.map} +1 -1
  72. package/dist/{chunk-TC4RWP3Y.js → chunk-X3LOJJMO.js} +89 -29
  73. package/dist/chunk-X3LOJJMO.js.map +1 -0
  74. package/dist/{chunk-2WXHA33T.js → chunk-XERM7PDQ.js} +3 -3
  75. package/dist/{chunk-2WXHA33T.js.map → chunk-XERM7PDQ.js.map} +1 -1
  76. package/dist/{chunk-MEUBLCM4.cjs → chunk-YEHQ3SIC.cjs} +4 -3
  77. package/dist/chunk-YEHQ3SIC.cjs.map +1 -0
  78. package/dist/{chunk-YIFFF23U.cjs → chunk-ZAM7BJXJ.cjs} +5 -5
  79. package/dist/{chunk-YIFFF23U.cjs.map → chunk-ZAM7BJXJ.cjs.map} +1 -1
  80. package/dist/{chunk-76PIKR4P.cjs → chunk-ZD66GFH5.cjs} +91 -29
  81. package/dist/chunk-ZD66GFH5.cjs.map +1 -0
  82. package/dist/{chunk-GZV6AVRL.cjs → chunk-ZWACQM5U.cjs} +11 -3
  83. package/dist/chunk-ZWACQM5U.cjs.map +1 -0
  84. package/dist/{compact-session-RBPLUPCK.cjs → compact-session-4QHBBGEY.cjs} +16 -15
  85. package/dist/{compact-session-RBPLUPCK.cjs.map → compact-session-4QHBBGEY.cjs.map} +1 -1
  86. package/dist/{compact-session-2N3ZYJTW.js → compact-session-PVAWTKKL.js} +7 -6
  87. package/dist/{compact-session-2N3ZYJTW.js.map → compact-session-PVAWTKKL.js.map} +1 -1
  88. package/dist/{cron-DTuaPMVI.d.ts → cron-BPccQCO8.d.ts} +1 -1
  89. package/dist/{cron-QTgcwcZt.d.cts → cron-Blj6wMYg.d.cts} +1 -1
  90. package/dist/cron.cjs +17 -15
  91. package/dist/cron.d.cts +2 -2
  92. package/dist/cron.d.ts +2 -2
  93. package/dist/cron.js +16 -14
  94. package/dist/eval.cjs +20 -18
  95. package/dist/eval.cjs.map +1 -1
  96. package/dist/eval.js +16 -14
  97. package/dist/eval.js.map +1 -1
  98. package/dist/fs-session-store-3VI4CPTX.js +11 -0
  99. package/dist/{fs-session-store-STZZFXH2.js.map → fs-session-store-3VI4CPTX.js.map} +1 -1
  100. package/dist/fs-session-store-IQ6PEHYF.cjs +20 -0
  101. package/dist/{fs-session-store-JHBJFKVV.cjs.map → fs-session-store-IQ6PEHYF.cjs.map} +1 -1
  102. package/dist/{index-manager-ONQJSWX5.js → index-manager-JVYIVTZG.js} +6 -5
  103. package/dist/{index-manager-ONQJSWX5.js.map → index-manager-JVYIVTZG.js.map} +1 -1
  104. package/dist/{index-manager-ZGJN25FD.cjs → index-manager-YGXRFJMZ.cjs} +7 -6
  105. package/dist/{index-manager-ZGJN25FD.cjs.map → index-manager-YGXRFJMZ.cjs.map} +1 -1
  106. package/dist/index.cjs +68 -60
  107. package/dist/index.cjs.map +1 -1
  108. package/dist/index.d.cts +42 -6
  109. package/dist/index.d.ts +42 -6
  110. package/dist/index.js +31 -23
  111. package/dist/index.js.map +1 -1
  112. package/dist/{inject-session-YNNOE3O6.js → inject-session-O24XGRR6.js} +5 -5
  113. package/dist/{inject-session-YNNOE3O6.js.map → inject-session-O24XGRR6.js.map} +1 -1
  114. package/dist/{inject-session-3FPXJDJP.cjs → inject-session-OMLFL2V3.cjs} +7 -7
  115. package/dist/{inject-session-3FPXJDJP.cjs.map → inject-session-OMLFL2V3.cjs.map} +1 -1
  116. package/dist/internal/memory/adapters/index.cjs +3 -2
  117. package/dist/internal/memory/adapters/index.js +2 -1
  118. package/dist/internal/memory/dreaming/phases.d.ts +2 -0
  119. package/dist/internal/memory/dreaming/run.d.ts +5 -0
  120. package/dist/internal/memory/sdk-memory-peer-loader.d.ts +2 -0
  121. package/dist/internal/memory/storage/fact-ceiling.d.cts +19 -0
  122. package/dist/internal/memory/storage/fact-ceiling.d.ts +19 -0
  123. package/dist/internal/memory/storage/index.cjs +41 -32
  124. package/dist/internal/memory/storage/index.d.cts +1 -0
  125. package/dist/internal/memory/storage/index.d.ts +1 -0
  126. package/dist/internal/memory/storage/index.js +4 -3
  127. package/dist/internal/memory/storage/markdown-store.d.cts +3 -1
  128. package/dist/internal/memory/storage/markdown-store.d.ts +3 -1
  129. package/dist/internal/memory/types.d.ts +6 -0
  130. package/dist/internal/persistence/index.cjs +7 -6
  131. package/dist/internal/persistence/index.cjs.map +1 -1
  132. package/dist/internal/persistence/index.js +2 -1
  133. package/dist/internal/persistence/index.js.map +1 -1
  134. package/dist/internal/persistence/persistence-schema.d.cts +1 -1
  135. package/dist/internal/persistence/persistence-schema.d.ts +1 -1
  136. package/dist/internal/providers/catalog-loader.d.ts +30 -3
  137. package/dist/internal/runtime/registry/agent-registry-store.d.ts +2 -0
  138. package/dist/internal/runtime-fetch.d.ts +1 -0
  139. package/dist/models.cjs +12 -11
  140. package/dist/models.cjs.map +1 -1
  141. package/dist/models.js +4 -3
  142. package/dist/models.js.map +1 -1
  143. package/dist/persistence.cjs +14 -13
  144. package/dist/persistence.cjs.map +1 -1
  145. package/dist/persistence.js +4 -3
  146. package/dist/persistence.js.map +1 -1
  147. package/dist/providers.cjs +6 -5
  148. package/dist/providers.js +4 -3
  149. package/dist/{session-transcript-VTBTCGQX.js → session-transcript-AR7IBICT.js} +3 -3
  150. package/dist/{session-transcript-VTBTCGQX.js.map → session-transcript-AR7IBICT.js.map} +1 -1
  151. package/dist/{session-transcript-LGHSNVY5.cjs → session-transcript-RACG7BK2.cjs} +16 -16
  152. package/dist/{session-transcript-LGHSNVY5.cjs.map → session-transcript-RACG7BK2.cjs.map} +1 -1
  153. package/dist/subagents-loader.d.cts +1 -1
  154. package/dist/subagents-loader.d.ts +1 -1
  155. package/dist/subscription/index.cjs +2 -1
  156. package/dist/subscription/index.cjs.map +1 -1
  157. package/dist/subscription/index.js +2 -1
  158. package/dist/subscription/index.js.map +1 -1
  159. package/dist/types/agent.d.ts +27 -0
  160. package/docs/error-codes.md +40 -38
  161. package/docs/harness-capability-map.md +6 -1
  162. package/package.json +2 -2
  163. package/dist/agent-session-store-AFML3AXC.js +0 -6
  164. package/dist/agent-session-store-MTSIY3MH.cjs +0 -23
  165. package/dist/chunk-56BCEM26.cjs.map +0 -1
  166. package/dist/chunk-76PIKR4P.cjs.map +0 -1
  167. package/dist/chunk-ARMFXTY6.cjs.map +0 -1
  168. package/dist/chunk-B3XXQX6L.cjs.map +0 -1
  169. package/dist/chunk-BKMDRBJ7.js +0 -180
  170. package/dist/chunk-BKMDRBJ7.js.map +0 -1
  171. package/dist/chunk-EJROML3Q.js.map +0 -1
  172. package/dist/chunk-GZV6AVRL.cjs.map +0 -1
  173. package/dist/chunk-HOHR75KF.js.map +0 -1
  174. package/dist/chunk-JOFVLOFY.js.map +0 -1
  175. package/dist/chunk-MEUBLCM4.cjs.map +0 -1
  176. package/dist/chunk-MFZODA5Y.js +0 -583
  177. package/dist/chunk-MFZODA5Y.js.map +0 -1
  178. package/dist/chunk-NOO6GZTZ.js.map +0 -1
  179. package/dist/chunk-OF2CLCTH.cjs +0 -186
  180. package/dist/chunk-OF2CLCTH.cjs.map +0 -1
  181. package/dist/chunk-OOM236Z4.js.map +0 -1
  182. package/dist/chunk-R3ZQBPA5.cjs +0 -18
  183. package/dist/chunk-RA7IE4NK.cjs.map +0 -1
  184. package/dist/chunk-TC4RWP3Y.js.map +0 -1
  185. package/dist/chunk-UNZOJVVC.js.map +0 -1
  186. package/dist/chunk-YRJA2POB.cjs +0 -601
  187. package/dist/chunk-YRJA2POB.cjs.map +0 -1
  188. package/dist/fs-session-store-JHBJFKVV.cjs +0 -19
  189. package/dist/fs-session-store-STZZFXH2.js +0 -10
  190. package/dist/provider-catalog.json +0 -1295
@@ -1,186 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkZF2LDKQQ_cjs = require('./chunk-ZF2LDKQQ.cjs');
4
- var chunkUNFBHV46_cjs = require('./chunk-UNFBHV46.cjs');
5
- var chunk6LHQPOMI_cjs = require('./chunk-6LHQPOMI.cjs');
6
- var fs = require('fs');
7
- var path = require('path');
8
-
9
- // src/internal/persistence/file-lock.ts
10
- var cached;
11
- var warnedMissing = false;
12
- var warnedStructural = false;
13
- var loadFailure;
14
- function isModuleAbsent(err) {
15
- const code = err?.code;
16
- return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
17
- }
18
- function describeLockLoadFailure(err) {
19
- const consequence = "cross-process file lock unavailable \u2014 concurrent processes over the same file are NOT serialized.";
20
- if (isModuleAbsent(err)) {
21
- return `[theokit-sdk] proper-lockfile not installed; ${consequence} Install with: pnpm add proper-lockfile
22
- `;
23
- }
24
- const code = err?.code;
25
- const detail = err instanceof Error ? err.message : String(err);
26
- 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.
27
- `;
28
- }
29
- async function getProperLockfile() {
30
- if (cached !== void 0) return cached;
31
- try {
32
- const mod = await import('proper-lockfile');
33
- if (!validateLockModule(mod)) {
34
- if (!warnedStructural) {
35
- warnedStructural = true;
36
- chunk6LHQPOMI_cjs.diag(
37
- "[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"
38
- );
39
- }
40
- cached = null;
41
- return cached;
42
- }
43
- cached = mod;
44
- } catch (err) {
45
- loadFailure = err;
46
- cached = null;
47
- }
48
- return cached;
49
- }
50
- function validateLockModule(mod) {
51
- if (mod === null || mod === void 0 || typeof mod !== "object") return false;
52
- const m = mod;
53
- return typeof m.lock === "function" && typeof m.unlock === "function";
54
- }
55
- async function withFileLock(path, fn, options) {
56
- const lib = await getProperLockfile();
57
- if (lib === null) {
58
- if (!warnedMissing && !warnedStructural) {
59
- warnedMissing = true;
60
- chunk6LHQPOMI_cjs.diag(describeLockLoadFailure(loadFailure));
61
- }
62
- return chunkZF2LDKQQ_cjs.withCwdMutex(`file-lock:${path}`, fn);
63
- }
64
- return chunkZF2LDKQQ_cjs.withCwdMutex(`file-lock:${path}`, async () => {
65
- const release = await lib.lock(path, {
66
- // EC-1: companion lockfile, target path may not exist yet.
67
- lockfilePath: `${path}.lock`,
68
- realpath: false,
69
- stale: options?.stale ?? 3e4,
70
- retries: {
71
- retries: options?.retries ?? 5,
72
- factor: options?.retryFactor ?? 1.5,
73
- minTimeout: 100,
74
- maxTimeout: 5e3
75
- }
76
- });
77
- try {
78
- return await fn();
79
- } finally {
80
- await release();
81
- }
82
- });
83
- }
84
- var JsonlParseError = class extends chunkUNFBHV46_cjs.TheokitAgentError {
85
- constructor(message, line) {
86
- super(message, { code: "jsonl_parse_failed", isRetryable: false });
87
- this.line = line;
88
- }
89
- line;
90
- name = "JsonlParseError";
91
- };
92
- function isPlainObject(value) {
93
- return typeof value === "object" && value !== null && !Array.isArray(value);
94
- }
95
- function tryParseObjectLine(line) {
96
- if (line.length === 0) return void 0;
97
- let parsed;
98
- try {
99
- parsed = JSON.parse(line);
100
- } catch {
101
- return void 0;
102
- }
103
- return isPlainObject(parsed) ? parsed : void 0;
104
- }
105
- function loadJsonl(path, opts = {}) {
106
- const lines = fs.readFileSync(path, "utf8").split("\n");
107
- const out = [];
108
- for (let i = 0; i < lines.length; i += 1) {
109
- const lineNumber = i + 1;
110
- const line = (lines[i] ?? "").trim();
111
- if (line.length === 0) continue;
112
- const parsed = parseLine(
113
- line,
114
- lineNumber,
115
- opts.tolerateTrailingPartialLine === true && lineNumber === lines.length
116
- );
117
- if (parsed === void 0) break;
118
- out.push(opts.map ? opts.map(parsed, lineNumber) : parsed);
119
- }
120
- return out;
121
- }
122
- function parseLine(line, lineNumber, tolerate) {
123
- let parsed;
124
- try {
125
- parsed = JSON.parse(line);
126
- } catch {
127
- if (tolerate) return void 0;
128
- throw new JsonlParseError(`line ${lineNumber}: invalid JSON`, lineNumber);
129
- }
130
- if (!isPlainObject(parsed)) {
131
- throw new JsonlParseError(`line ${lineNumber}: not a JSON object`, lineNumber);
132
- }
133
- return parsed;
134
- }
135
- function appendJsonl(path$1, record) {
136
- fs.mkdirSync(path.dirname(path$1), { recursive: true, mode: 448 });
137
- const prefix = needsLineBreakBefore(path$1) ? "\n" : "";
138
- const fd = fs.openSync(path$1, "a", 384);
139
- try {
140
- fs.writeSync(fd, `${prefix}${JSON.stringify(record)}
141
- `);
142
- } finally {
143
- fs.closeSync(fd);
144
- }
145
- }
146
- function needsLineBreakBefore(path) {
147
- let fd;
148
- try {
149
- fd = fs.openSync(path, "r");
150
- } catch {
151
- return false;
152
- }
153
- try {
154
- const size = fs.fstatSync(fd).size;
155
- if (size === 0) return false;
156
- const buf = Buffer.alloc(1);
157
- fs.readSync(fd, buf, 0, 1, size - 1);
158
- return buf[0] !== 10;
159
- } finally {
160
- fs.closeSync(fd);
161
- }
162
- }
163
- function readJsonlIds(path, keyFn) {
164
- const done = /* @__PURE__ */ new Set();
165
- let text;
166
- try {
167
- text = fs.readFileSync(path, "utf8");
168
- } catch {
169
- return done;
170
- }
171
- for (const rawLine of text.split("\n")) {
172
- const parsed = tryParseObjectLine(rawLine.trim());
173
- if (parsed === void 0) continue;
174
- const key = keyFn(parsed);
175
- if (typeof key === "string" && key.length > 0) done.add(key);
176
- }
177
- return done;
178
- }
179
-
180
- exports.JsonlParseError = JsonlParseError;
181
- exports.appendJsonl = appendJsonl;
182
- exports.loadJsonl = loadJsonl;
183
- exports.readJsonlIds = readJsonlIds;
184
- exports.withFileLock = withFileLock;
185
- //# sourceMappingURL=chunk-OF2CLCTH.cjs.map
186
- //# sourceMappingURL=chunk-OF2CLCTH.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/persistence/file-lock.ts","../src/internal/persistence/jsonl.ts"],"names":["diag","withCwdMutex","TheokitAgentError","readFileSync","path","mkdirSync","dirname","openSync","writeSync","closeSync","fstatSync","readSync"],"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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AM,GAAG,CAAA;AAAA,EACzB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAOG,YAAA,CAAU,EAAE,CAAA,CAAE,IAAA;AAC3B,IAAA,IAAI,IAAA,KAAS,GAAG,OAAO,KAAA;AACvB,IAAA,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-OF2CLCTH.cjs","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","/**\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"]}