@theokit/sdk 5.14.0 → 5.15.1

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 (214) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/{agent-T34LCGQM.js → agent-66U5QCPF.js} +18 -17
  3. package/dist/{agent-T34LCGQM.js.map → agent-66U5QCPF.js.map} +1 -1
  4. package/dist/{agent-DExqjqYy.d.cts → agent-BL4kxgwq.d.cts} +30 -214
  5. package/dist/{agent-Dfw3VsIX.d.ts → agent-ByDx7K30.d.ts} +30 -214
  6. package/dist/{agent-TL4K7BTG.cjs → agent-CB27KF6O.cjs} +19 -18
  7. package/dist/{agent-TL4K7BTG.cjs.map → agent-CB27KF6O.cjs.map} +1 -1
  8. package/dist/agent.d.ts +2 -3
  9. package/dist/{batch-EP3FCL6D.js → batch-N2XDYZED.js} +4 -4
  10. package/dist/{batch-EP3FCL6D.js.map → batch-N2XDYZED.js.map} +1 -1
  11. package/dist/{batch-IZ5EDKJ5.cjs → batch-VFR2MAUE.cjs} +7 -7
  12. package/dist/{batch-IZ5EDKJ5.cjs.map → batch-VFR2MAUE.cjs.map} +1 -1
  13. package/dist/{chunk-ZOL3L4EH.js → chunk-26GI3OYA.js} +118 -21
  14. package/dist/chunk-26GI3OYA.js.map +1 -0
  15. package/dist/{chunk-2WY2OFSC.cjs → chunk-26UQG242.cjs} +616 -318
  16. package/dist/chunk-26UQG242.cjs.map +1 -0
  17. package/dist/{chunk-2C24NSNV.js → chunk-3BBTHFGJ.js} +3 -3
  18. package/dist/{chunk-2C24NSNV.js.map → chunk-3BBTHFGJ.js.map} +1 -1
  19. package/dist/{chunk-SNVYOX46.cjs → chunk-3E3VSMB6.cjs} +160 -63
  20. package/dist/chunk-3E3VSMB6.cjs.map +1 -0
  21. package/dist/{chunk-NP362THY.cjs → chunk-3F53FLQ7.cjs} +5 -7
  22. package/dist/chunk-3F53FLQ7.cjs.map +1 -0
  23. package/dist/{chunk-SXH37C7X.cjs → chunk-55LLQFHW.cjs} +6 -6
  24. package/dist/{chunk-SXH37C7X.cjs.map → chunk-55LLQFHW.cjs.map} +1 -1
  25. package/dist/{chunk-ZJAYFSVI.js → chunk-7ACS6P5Z.js} +5 -7
  26. package/dist/chunk-7ACS6P5Z.js.map +1 -0
  27. package/dist/{chunk-WDVG5R2Q.cjs → chunk-AUH2EVWY.cjs} +4 -3
  28. package/dist/chunk-AUH2EVWY.cjs.map +1 -0
  29. package/dist/chunk-BNEUB52I.cjs +55 -0
  30. package/dist/chunk-BNEUB52I.cjs.map +1 -0
  31. package/dist/chunk-BPL5CVZ5.js +53 -0
  32. package/dist/chunk-BPL5CVZ5.js.map +1 -0
  33. package/dist/{chunk-NVQSBRG6.js → chunk-CBBT42VX.js} +3 -3
  34. package/dist/{chunk-NVQSBRG6.js.map → chunk-CBBT42VX.js.map} +1 -1
  35. package/dist/chunk-CHKV2L2Y.cjs +416 -0
  36. package/dist/chunk-CHKV2L2Y.cjs.map +1 -0
  37. package/dist/{chunk-LXG6VL6R.cjs → chunk-FBIDOOJM.cjs} +3 -3
  38. package/dist/{chunk-LXG6VL6R.cjs.map → chunk-FBIDOOJM.cjs.map} +1 -1
  39. package/dist/{chunk-354F3OF5.js → chunk-FGGVSHDW.js} +3 -3
  40. package/dist/{chunk-354F3OF5.js.map → chunk-FGGVSHDW.js.map} +1 -1
  41. package/dist/{chunk-6OCJWGVD.cjs → chunk-FTXY4D44.cjs} +4 -4
  42. package/dist/{chunk-6OCJWGVD.cjs.map → chunk-FTXY4D44.cjs.map} +1 -1
  43. package/dist/chunk-INVEGVGO.js +405 -0
  44. package/dist/chunk-INVEGVGO.js.map +1 -0
  45. package/dist/{chunk-DF77RBF4.js → chunk-LCCT5ZXJ.js} +6 -6
  46. package/dist/{chunk-DF77RBF4.js.map → chunk-LCCT5ZXJ.js.map} +1 -1
  47. package/dist/{chunk-G7XBVM3T.cjs → chunk-MHUOVS5I.cjs} +5 -5
  48. package/dist/{chunk-G7XBVM3T.cjs.map → chunk-MHUOVS5I.cjs.map} +1 -1
  49. package/dist/{chunk-CWQPQTUZ.cjs → chunk-NEH3BPFD.cjs} +15 -15
  50. package/dist/{chunk-CWQPQTUZ.cjs.map → chunk-NEH3BPFD.cjs.map} +1 -1
  51. package/dist/{chunk-5AR6O7GW.js → chunk-NK5EOTDY.js} +3 -3
  52. package/dist/{chunk-5AR6O7GW.js.map → chunk-NK5EOTDY.js.map} +1 -1
  53. package/dist/{chunk-NAVUTK6X.js → chunk-O2RCS3SJ.js} +3 -3
  54. package/dist/{chunk-NAVUTK6X.js.map → chunk-O2RCS3SJ.js.map} +1 -1
  55. package/dist/{chunk-4TEGFMSP.cjs → chunk-P7QYG4RZ.cjs} +23 -15
  56. package/dist/chunk-P7QYG4RZ.cjs.map +1 -0
  57. package/dist/chunk-PPU2D4FZ.js +19 -0
  58. package/dist/chunk-PPU2D4FZ.js.map +1 -0
  59. package/dist/{chunk-AB4OPJLD.js → chunk-RGVMJU57.js} +3 -3
  60. package/dist/{chunk-AB4OPJLD.js.map → chunk-RGVMJU57.js.map} +1 -1
  61. package/dist/{chunk-4KBI37F3.cjs → chunk-RTDVSHJR.cjs} +5 -5
  62. package/dist/{chunk-4KBI37F3.cjs.map → chunk-RTDVSHJR.cjs.map} +1 -1
  63. package/dist/{chunk-CJN5CEI3.js → chunk-RZL2W4C3.js} +23 -15
  64. package/dist/chunk-RZL2W4C3.js.map +1 -0
  65. package/dist/chunk-SPEN7RJU.cjs +18 -0
  66. package/dist/{chunk-R5UQL2R5.cjs.map → chunk-SPEN7RJU.cjs.map} +1 -1
  67. package/dist/{chunk-BZK5QL3N.cjs → chunk-TRPRTZEH.cjs} +4 -4
  68. package/dist/{chunk-BZK5QL3N.cjs.map → chunk-TRPRTZEH.cjs.map} +1 -1
  69. package/dist/{chunk-ZF2LDKQQ.cjs → chunk-U3DW3WDE.cjs} +9 -8
  70. package/dist/chunk-U3DW3WDE.cjs.map +1 -0
  71. package/dist/{chunk-H7G65PNI.js → chunk-VCQ37TC5.js} +3 -3
  72. package/dist/{chunk-H7G65PNI.js.map → chunk-VCQ37TC5.js.map} +1 -1
  73. package/dist/{chunk-3ONIVO2I.js → chunk-VNRNZ3WI.js} +3 -3
  74. package/dist/{chunk-3ONIVO2I.js.map → chunk-VNRNZ3WI.js.map} +1 -1
  75. package/dist/{chunk-SDZ4XDWS.cjs → chunk-VWYFGE27.cjs} +9 -9
  76. package/dist/{chunk-SDZ4XDWS.cjs.map → chunk-VWYFGE27.cjs.map} +1 -1
  77. package/dist/{chunk-RN3XDZGS.js → chunk-WM646HEN.js} +4 -3
  78. package/dist/chunk-WM646HEN.js.map +1 -0
  79. package/dist/chunk-X7CE7Y5W.js +305 -0
  80. package/dist/chunk-X7CE7Y5W.js.map +1 -0
  81. package/dist/{chunk-CGH4BCIY.cjs → chunk-XE3CAY6Z.cjs} +5 -5
  82. package/dist/{chunk-CGH4BCIY.cjs.map → chunk-XE3CAY6Z.cjs.map} +1 -1
  83. package/dist/chunk-XOU3CL7S.cjs +312 -0
  84. package/dist/chunk-XOU3CL7S.cjs.map +1 -0
  85. package/dist/{chunk-ULEK4OM4.js → chunk-YKNBTHMD.js} +3 -3
  86. package/dist/{chunk-ULEK4OM4.js.map → chunk-YKNBTHMD.js.map} +1 -1
  87. package/dist/{chunk-GARVAUCU.js → chunk-ZQWRUJHE.js} +534 -236
  88. package/dist/chunk-ZQWRUJHE.js.map +1 -0
  89. package/dist/{compact-session-D2MQDB6G.cjs → compact-session-CHBJOYWP.cjs} +16 -16
  90. package/dist/{compact-session-D2MQDB6G.cjs.map → compact-session-CHBJOYWP.cjs.map} +1 -1
  91. package/dist/{compact-session-N2PPHQO6.js → compact-session-F3J3FMEU.js} +7 -7
  92. package/dist/{compact-session-N2PPHQO6.js.map → compact-session-F3J3FMEU.js.map} +1 -1
  93. package/dist/{cron-CK2v0VWA.d.cts → cron-B7KH9sHW.d.cts} +2 -2
  94. package/dist/{cron-BubDpFJG.d.ts → cron-FEO7UAQF.d.ts} +2 -2
  95. package/dist/cron.cjs +18 -17
  96. package/dist/cron.d.cts +4 -3
  97. package/dist/cron.d.ts +4 -3
  98. package/dist/cron.js +17 -16
  99. package/dist/eval.cjs +17 -16
  100. package/dist/eval.cjs.map +1 -1
  101. package/dist/eval.js +16 -15
  102. package/dist/eval.js.map +1 -1
  103. package/dist/fs-session-store-CYNTEPJZ.cjs +20 -0
  104. package/dist/{fs-session-store-S2AXVJIX.cjs.map → fs-session-store-CYNTEPJZ.cjs.map} +1 -1
  105. package/dist/fs-session-store-MYQEVUFL.js +11 -0
  106. package/dist/{fs-session-store-6ZCCJX3K.js.map → fs-session-store-MYQEVUFL.js.map} +1 -1
  107. package/dist/{index-manager-HO456AVW.cjs → index-manager-2KH75BRW.cjs} +7 -7
  108. package/dist/{index-manager-HO456AVW.cjs.map → index-manager-2KH75BRW.cjs.map} +1 -1
  109. package/dist/{index-manager-QDH56FER.js → index-manager-NF2WRLOU.js} +6 -6
  110. package/dist/{index-manager-QDH56FER.js.map → index-manager-NF2WRLOU.js.map} +1 -1
  111. package/dist/index.cjs +66 -262
  112. package/dist/index.cjs.map +1 -1
  113. package/dist/index.d.cts +10 -46
  114. package/dist/index.d.ts +10 -46
  115. package/dist/index.js +27 -227
  116. package/dist/index.js.map +1 -1
  117. package/dist/{inject-session-J26SHHIO.js → inject-session-LC2TROHM.js} +3 -3
  118. package/dist/{inject-session-J26SHHIO.js.map → inject-session-LC2TROHM.js.map} +1 -1
  119. package/dist/{inject-session-3ICZIJ2N.cjs → inject-session-T4RXANG3.cjs} +4 -4
  120. package/dist/{inject-session-3ICZIJ2N.cjs.map → inject-session-T4RXANG3.cjs.map} +1 -1
  121. package/dist/internal/agent-loop/doom-loop-tracker.d.ts +3 -0
  122. package/dist/internal/agent-loop/types.d.ts +6 -0
  123. package/dist/internal/error-mappers/anthropic.d.ts +3 -0
  124. package/dist/internal/error-mappers/openai-compatible.d.ts +2 -3
  125. package/dist/internal/llm/hermes-tool-extract.d.ts +2 -0
  126. package/dist/internal/local-agent/local-agent-dispatch.d.ts +3 -1
  127. package/dist/internal/local-agent/send-queue.d.ts +31 -0
  128. package/dist/internal/mcp/client.d.ts +2 -0
  129. package/dist/internal/mcp/oauth-bearer.d.ts +2 -0
  130. package/dist/internal/memory/adapters/index.cjs +3 -3
  131. package/dist/internal/memory/adapters/index.js +2 -2
  132. package/dist/internal/memory/dreaming/phases.d.ts +15 -0
  133. package/dist/internal/memory/dreaming/run.d.ts +29 -0
  134. package/dist/internal/memory/sdk-memory-peer-loader.d.ts +2 -0
  135. package/dist/internal/memory/storage/index.cjs +51 -35
  136. package/dist/internal/memory/storage/index.d.cts +2 -0
  137. package/dist/internal/memory/storage/index.d.ts +2 -0
  138. package/dist/internal/memory/storage/index.js +4 -4
  139. package/dist/internal/persistence/cwd-mutex.d.cts +4 -2
  140. package/dist/internal/persistence/cwd-mutex.d.ts +4 -2
  141. package/dist/internal/persistence/index.cjs +4 -4
  142. package/dist/internal/persistence/index.js +2 -2
  143. package/dist/internal/persistence/sqlite-session-store.d.cts +25 -0
  144. package/dist/internal/persistence/sqlite-session-store.d.ts +25 -0
  145. package/dist/internal/providers/registry.d.ts +5 -1
  146. package/dist/mcp-auth.cjs +25 -307
  147. package/dist/mcp-auth.cjs.map +1 -1
  148. package/dist/mcp-auth.js +5 -305
  149. package/dist/mcp-auth.js.map +1 -1
  150. package/dist/models.cjs +9 -9
  151. package/dist/models.js +2 -2
  152. package/dist/persistence.cjs +9 -4
  153. package/dist/persistence.cjs.map +1 -1
  154. package/dist/persistence.d.cts +744 -40
  155. package/dist/persistence.d.ts +744 -40
  156. package/dist/persistence.js +3 -2
  157. package/dist/persistence.js.map +1 -1
  158. package/dist/providers.cjs +4 -4
  159. package/dist/providers.js +2 -2
  160. package/dist/sandbox/docker-sandbox.d.cts +58 -0
  161. package/dist/sandbox/docker-sandbox.d.ts +58 -0
  162. package/dist/sandbox/index.cjs +129 -1
  163. package/dist/sandbox/index.cjs.map +1 -1
  164. package/dist/sandbox/index.d.cts +1 -0
  165. package/dist/sandbox/index.d.ts +1 -0
  166. package/dist/sandbox/index.js +132 -5
  167. package/dist/sandbox/index.js.map +1 -1
  168. package/dist/{sdk-agent-DwzHcuxy.d.cts → sdk-agent-BA_6_wtc.d.cts} +30 -2
  169. package/dist/{sdk-agent-a3fW1xUK.d.ts → sdk-agent-CnwPODYH.d.ts} +30 -2
  170. package/dist/session-store-Dh07jr9N.d.cts +209 -0
  171. package/dist/session-store-Dh07jr9N.d.ts +209 -0
  172. package/dist/sqlite-session-store-BbcpKY1L.d.ts +64 -0
  173. package/dist/sqlite-session-store-TKXtT4ON.d.cts +64 -0
  174. package/dist/subagents-loader-KLWF4QPD.cjs +16 -0
  175. package/dist/{subagents-loader-TXOA5EJJ.cjs.map → subagents-loader-KLWF4QPD.cjs.map} +1 -1
  176. package/dist/subagents-loader-SXETS2F2.js +7 -0
  177. package/dist/{subagents-loader-Z744TAKD.js.map → subagents-loader-SXETS2F2.js.map} +1 -1
  178. package/dist/subagents-loader.cjs +2 -2
  179. package/dist/subagents-loader.d.cts +3 -2
  180. package/dist/subagents-loader.d.ts +3 -2
  181. package/dist/subagents-loader.js +1 -1
  182. package/dist/types/agent.d.ts +14 -1
  183. package/dist/types/budget-tracker.d.ts +6 -2
  184. package/dist/types/hooks.d.ts +7 -1
  185. package/dist/types/mcp.d.ts +14 -0
  186. package/dist/types/run.d.ts +15 -1
  187. package/dist/workflow.d.cts +1 -1
  188. package/dist/workflow.d.ts +1 -1
  189. package/docs/adr/mutation-testing-scope.md +12 -2
  190. package/docs/error-codes.md +41 -40
  191. package/docs/harness-capability-map.md +32 -6
  192. package/package.json +1 -1
  193. package/dist/chunk-2WY2OFSC.cjs.map +0 -1
  194. package/dist/chunk-4TEGFMSP.cjs.map +0 -1
  195. package/dist/chunk-6CXRYPG7.cjs +0 -211
  196. package/dist/chunk-6CXRYPG7.cjs.map +0 -1
  197. package/dist/chunk-CJN5CEI3.js.map +0 -1
  198. package/dist/chunk-GARVAUCU.js.map +0 -1
  199. package/dist/chunk-MSEL5E5P.js +0 -204
  200. package/dist/chunk-MSEL5E5P.js.map +0 -1
  201. package/dist/chunk-NP362THY.cjs.map +0 -1
  202. package/dist/chunk-Q5EWJPRY.js +0 -18
  203. package/dist/chunk-Q5EWJPRY.js.map +0 -1
  204. package/dist/chunk-R5UQL2R5.cjs +0 -18
  205. package/dist/chunk-RN3XDZGS.js.map +0 -1
  206. package/dist/chunk-SNVYOX46.cjs.map +0 -1
  207. package/dist/chunk-WDVG5R2Q.cjs.map +0 -1
  208. package/dist/chunk-ZF2LDKQQ.cjs.map +0 -1
  209. package/dist/chunk-ZJAYFSVI.js.map +0 -1
  210. package/dist/chunk-ZOL3L4EH.js.map +0 -1
  211. package/dist/fs-session-store-6ZCCJX3K.js +0 -11
  212. package/dist/fs-session-store-S2AXVJIX.cjs +0 -20
  213. package/dist/subagents-loader-TXOA5EJJ.cjs +0 -16
  214. package/dist/subagents-loader-Z744TAKD.js +0 -7
@@ -1,204 +0,0 @@
1
- import { defaultIndexPath, openMemoryDb, resolveMemoryRoot, lanceStoragePath, LanceIndex } from './chunk-DF77RBF4.js';
2
- import { replaceFileAtomic } from './chunk-M4U24U6G.js';
3
- import { ConfigurationError } from './chunk-TNFOU6SB.js';
4
- import { redactSecrets } from './chunk-3OY6H3I7.js';
5
- import { createHash } from 'crypto';
6
- import { readFile } from 'fs/promises';
7
- import { join } from 'path';
8
- import { existsSync, rmSync, mkdirSync, renameSync } from 'fs';
9
-
10
- function diaryPath(root) {
11
- return join(root, "dream-diary.md");
12
- }
13
- function renderDiaryEntry(entry) {
14
- const stamp = new Date(entry.timestampMs).toISOString();
15
- const hash = entryHash(entry).slice(0, 8);
16
- return [
17
- `## ${stamp}`,
18
- "",
19
- `- entry-hash: ${hash}`,
20
- `- facts before: ${entry.factsBefore}`,
21
- `- facts after: ${entry.factsAfter}`,
22
- `- duplicates removed: ${entry.duplicatesRemoved}`,
23
- `- clusters created: ${entry.clustersCreated}`,
24
- `- notes written: ${entry.notesWritten}`,
25
- ""
26
- ].join("\n");
27
- }
28
- async function appendDiaryEntry(root, entry) {
29
- const path = diaryPath(root);
30
- let raw = "";
31
- try {
32
- raw = await readFile(path, "utf8");
33
- } catch {
34
- raw = "# Dream Diary\n\n";
35
- }
36
- const next = `${raw.endsWith("\n") ? raw : `${raw}
37
- `}${renderDiaryEntry(entry)}`;
38
- await replaceFileAtomic(path, next);
39
- }
40
- function entryHash(entry) {
41
- return createHash("sha256").update(
42
- [
43
- entry.factsBefore,
44
- entry.factsAfter,
45
- entry.duplicatesRemoved,
46
- entry.clustersCreated,
47
- entry.notesWritten
48
- ].join("|")
49
- ).digest("hex");
50
- }
51
- async function readAllSqliteFacts(root) {
52
- const dbPath = defaultIndexPath(root);
53
- if (!existsSync(dbPath)) return [];
54
- const db = await openMemoryDb({ filePath: dbPath });
55
- try {
56
- const stmt = db.prepare("SELECT id, path, source, start_line, end_line, text FROM chunks");
57
- const rows = stmt.all();
58
- return rows.map((r) => ({
59
- ...r,
60
- namespace: "default",
61
- scope: "agent",
62
- user_id: "default"
63
- }));
64
- } finally {
65
- db.close();
66
- }
67
- }
68
- function nfcEqual(a, b) {
69
- return a.normalize("NFC") === b.normalize("NFC");
70
- }
71
- function assertUsableBatchSize(batchSize) {
72
- if (batchSize === void 0) return;
73
- if (!Number.isInteger(batchSize) || batchSize < 1) {
74
- throw new ConfigurationError(
75
- `migrateSqliteToLance: batchSize must be a whole number of at least 1; received ${String(batchSize)}.`,
76
- { code: "invalid_batch_size" }
77
- );
78
- }
79
- }
80
- async function migrateSqliteToLance(opts) {
81
- assertUsableBatchSize(opts.batchSize);
82
- const cwd = opts.cwd;
83
- const memoryRoot = resolveMemoryRoot(cwd, { directory: opts.directory });
84
- const finalPath = lanceStoragePath(memoryRoot);
85
- const newPath = join(memoryRoot, "lance-new");
86
- const rawLog = opts.logger ?? ((m) => console.log(m));
87
- const log = (m) => rawLog(redactSecrets(m));
88
- if (existsSync(finalPath)) {
89
- throw new ConfigurationError(
90
- `Destination already exists: ${finalPath}. Remove it manually (\`rm -rf ${finalPath}\`) and re-run.`,
91
- { code: "migration_destination_exists" }
92
- );
93
- }
94
- if (existsSync(newPath)) {
95
- log(`Removing stale ${newPath} from a previous run...`);
96
- rmSync(newPath, { recursive: true, force: true });
97
- }
98
- log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);
99
- const sqliteFacts = await readAllSqliteFacts(memoryRoot);
100
- log(`SQLite has ${sqliteFacts.length} facts.`);
101
- if (sqliteFacts.length === 0) {
102
- return {
103
- countSqlite: 0,
104
- countLance: 0,
105
- validated: true,
106
- sampleComparisons: [],
107
- lancePath: finalPath,
108
- committed: false
109
- };
110
- }
111
- const placeholderEmbedding = {
112
- id: "migration-placeholder",
113
- model: "deterministic-hash",
114
- dimension: 8,
115
- embed: async (texts) => {
116
- return texts.map((t) => {
117
- const arr = new Array(8).fill(0);
118
- for (let i = 0; i < t.length; i += 1) {
119
- arr[i % 8] += t.charCodeAt(i);
120
- }
121
- return arr.map((x) => x / 1e3);
122
- });
123
- },
124
- stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 })
125
- };
126
- mkdirSync(newPath, { recursive: true });
127
- log(`Writing Lance index to ${newPath} ...`);
128
- const lance = await LanceIndex.open({
129
- cwd,
130
- embedding: placeholderEmbedding,
131
- storagePath: newPath
132
- });
133
- const batchSize = opts.batchSize ?? 100;
134
- for (let i = 0; i < sqliteFacts.length; i += batchSize) {
135
- const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({
136
- id: f.id,
137
- text: f.text,
138
- source: f.source,
139
- namespace: f.namespace ?? "default",
140
- scope: f.scope ?? "agent",
141
- user_id: f.user_id ?? "default",
142
- timestamp: 0
143
- }));
144
- await lance.addFacts(batch);
145
- log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);
146
- }
147
- const lanceCount = await lance.countFacts("default");
148
- log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);
149
- const sampleSize = Math.min(10, sqliteFacts.length);
150
- const sampleComparisons = [];
151
- for (let i = 0; i < sampleSize; i += 1) {
152
- const sqliteFact = sqliteFacts[Math.floor(i * sqliteFacts.length / sampleSize)];
153
- if (sqliteFact === void 0) continue;
154
- const hits = await lance.search(sqliteFact.text, {
155
- namespace: sqliteFact.namespace ?? "default",
156
- limit: 1
157
- });
158
- const hit = hits[0];
159
- const match = hit !== void 0 && nfcEqual(hit.text, sqliteFact.text);
160
- sampleComparisons.push({ id: sqliteFact.id, match });
161
- }
162
- const allMatch = sampleComparisons.every((c) => c.match);
163
- const countMatch = lanceCount === sqliteFacts.length;
164
- const validated = allMatch && countMatch;
165
- await lance.close();
166
- if (opts.dryRun === true) {
167
- log("Dry-run mode \u2014 discarding Lance staging dir.");
168
- rmSync(newPath, { recursive: true, force: true });
169
- return {
170
- countSqlite: sqliteFacts.length,
171
- countLance: lanceCount,
172
- validated,
173
- sampleComparisons,
174
- lancePath: finalPath,
175
- committed: false
176
- };
177
- }
178
- if (!validated) {
179
- log("Validation FAILED \u2014 leaving SQLite intact, removing Lance staging dir.");
180
- rmSync(newPath, { recursive: true, force: true });
181
- return {
182
- countSqlite: sqliteFacts.length,
183
- countLance: lanceCount,
184
- validated: false,
185
- sampleComparisons,
186
- lancePath: finalPath,
187
- committed: false
188
- };
189
- }
190
- renameSync(newPath, finalPath);
191
- log(`Migration committed to ${finalPath}.`);
192
- return {
193
- countSqlite: sqliteFacts.length,
194
- countLance: lanceCount,
195
- validated: true,
196
- sampleComparisons,
197
- lancePath: finalPath,
198
- committed: true
199
- };
200
- }
201
-
202
- export { appendDiaryEntry, diaryPath, entryHash, migrateSqliteToLance, readAllSqliteFacts, renderDiaryEntry };
203
- //# sourceMappingURL=chunk-MSEL5E5P.js.map
204
- //# sourceMappingURL=chunk-MSEL5E5P.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../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AAA,MACzB,UAAA,EAAY,UAAA;AAAA,MACZ,SAAA;AAAA,MACA,iBAAA;AAAA,MACA,SAAA,EAAW,SAAA;AAAA,MACX,SAAA,EAAW;AAAA,KACb;AAAA,EACF;AAEA,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,GAAA,CAAI,6EAAwE,CAAA;AAC5E,IAAA,MAAA,CAAO,SAAS,EAAE,SAAA,EAAW,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAChD,IAAA,OAAO;AAAA,MACL,aAAa,WAAA,CAAY,MAAA;AAAA,MACzB,UAAA,EAAY,UAAA;AAAA,MACZ,SAAA,EAAW,KAAA;AAAA,MACX,iBAAA;AAAA,MACA,SAAA,EAAW,SAAA;AAAA,MACX,SAAA,EAAW;AAAA,KACb;AAAA,EACF;AAGA,EAAA,UAAA,CAAW,SAAS,SAAS,CAAA;AAC7B,EAAA,GAAA,CAAI,CAAA,uBAAA,EAA0B,SAAS,CAAA,CAAA,CAAG,CAAA;AAC1C,EAAA,OAAO;AAAA,IACL,aAAa,WAAA,CAAY,MAAA;AAAA,IACzB,UAAA,EAAY,UAAA;AAAA,IACZ,SAAA,EAAW,IAAA;AAAA,IACX,iBAAA;AAAA,IACA,SAAA,EAAW,SAAA;AAAA,IACX,SAAA,EAAW;AAAA,GACb;AACF","file":"chunk-MSEL5E5P.js","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { replaceFileAtomic } from \"../../persistence/atomic-write.js\";\nimport type { MemoryRoot } from \"../storage/memory-root.js\";\n\n/**\n * Dream-diary append (ADR D7).\n *\n * Diary lives at `.theokit/memory/dream-diary.md` and grows with one entry\n * per sweep. Each entry is content-hashed so the same input produces the\n * same entry — idempotency contract.\n *\n * Writes go through `replaceFileAtomic` (EC-3 of edge-case review) so a\n * crash mid-write can never leave a half-written diary.\n *\n * Shared with `@theokit/sdk-memory`; see the memory-store barrel.\n */\n\nexport interface DiaryEntry {\n timestampMs: number;\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n}\n\n/** `<memory root>/dream-diary.md`. Takes the RESOLVED ROOT — see `storage/memory-root.ts` (#463). */\nexport function diaryPath(root: MemoryRoot): string {\n return join(root, \"dream-diary.md\");\n}\n\n/**\n * One diary entry as the markdown that gets appended: a timestamp heading, the short entry hash,\n * and the counts the sweep produced. The hash is what makes a re-run recognisable as the same\n * sweep rather than a new one.\n */\nexport function renderDiaryEntry(entry: DiaryEntry): string {\n const stamp = new Date(entry.timestampMs).toISOString();\n const hash = entryHash(entry).slice(0, 8);\n return [\n `## ${stamp}`,\n \"\",\n `- entry-hash: ${hash}`,\n `- facts before: ${entry.factsBefore}`,\n `- facts after: ${entry.factsAfter}`,\n `- duplicates removed: ${entry.duplicatesRemoved}`,\n `- clusters created: ${entry.clustersCreated}`,\n `- notes written: ${entry.notesWritten}`,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Append one sweep's entry to `<memory root>/dream-diary.md`, creating the file with its header\n * when this is the first sweep. The diary is a human-readable record of what dreaming changed —\n * consolidations are otherwise invisible, because they alter the notes rather than announce\n * themselves.\n */\nexport async function appendDiaryEntry(root: MemoryRoot, entry: DiaryEntry): Promise<void> {\n const path = diaryPath(root);\n let raw = \"\";\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n raw = \"# Dream Diary\\n\\n\";\n }\n const next = `${raw.endsWith(\"\\n\") ? raw : `${raw}\\n`}${renderDiaryEntry(entry)}`;\n await replaceFileAtomic(path, next);\n}\n\n/**\n * A stable hash of one entry's counts, so two sweeps that did the same work read as the same work.\n * Rendered truncated in the entry; the full value is what callers compare.\n */\nexport function entryHash(entry: DiaryEntry): string {\n return createHash(\"sha256\")\n .update(\n [\n entry.factsBefore,\n entry.factsAfter,\n entry.duplicatesRemoved,\n entry.clustersCreated,\n entry.notesWritten,\n ].join(\"|\"),\n )\n .digest(\"hex\");\n}\n","import { existsSync, mkdirSync, renameSync, rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\nimport { defaultIndexPath, openMemoryDb } from \"./index-db.js\";\nimport { LanceIndex, lanceStoragePath } from \"./lance-index.js\";\nimport { type MemoryRoot, resolveMemoryRoot } from \"./storage/memory-root.js\";\n\n/**\n * Migrate Memory.index from SQLite to LanceDB (ADR D44).\n *\n * EC-3 MUST FIX: validation uses NFC unicode normalization on both sides.\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel (#463).\n */\n\nexport interface MigrateOptions {\n cwd: string;\n /**\n * Absolute path (or `~/`-prefixed) of the memory root to migrate, when the agent that wrote it\n * set `memory.directory`. Defaults to `<cwd>/.theokit/memory` (#463).\n */\n directory?: string;\n dryRun?: boolean;\n batchSize?: number;\n /** Inject for tests; defaults to console.log. */\n logger?: (msg: string) => void;\n}\n\nexport interface MigrateResult {\n countSqlite: number;\n countLance: number;\n /** Set when validation succeeded (or dryRun); false on validation failure. */\n validated: boolean;\n /** Per-fact compare results (size = sample count, up to 10). */\n sampleComparisons: ReadonlyArray<{ id: string; match: boolean }>;\n /** Lance storage location (final, after migration). */\n lancePath: string;\n /** Was the migration committed (false for dry-run). */\n committed: boolean;\n}\n\n/**\n * One row of the SQLite memory index, as the Lance migration reads it: the chunk plus the tenant\n * columns the target table needs. Shared with `@theokit/sdk-memory`, which migrates the same table.\n */\nexport interface SqliteFactRow {\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n namespace?: string | null;\n scope?: string | null;\n user_id?: string | null;\n}\n\n/**\n * Read all facts from the SQLite memory index. Returns empty array if the\n * SQLite db file does not exist (workspace never used Memory).\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel, so it carries no visibility\n * tag — naming that tag in this block would delete the function below it (#463).\n */\nexport async function readAllSqliteFacts(root: MemoryRoot): Promise<SqliteFactRow[]> {\n const dbPath = defaultIndexPath(root);\n if (!existsSync(dbPath)) return [];\n const db = await openMemoryDb({ filePath: dbPath });\n try {\n // SQLite schema: chunks table holds the facts. Schema may vary; we\n // probe column existence and fall back to safe defaults.\n const stmt = db.prepare(\"SELECT id, path, source, start_line, end_line, text FROM chunks\");\n const rows = stmt.all() as Array<{\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n }>;\n return rows.map((r) => ({\n ...r,\n namespace: \"default\",\n scope: \"agent\",\n user_id: \"default\",\n }));\n } finally {\n db.close();\n }\n}\n\n/**\n * Compare two strings via NFC normalization (EC-3 MUST FIX). Required\n * because SQLite/Lance native bindings can normalize unicode differently\n * (NFC vs NFD), producing false negatives on facts with accents/emojis.\n *\n * @internal\n */\nfunction nfcEqual(a: string, b: string): boolean {\n return a.normalize(\"NFC\") === b.normalize(\"NFC\");\n}\n\n/**\n * Refuse a `batchSize` the loop below cannot make progress with, before anything is migrated.\n *\n * The loop is `for (let i = 0; i < facts.length; i += batchSize)`, so the three ways this goes wrong\n * are all silent and all different:\n *\n * - 0 or negative: `i` never advances past the guard. The migration SPINS FOREVER, calling\n * `addFacts([])` and writing a \"Migrated x/y\" line every iteration — a hang with unbounded output,\n * which is the worst shape a failure can take because it looks like work.\n * - NaN (`Number(\"abc\")`): `i += NaN` makes the guard false on the first check, zero facts move, and\n * the caller is told \"Validation FAILED. SQLite preserved.\" A typo in an argument is reported as a\n * migration failure.\n * - a fraction: `slice` truncates and the loop still terminates, but the batch boundaries stop\n * matching the number the caller asked for.\n *\n * Validated HERE rather than only in the CLI that motivated the finding, because the CLI is a wrapper\n * over this function and a programmatic caller reaches it with no wrapper at all.\n *\n * @internal\n */\nfunction assertUsableBatchSize(batchSize: number | undefined): void {\n if (batchSize === undefined) return;\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new ConfigurationError(\n `migrateSqliteToLance: batchSize must be a whole number of at least 1; received ${String(batchSize)}.`,\n { code: \"invalid_batch_size\" },\n );\n }\n}\n\n/**\n * Run the migration. Writes Lance to `<cwd>/.theokit/memory/lance-new/`\n * first, validates round-trip, then renames to `lance/` on success.\n * SQLite db is preserved (CLI prompts user to delete).\n *\n * @internal\n */\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: migration is a single transaction (read → write → validate → commit-or-rollback); splitting harms atomicity reasoning.\nexport async function migrateSqliteToLance(opts: MigrateOptions): Promise<MigrateResult> {\n assertUsableBatchSize(opts.batchSize);\n const cwd = opts.cwd;\n // One resolution, reused by every path this migration touches (#463).\n const memoryRoot = resolveMemoryRoot(cwd, { directory: opts.directory });\n const finalPath = lanceStoragePath(memoryRoot);\n const newPath = join(memoryRoot, \"lance-new\");\n // T1.4 (ADR D68): wrap logger so any fact text containing secrets is\n // masked before reaching the destination (console or user-supplied sink).\n // Caller-supplied loggers cannot bypass — by design (D70).\n const rawLog = opts.logger ?? ((m: string) => console.log(m));\n const log = (m: string) => rawLog(redactSecrets(m));\n\n // EC: destination exists → typed error.\n if (existsSync(finalPath)) {\n throw new ConfigurationError(\n `Destination already exists: ${finalPath}. Remove it manually (\\`rm -rf ${finalPath}\\`) and re-run.`,\n { code: \"migration_destination_exists\" },\n );\n }\n if (existsSync(newPath)) {\n // Leftover from a previous failed/interrupted migration. Safe to delete.\n log(`Removing stale ${newPath} from a previous run...`);\n rmSync(newPath, { recursive: true, force: true });\n }\n\n log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);\n const sqliteFacts = await readAllSqliteFacts(memoryRoot);\n log(`SQLite has ${sqliteFacts.length} facts.`);\n if (sqliteFacts.length === 0) {\n return {\n countSqlite: 0,\n countLance: 0,\n validated: true,\n sampleComparisons: [],\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Reuse the embedding runtime configured in the workspace? For v1.2 we\n // require the caller to pass embedding explicitly via env. The migration\n // path is documented as: \"set OPENAI_API_KEY (or similar) before running.\"\n // Here we ship a placeholder embedder that uses a deterministic\n // content-hash — sufficient for migration validation; consumers should\n // re-embed on first real query after migration if needed.\n const placeholderEmbedding = {\n id: \"migration-placeholder\",\n model: \"deterministic-hash\",\n dimension: 8,\n embed: async (texts: ReadonlyArray<string>) => {\n // Simple deterministic hash → 8-dim vector (migration validation only).\n return texts.map((t) => {\n const arr = new Array(8).fill(0);\n for (let i = 0; i < t.length; i += 1) {\n arr[i % 8] += t.charCodeAt(i);\n }\n return arr.map((x) => x / 1000);\n });\n },\n stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 }),\n };\n\n mkdirSync(newPath, { recursive: true });\n log(`Writing Lance index to ${newPath} ...`);\n\n const lance = await LanceIndex.open({\n cwd,\n embedding: placeholderEmbedding,\n storagePath: newPath,\n });\n\n const batchSize = opts.batchSize ?? 100;\n for (let i = 0; i < sqliteFacts.length; i += batchSize) {\n const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({\n id: f.id,\n text: f.text,\n source: f.source,\n namespace: f.namespace ?? \"default\",\n scope: f.scope ?? \"agent\",\n user_id: f.user_id ?? \"default\",\n timestamp: 0,\n }));\n await lance.addFacts(batch);\n log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);\n }\n\n // Validation: count + sample compare (10 random) with NFC normalization.\n const lanceCount = await lance.countFacts(\"default\");\n log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);\n\n const sampleSize = Math.min(10, sqliteFacts.length);\n const sampleComparisons: { id: string; match: boolean }[] = [];\n for (let i = 0; i < sampleSize; i += 1) {\n const sqliteFact = sqliteFacts[Math.floor((i * sqliteFacts.length) / sampleSize)];\n if (sqliteFact === undefined) continue;\n // Search Lance for this fact's text — best-effort round-trip.\n const hits = await lance.search(sqliteFact.text, {\n namespace: sqliteFact.namespace ?? \"default\",\n limit: 1,\n });\n // EC-3: compare with NFC normalization.\n const hit = hits[0];\n const match = hit !== undefined && nfcEqual(hit.text, sqliteFact.text);\n sampleComparisons.push({ id: sqliteFact.id, match });\n }\n\n const allMatch = sampleComparisons.every((c) => c.match);\n const countMatch = lanceCount === sqliteFacts.length;\n const validated = allMatch && countMatch;\n\n await lance.close();\n\n if (opts.dryRun === true) {\n log(\"Dry-run mode — discarding Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n if (!validated) {\n log(\"Validation FAILED — leaving SQLite intact, removing Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: false,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Atomic commit via rename.\n renameSync(newPath, finalPath);\n log(`Migration committed to ${finalPath}.`);\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: true,\n sampleComparisons,\n lancePath: finalPath,\n committed: true,\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/error-mappers/shared.ts","../src/internal/error-mappers/openai-compatible.ts"],"names":["redactSecrets","AuthenticationError","RateLimitError","ConfigurationError","NetworkError","UnknownAgentError"],"mappings":";;;;;;AAeA,IAAM,aAAA,GAAgB,IAAA;AAUf,SAAS,gBAAgB,OAAA,EAAkD;AAChF,EAAA,IAAI,OAAA,KAAY,QAAW,OAAO,MAAA;AAClC,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,aAAa,CAAA;AACrC,EAAA,IAAI,GAAA,KAAQ,MAAM,OAAO,MAAA;AACzB,EAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,EAAA,IAAI,MAAA,CAAO,SAAS,CAAC,CAAA,IAAK,KAAK,CAAA,EAAG,OAAO,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA;AAEpD,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,GAAG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S,uBAAuB,OAAA,EAAwC;AACtE,EAAA,MAAM,OAAO,eAAA,CAAgB,IAAA;AAAA,IAAK,CAAC,EAAE,SAAA,EAAU,KAC7C,SAAA,CAAU,IAAA,CAAK,CAAC,QAAA,KAAa,OAAA,CAAQ,QAAA,CAAS,QAAQ,CAAC;AAAA,GACzD;AACA,EAAA,OAAO,IAAA,EAAM,IAAA;AACf;AAEA,SAAS,aAAA,CACP,UAAA,EACA,MAAA,EACA,IAAA,EACA,MAAA,EACQ;AACR,EAAA,MAAM,OAAO,CAAA,EAAG,UAAU,CAAA,YAAA,EAAe,IAAI,UAAU,MAAM,CAAA,CAAA,CAAA;AAC7D,EAAA,OAAO,MAAA,KAAW,UAAa,MAAA,KAAW,EAAA,GAAK,OAAO,CAAA,EAAG,IAAI,KAAK,MAAM,CAAA,CAAA;AAC1E","file":"chunk-NP362THY.cjs","sourcesContent":["/**\nimport type { ErrorCode } from \"../../errors.js\";\n * Helpers shared between provider HTTP error mappers (ADR D67).\n *\n * Extracted to dedupe identical logic in `anthropic.ts` and\n * `openai-compatible.ts` — retry-after parsing, raw-body truncation,\n * and metadata assembly are dialect-agnostic.\n *\n * @internal\n */\n\nimport type { ErrorCode, ErrorMetadata } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\n\n/** Longest `ErrorMetadata.raw`, in UTF-16 code units, before the `…` suffix. */\nconst RAW_MAX_CHARS = 2048;\n\n/**\n * Parse the `Retry-After` header (RFC 7231) into seconds. Both forms are\n * supported: numeric-seconds (`Retry-After: 30`) and HTTP-date\n * (`Retry-After: Wed, 21 Oct 2025 07:28:00 GMT` → seconds until that instant,\n * clamped at 0 for a past date). Garbage / missing header → `undefined`.\n *\n * @internal\n */\nexport function parseRetryAfter(headers: Headers | undefined): number | undefined {\n if (headers === undefined) return undefined;\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return Math.ceil(n);\n // HTTP-date form — seconds until the given instant (0 if already elapsed).\n const dateMs = Date.parse(raw);\n if (Number.isFinite(dateMs)) return Math.max(0, Math.ceil((dateMs - Date.now()) / 1000));\n return undefined;\n}\n\n/**\n * Redact known credential patterns in the raw response body, then\n * cut the redacted text to 2048 characters (UTF-16 code units), so it can ride inside\n * `ErrorMetadata.raw` without ballooning logs OR leaking tokens.\n * Returns `undefined` for null/undefined input.\n *\n * Redaction runs first: a pattern can only mask a credential it sees\n * whole, and cutting first left a key straddling the cut too short for\n * its pattern, so its leading fragment reached `raw` in clear (B-540).\n * The `…` suffix is added exactly when text was dropped.\n *\n * Redaction sees the whole body, however long. Any bound on what it reads\n * brings the edge back: a credential cut by the bound matches nothing, and\n * redaction of the text before it can pull the clear fragment inside the\n * cut, and no fixed margin is enough because JWTs and PEM blocks have no\n * length bound (plan D1, review round 2). The builtin patterns were timed\n * on hostile input and the two that were not linear were fixed (B-544,\n * B-554), so the cost grows with the body's length; a pattern\n * registered with `Security.addPattern` sees the whole body too and\n * should stay linear in its input. The cut never splits a surrogate pair.\n *\n * Post T1.1 (secret-redaction-discipline, ADR D68): every error metadata\n * goes through `redactSecrets` before exposure. Note the shape change —\n * pre-T1.1 the function preserved the original `body` shape when ≤2KB;\n * now it always returns a (possibly redacted) string, because redaction\n * coerces non-strings to JSON. Consumers who used to do `err.metadata.raw.foo`\n * must now `JSON.parse(err.metadata.raw)` first — but a workspace-wide\n * grep at T1.1 land time confirmed zero such callers.\n *\n * @internal\n */\nexport function truncateRaw(body: unknown): unknown {\n if (body === null || body === undefined) return undefined;\n const s = typeof body === \"string\" ? body : JSON.stringify(body);\n const redacted = redactSecrets(s);\n return redacted.length <= RAW_MAX_CHARS ? redacted : `${cutAt(redacted, RAW_MAX_CHARS)}…`;\n}\n\n/** The first `end` code units of `text`, one fewer when that would split a surrogate pair. */\nfunction cutAt(text: string, end: number): string {\n if (end >= text.length) return text;\n const last = text.charCodeAt(end - 1);\n return text.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end);\n}\n\n/**\n * Build an `ErrorMetadata` object with all optional fields included\n * conditionally (no `undefined` keys in the output). Caller passes\n * dialect-specific fields (`provider`, `endpoint`, `code`); shared\n * fields (`statusCode`, `retryAfter`, `raw`) are derived here.\n *\n * @internal\n */\nexport function buildErrorMetadata(args: {\n provider: string;\n endpoint: string;\n code: ErrorCode;\n status: number;\n headers: Headers | undefined;\n body: unknown;\n}): ErrorMetadata {\n const retryAfter = parseRetryAfter(args.headers);\n const raw = truncateRaw(args.body);\n return {\n provider: args.provider,\n endpoint: args.endpoint,\n code: args.code,\n statusCode: args.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n ...(raw !== undefined ? { raw } : {}),\n };\n}\n\n/**\n * D314: extract the provider's request id (`x-request-id` is OpenAI/most;\n * `request-id` is Anthropic). Returns `undefined` when neither is present.\n *\n * @internal\n */\nexport function parseRequestId(headers: Headers | undefined): string | undefined {\n if (headers === undefined) return undefined;\n return headers.get(\"x-request-id\") ?? headers.get(\"request-id\") ?? undefined;\n}\n\n/**\n * The HTTP status ladder — ONE definition, shared by every provider mapper.\n *\n * This is RFC 9110 semantics, not a vendor contract: a 429 means the same thing\n * whether Anthropic, OpenAI, Bedrock or Vertex sent it. It lived in four copies\n * until 2026-09-01 and the copies had already drifted in two measurable ways,\n * which is what moved it here beside the other dialect-agnostic helpers ADR D67\n * extracted:\n *\n * 1. **402 reached one mapper of four.** T3.7 added `quota_exceeded` and wired\n * it into `openai-compatible.ts` only. A Bedrock, Vertex or Anthropic\n * endpoint answering 402 fell through every arm and came back `unknown` —\n * the canonical bucket existed and three of four mappers could not reach it.\n * 2. **The 5xx arm had two different upper bounds.** `anthropic` and\n * `openai-compatible` guarded `>= 500 && < 600`; `bedrock` and `vertex`\n * guarded `>= 500` with no ceiling, so a malformed or proxy-injected 6xx was\n * `server_error` in two mappers and `unknown` in the other two.\n *\n * Neither was a vendor difference. Both were copy-drift, and that is the DRY\n * test in its textbook form: one piece of knowledge, four places to change it.\n *\n * The ladder is deliberately the FALLBACK, never the whole classifier. Each\n * mapper keeps its own body-dialect rules — Anthropic's `context_too_long`,\n * Bedrock's AWS `__type` strings, Vertex's `google.rpc` status enum — because\n * those ARE per-vendor contracts. The shape is\n * `classifyVendorBody(body) ?? httpStatusToErrorCode(status)`.\n *\n * 404 is deliberately NOT mapped here. Three mappers treat it as `unknown` and\n * Bedrock treats it as `invalid_request` via its own `__type` rules; folding it\n * in would silently change three mappers to close a divergence nobody measured.\n *\n * @internal\n */\nexport type HttpStatusErrorCode = Extract<\n ErrorCode,\n | \"auth_failed\"\n | \"quota_exceeded\"\n | \"timeout\"\n | \"rate_limit\"\n | \"invalid_request\"\n | \"server_error\"\n | \"unknown\"\n>;\n\nexport function httpStatusToErrorCode(status: number): HttpStatusErrorCode {\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 402) return \"quota_exceeded\";\n if (status === 408) return \"timeout\";\n if (status === 429) return \"rate_limit\";\n if (status === 400) return \"invalid_request\";\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\n/**\n * Reads an error body that may arrive already parsed, as a JSON string, or as neither.\n *\n * This is TRANSPORT knowledge, not vendor knowledge: it describes how `fetch` surfaces a body, which\n * is the same whichever provider sent it. It lived twice, character-for-character, in bedrock.ts and\n * vertex.ts — identical once the return type name was substituted. They had not drifted, so the cost\n * was only latent: a fix to one would have missed the other silently.\n *\n * Unparseable input yields `{}` rather than throwing, because a mapper's job is to classify a\n * failure that already happened; failing to read the body is not a second failure to report.\n */\nexport function parseErrorBody<T>(body: unknown): T {\n if (body !== null && typeof body === \"object\") return body as T;\n if (typeof body === \"string\") {\n try {\n return JSON.parse(body) as T;\n } catch {\n return {} as T;\n }\n }\n return {} as T;\n}\n","/**\n * OpenAI-compatible HTTP error mapper (ADR D67).\n *\n * Translates OpenAI-shaped API error responses (covers OpenAI, OpenRouter,\n * DeepSeek, Together, Mistral, Voyage, DeepInfra, etc.) into typed\n * `TheokitAgentError` subclasses with full `ErrorMetadata`.\n *\n * Body inspection: looks at `body.error.code` / `body.error.type` to detect\n * `context_too_long`, `content_filtered`, `model_unavailable` semantics, and at\n * `body.error.message` for a 404 that says no endpoint serves the model\n * (OpenRouter's numeric-code body for a retired model id). A 400 and that 404\n * end their message with the provider's text, redacted and capped at 512\n * characters; every other status keeps the bare message.\n * Falls back to status-based mapping when body doesn't expose `.error`\n * (e.g., HTML server error page, DeepInfra's `{message: \"...\"}` shape).\n *\n * Never throws — caller is already in an error path.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\nimport { buildErrorMetadata, httpStatusToErrorCode } from \"./shared.js\";\n\n// A provider's text joins a message consumers log and show, so it is bounded first. 512 keeps every\n// measured text whole (OpenRouter's 400s run 40 to 60 characters, OpenAI's context-length text\n// about 250); `metadata.raw` keeps up to 2048 bytes of the body for the rest.\nconst PROVIDER_DETAIL_MAX_CHARS = 512;\n\ninterface MapOpenAiErrorArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\nexport function mapOpenAICompatibleError(args: MapOpenAiErrorArgs): TheokitAgentError {\n const { providerId, status, body, headers, endpoint } = args;\n const code = mapOpenAiStatusToCode(status, body);\n const message = formatMessage(providerId, status, code);\n const metadata = buildErrorMetadata({\n provider: providerId,\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: `${providerId}_auth_failed`, metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });\n }\n if (status === 404 && code === \"model_unavailable\") {\n // The model id lives only in the provider's text, so this case carries it.\n const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));\n return new ConfigurationError(detailed, {\n code: `${providerId}_model_unavailable`,\n metadata,\n });\n }\n if (status === 400) {\n // A 400 is fixed by changing the request, and only the provider's text says what to change.\n const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));\n return new ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });\n }\n if (status === 408) {\n return new NetworkError(message, { code: `${providerId}_timeout`, metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: `${providerId}_server_error`, metadata });\n }\n return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });\n}\n\nfunction extractOpenAiErrorCode(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { code?: unknown; type?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n if (typeof err.code === \"string\") return err.code;\n if (typeof err.type === \"string\") return err.type;\n return undefined;\n}\n\nfunction extractOpenAiErrorMessage(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { message?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n return typeof err.message === \"string\" ? err.message : undefined;\n}\n\n// Redaction runs before the cut: a key cut first could keep too few characters to match a\n// credential pattern, and its prefix would reach the message unmasked.\nfunction boundedProviderDetail(body: unknown): string | undefined {\n const raw = extractOpenAiErrorMessage(body);\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const redacted = redactSecrets(raw);\n return redacted.length <= PROVIDER_DETAIL_MAX_CHARS\n ? redacted\n : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}…`;\n}\n\n// OpenRouter answers a model it does not serve with HTTP 404 and a numeric `error.code`,\n// so only the message tells it apart from a 404 for a wrong path (measured 2026-10-20).\nconst MISSING_MODEL_MESSAGE = /no endpoints found/i;\n\nfunction mapOpenAiStatusToCode(status: number, body: unknown): ErrorCode {\n const fromBodyCode = classifyOpenAiBodyCode(extractOpenAiErrorCode(body)?.toLowerCase() ?? \"\");\n if (fromBodyCode !== undefined) return fromBodyCode;\n if (isMissingModel404(status, body)) return \"model_unavailable\";\n\n // Everything below the body dialect is RFC 9110 and lives once, in shared.ts.\n return httpStatusToErrorCode(status);\n}\n\nfunction isMissingModel404(status: number, body: unknown): boolean {\n return status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? \"\");\n}\n\n// The body dialect, in precedence order: the first rule whose fragment appears in the\n// lowercased body code wins.\nconst BODY_CODE_RULES: ReadonlyArray<{ fragments: readonly string[]; code: ErrorCode }> = [\n {\n fragments: [\"context_length\", \"context_window\", \"too_many_tokens\", \"max_tokens\"],\n code: \"context_too_long\",\n },\n { fragments: [\"content_filter\", \"content_policy\", \"safety\"], code: \"content_filtered\" },\n {\n fragments: [\"model_not_found\", \"model_unavailable\", \"invalid_model\"],\n code: \"model_unavailable\",\n },\n // T3.7 — OpenRouter \"Insufficient credits\" / `insufficient_quota` in the BODY.\n // The status-402 half of this rule moved to the shared ladder, where it now\n // reaches all four mappers instead of this one; what stays here is the part\n // that is genuinely a body dialect.\n { fragments: [\"insufficient_quota\", \"quota_exceeded\"], code: \"quota_exceeded\" },\n];\n\nfunction classifyOpenAiBodyCode(rawCode: string): ErrorCode | undefined {\n const rule = BODY_CODE_RULES.find(({ fragments }) =>\n fragments.some((fragment) => rawCode.includes(fragment)),\n );\n return rule?.code;\n}\n\nfunction formatMessage(\n providerId: string,\n status: number,\n code: ErrorCode,\n detail?: string,\n): string {\n const base = `${providerId} API error: ${code} (HTTP ${status})`;\n return detail === undefined || detail === \"\" ? base : `${base}: ${detail}`;\n}\n"]}
@@ -1,18 +0,0 @@
1
- // src/internal/persistence/cwd-mutex.ts
2
- var tails = /* @__PURE__ */ new Map();
3
- function withCwdMutex(key, fn) {
4
- const prev = tails.get(key) ?? Promise.resolve();
5
- const next = prev.then(fn, fn);
6
- tails.set(
7
- key,
8
- next.then(
9
- () => void 0,
10
- () => void 0
11
- )
12
- );
13
- return next;
14
- }
15
-
16
- export { withCwdMutex };
17
- //# sourceMappingURL=chunk-Q5EWJPRY.js.map
18
- //# sourceMappingURL=chunk-Q5EWJPRY.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/persistence/cwd-mutex.ts"],"names":[],"mappings":";AAIA,IAAM,KAAA,uBAAY,GAAA,EAA8B;AAoCzC,SAAS,YAAA,CAAgB,KAAa,EAAA,EAAkC;AAC7E,EAAA,MAAM,OAAO,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA,IAAK,QAAQ,OAAA,EAAQ;AAC/C,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,EAAA,EAAI,EAAE,CAAA;AAG7B,EAAA,KAAA,CAAM,GAAA;AAAA,IACJ,GAAA;AAAA,IACA,IAAA,CAAK,IAAA;AAAA,MACH,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-Q5EWJPRY.js","sourcesContent":["// Tail of the queue per key. Module-scoped on purpose — see `withCwdMutex` below, which is where\n// the contract is documented. Entries are never removed, so the Map holds one promise per distinct\n// key for the life of the process; keys are expected to come from a bounded set (a file path, a\n// subsystem name), not from unbounded user input.\nconst tails = new Map<string, Promise<unknown>>();\n\n/**\n * Run `fn` after every earlier `withCwdMutex` call for the same `key` has settled, and return\n * what `fn` returns.\n *\n * Calls with the same key run strictly in the order they were made — FIFO, never concurrent.\n * Calls with different keys never wait on each other. The key is an opaque string: two callers\n * serialize against each other exactly when they pass equal keys, so a shared key IS the\n * contract, and a mismatched one silently buys no protection at all.\n *\n * A rejection does not poison the queue. The next waiter runs whether the previous `fn` fulfilled\n * or rejected, and the rejection is delivered only to the caller whose `fn` threw. This function\n * neither retries nor swallows: the returned promise rejects with whatever `fn` rejected with.\n *\n * There is no timeout and no cancellation. An `fn` that never settles blocks that key for the\n * lifetime of the process.\n *\n * **Scope — this is an in-process lock only.** State is a module-scoped Map, so it serializes\n * callers that share one module instance and nothing else. Two processes, two worker threads, or\n * two copies of the SDK resolved into the same tree do not see each other's queue. When the\n * resource is a file that other processes can also write, use `withFileLock` from\n * `./file-lock.ts` instead — it takes an OS-level lock and layers this mutex underneath, so it\n * gives both guarantees. Reach for `withCwdMutex` directly when the shared state is in memory, or\n * when the file is one only this process touches.\n *\n * Extracted packages (`@theokit/sdk-budget`, `@theokit/sdk-memory`) import this from\n * `@theokit/sdk` rather than reimplementing it, precisely so the Map is the same one: a per-package\n * copy would give each package its own queue and let their writes race.\n *\n * The Map is module-scoped, so nothing survives a process restart or a fresh module instance, and\n * its entries are never removed — pass keys from a bounded set rather than from arbitrary input.\n * Signature and semantics will not change before sdk-core v3.0.\n *\n * @public\n */\nexport function withCwdMutex<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = tails.get(key) ?? Promise.resolve();\n const next = prev.then(fn, fn); // run fn whether prev fulfilled or rejected\n // Save the new tail. Store the .then() chain that swallows the result so a\n // failure here doesn't poison subsequent waiters.\n tails.set(\n key,\n next.then(\n () => undefined,\n () => undefined,\n ),\n );\n return next;\n}\n"]}
@@ -1,18 +0,0 @@
1
- 'use strict';
2
-
3
- var chunk4TEGFMSP_cjs = require('./chunk-4TEGFMSP.cjs');
4
-
5
- // src/providers.ts
6
- function listProviders2() {
7
- chunk4TEGFMSP_cjs.registerBuiltins();
8
- return chunk4TEGFMSP_cjs.listProviders();
9
- }
10
- function getProviderProfile2(name) {
11
- chunk4TEGFMSP_cjs.registerBuiltins();
12
- return chunk4TEGFMSP_cjs.getProviderProfile(name);
13
- }
14
-
15
- exports.getProviderProfile = getProviderProfile2;
16
- exports.listProviders = listProviders2;
17
- //# sourceMappingURL=chunk-R5UQL2R5.cjs.map
18
- //# sourceMappingURL=chunk-R5UQL2R5.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/runtime/plugin-loader/plugin-bundles.ts","../src/internal/runtime/skills/subagents-loader.ts"],"names":["join"],"mappings":";;;;;;;AAyBA,eAAsB,gBAAA,CACpB,GAAA,EAEA,aAAA,GAAoD,EAAC,EAClC;AACnB,EAAA,MAAM,OAAiB,EAAC;AACxB,EAAA,KAAA,M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C,CAAA,KAAM,CAAA,CAAE,SAAS,CAAC,CAAA;AAC9E,EAAA,IAAI,OAAO,MAAM,QAAA,EAAU;AACzB,IAAA,OAAO,EACJ,KAAA,CAAM,QAAQ,CAAA,CACd,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,EAAM,EACnB,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,CAAC,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,EAAC;AACV;AAGA,SAAS,eAAe,GAAA,EAAsB;AAC5C,EAAA,OAAO,WAAA,CAAY,KAAK,GAAG,CAAA;AAC7B;AAEA,SAAS,gBAAA,CAAiB,KAAa,QAAA,EAAyD;AAC9F,EAAA,MAAM,KAAA,GAAQ,yCAAA,CAA0C,IAAA,CAAK,GAAG,CAAA;AAChE,EAAA,IAAI,UAAU,IAAA,EAAM;AAClB,IAAA,MAAM,IAAI,kBAAA,CAAmB,CAAA,SAAA,EAAY,QAAQ,CAAA,uBAAA,CAAA,EAA2B;AAAA,MAC1E,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,OAAO,EAAE,WAAA,EAAa,KAAA,CAAM,CAAC,CAAA,IAAK,EAAA,EAAI,IAAA,EAAA,CAAO,KAAA,CAAM,CAAC,CAAA,IAAK,EAAA,EAAI,IAAA,EAAK,EAAE;AACtE;AAEA,SAAS,uBAAuB,WAAA,EAAmE;AAIjG,EAAA,OAAO,gBAAgB,WAAW,CAAA;AACpC","file":"chunk-RN3XDZGS.js","sourcesContent":["/**\n * Locating the plugin bundles a project carries.\n *\n * Shared by the skills and subagents loaders, which both need the same answer to \"which folders in\n * this project are plugins\" and would otherwise each grow their own copy of the directory walk.\n *\n * @internal\n */\n\nimport type { Dirent } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pluginBundleRoots } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\n\n/**\n * Every plugin folder under the project's plugin roots.\n *\n * Returns the FOLDERS, not their contents — what a bundle contributes (`skills/`, `agents/`) is the\n * caller's business, and a loader that also knew the layout would have to change whenever the other\n * one did.\n *\n * A missing root is not an error: most projects carry no plugins, and treating their absence as a\n * failure would make \"none installed\" indistinguishable from \"the directory could not be read\".\n */\nexport async function pluginBundleDirs(\n cwd: string,\n /** Declared foreign dialects (#524). Empty reads `.theokit/plugins` only. */\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<string[]> {\n const dirs: string[] = [];\n for (const root of pluginBundleRoots(cwd, compatSources)) {\n let entries: Dirent[];\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of entries) {\n if (entry.isDirectory()) dirs.push(join(root, entry.name));\n }\n }\n return dirs;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport type { AgentDefinition } from \"../../../types/agent.js\";\nimport type { ModelSelection } from \"../../../types/agent-prims.js\";\nimport { diag } from \"../../diagnostics.js\";\nimport { projectConfigRoots } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\nimport { readWorkspaceDir } from \"../config/workspace-dir.js\";\nimport { type FrontmatterValue, parseSimpleYaml } from \"../context/yaml-frontmatter.js\";\nimport { pluginBundleDirs } from \"../plugin-loader/plugin-bundles.js\";\n\n/**\n * Load file-based subagents from `.theokit/agents/*.md` and merge with\n * inline definitions. Inline overrides file-based on name conflict.\n *\n * Each markdown file has YAML frontmatter (description + optional model)\n * and a body that becomes the subagent prompt.\n *\n * @internal\n */\nexport async function loadSubagents(\n cwd: string,\n settingSourcesIncludeProject: boolean,\n inline: Record<string, AgentDefinition> | undefined,\n /** Declared foreign dialects (#524). Empty reads `.theokit/` only. */\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<Record<string, AgentDefinition>> {\n const result: Record<string, AgentDefinition> = {};\n if (settingSourcesIncludeProject) {\n const projectAgents = await readProjectSubagents(cwd, compatSources);\n for (const [name, definition] of Object.entries(projectAgents)) {\n result[name] = definition;\n }\n }\n if (inline !== undefined) {\n for (const [name, definition] of Object.entries(inline)) {\n result[name] = definition;\n }\n }\n return result;\n}\n\n/**\n * Read agent declarations from every project config root (`.theokit`, then `.claude`).\n *\n * FIRST occurrence of a name wins, which is what makes `projectConfigRoots`' order a contract rather\n * than a detail: a project declaring the same agent in both means the explicit namespace.\n */\nasync function readProjectSubagents(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[],\n): Promise<Record<string, AgentDefinition>> {\n const subagents: Record<string, AgentDefinition> = {};\n for (const configRoot of projectConfigRoots(cwd, compatSources, \"subagents\")) {\n await readSubagentsFrom(join(configRoot, \"agents\"), subagents);\n }\n // A Claude Code plugin is a BUNDLE, and its `agents/` is what it exists to contribute. Read after\n // the project's own, so a project can shadow an agent a plugin ships without editing the plugin.\n for (const bundle of await pluginBundleDirs(cwd, compatSources)) {\n await readSubagentsFrom(join(bundle, \"agents\"), subagents);\n }\n return subagents;\n}\n\n/**\n * Parse an agent file, or return null when it was written for another runtime.\n *\n * ## What this changed, and what it deliberately did not\n *\n * The failure used to take the whole directory, and that was a decision rather than an oversight:\n * \"a file that HAS frontmatter and gets it wrong is a broken agent and still fails loudly, which is\n * what keeps a typo'd `sandbox` from returning as a silent gate through this door. Isolating the\n * failure per file would hand that risk back.\"\n *\n * The risk named there is real and is NOT handed back, because the isolation is narrower than the\n * one that argument refuses. Only `KNOWN_CLAUDE_CODE_FIELDS` takes this door — the set that already\n * encodes \"this key belongs to another runtime and carries no behaviour here\". A misspelling of one\n * of OUR keys carries `subagent_unknown_field` and still propagates, so `sandboxx` remains fatal\n * and cannot return as a silent gate. `a-claude-code-field-names-itself.test.ts` pins both halves.\n *\n * What moved the decision was the cost, measured in a live TUI on 2026-09-15: one ported\n * `.claude/agents/*.md` carrying `memory:` stopped every sibling agent from loading and the turn\n * produced no answer at all — on an agent the task never used. Beside it, on the same prompt and\n * the same project, another runtime answered normally. The diagnosis fix this file shipped tells a\n * user which key is foreign; it does not give them back the turn.\n *\n * The loader already draws exactly this line for a file with no frontmatter, and for the same\n * stated reason: one of them must not stop every agent in the directory from loading.\n */\nfunction parseOrSkipForeignRuntime(\n raw: string,\n filename: string,\n): { name: string; definition: AgentDefinition } | null {\n try {\n return parseSubagentMarkdown(raw, filename);\n } catch (error) {\n if (error instanceof ConfigurationError && error.code === \"subagent_foreign_runtime_field\") {\n diag(`[theokit-sdk] ${filename}: ${error.message} — skipping this agent`);\n return null;\n }\n throw error;\n }\n}\n\nasync function readSubagentsFrom(\n root: string,\n subagents: Record<string, AgentDefinition>,\n): Promise<void> {\n const entries = await readWorkspaceDir(root, \"subagents_read_error\", \"subagents directory\");\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const path = join(root, entry.name);\n const raw = await readFile(path, \"utf8\");\n // A markdown file with NO frontmatter is not an agent declaration — a directory of agents\n // written for the Claude Code CLI conventionally carries documentation beside them, and\n // `.claude/agents/README.md` exists in this repository. Throwing on it made ONE such file stop\n // every agent in the directory from loading.\n //\n // Skipped with a warn rather than in silence, and ONLY for the no-frontmatter case: a file that\n // HAS frontmatter and gets it wrong is a broken agent and still fails loudly, which is what\n // keeps a typo'd `sandbox` from returning as a silent gate through this door.\n if (!hasFrontmatter(raw)) {\n diag(`[theokit-sdk] ${entry.name} has no frontmatter — not an agent declaration, skipping`);\n continue;\n }\n const definition = parseOrSkipForeignRuntime(raw, entry.name);\n if (definition === null) continue;\n if (subagents[definition.name] === undefined) {\n // `path` is computed above to read the file and was then dropped. Keeping it is the whole\n // visibility fix (#524): without it a listing cannot say which root an agent came from.\n subagents[definition.name] = { ...definition.definition, source: path };\n }\n }\n}\n\n// The frontmatter keys a disk subagent may declare. Any other key is a typed load\n// error rather than a silent drop — a dropped `sandbox` an operator wrote believing\n// it confines the child is exactly the silent-gate failure class this guards against.\nconst ACCEPTED_FIELDS = new Set([\n \"name\",\n \"description\",\n \"model\",\n \"tools\",\n \"reasoning_effort\",\n \"mcp\",\n \"sandbox\",\n \"memory\",\n]);\n\n// Fields the Claude Code CLI writes that carry NO behaviour for this runtime. Accepted and ignored,\n// so an agent authored for the CLI loads here unchanged — measured 2026-08-26 across the 59 agent\n// files on one machine, where `color` appeared in 38 of them and made every one of those a\n// `subagent_unknown_field` load error.\n//\n// Named explicitly instead of loosening the check above, because that check's reason is sound: a\n// dropped `sandbox` an operator wrote believing it confines the child is a silent gate. A field that\n// COULD change behaviour must still fail loudly. This set is the difference between \"we know this\n// one and it does nothing\" and \"we have never heard of this\" — two facts a bare allow-everything\n// would collapse into one.\n//\n// Anything added here needs the same justification: inert for THIS runtime, not merely unfamiliar.\nconst INERT_CLAUDE_CODE_FIELDS = new Set([\n /** The CLI's label colour for the agent. Presentation only. */\n \"color\",\n]);\n\nfunction parseSubagentMarkdown(\n raw: string,\n filename: string,\n): { name: string; definition: AgentDefinition } {\n const { frontmatter, body } = splitFrontmatter(raw, filename);\n const fields = parseFrontmatterFields(frontmatter);\n rejectUnknownFields(fields, filename);\n rejectMcp(fields, filename);\n\n const definition: AgentDefinition = {\n description: asString(fields.description) ?? \"\",\n prompt: body,\n };\n const model = resolveModel(fields, filename);\n if (model !== undefined) definition.model = model;\n const tools = toStringList(fields.tools);\n if (tools.length > 0) definition.tools = tools;\n const sandbox = resolveSandbox(fields, filename);\n if (sandbox !== undefined) definition.sandbox = sandbox;\n // Carried unjudged — see `AgentDefinition.memory`. Which root a scope names, and whether the\n // name is one at all, is `@theokit/agents`' decision and refusing it twice means two lists.\n const memory = asString(fields.memory);\n if (memory !== undefined) definition.memory = memory;\n\n const name = asString(fields.name) ?? filename.replace(/\\.md$/, \"\");\n return { name, definition };\n}\n\n/**\n * Frontmatter keys that Claude Code documents for a subagent and this runtime does not accept.\n *\n * Not an allow-list — every one of these still fails the load. It exists so the FAILURE can say\n * which kind of unknown it met. A user migrating a `.claude/agents/` tree used to learn one key per\n * round trip: fix `memory`, meet `permissionMode`, fix that, meet `maxTurns` — with nothing saying\n * the set was finite or that the tree was simply written for another runtime.\n *\n * The distinction this file already draws for `INERT_CLAUDE_CODE_FIELDS` is the same one: \"the\n * difference between 'we know this one and it does nothing' and 'we have never heard of this' — two\n * facts a bare allow-everything would collapse into one.\" This is the third fact beside them —\n * \"another runtime's field\" — and it changes only the message, never the verdict.\n */\nconst KNOWN_CLAUDE_CODE_FIELDS = new Set([\n \"disallowedTools\",\n \"permissionMode\",\n \"maxTurns\",\n \"skills\",\n \"background\",\n \"effort\",\n \"isolation\",\n \"initialPrompt\",\n \"hooks\",\n \"experimental\",\n \"mcpServers\",\n]);\n\n/**\n * The typed error for a key we do not accept. Built here rather than inline so `rejectUnknownFields`\n * stays a plain loop: the message has two shapes and the code has two values, and computing all four\n * at the throw site is what pushed that function past the cognitive-complexity gate.\n */\nfunction unknownFieldError(key: string, filename: string): ConfigurationError {\n const foreign = KNOWN_CLAUDE_CODE_FIELDS.has(key);\n const siblings = [...KNOWN_CLAUDE_CODE_FIELDS].filter((f) => f !== key);\n const origin = foreign\n ? ` — \"${key}\" is a Claude Code subagent field that this runtime does not support. ` +\n `The same applies to: ${siblings.join(\", \")}. Removing them one at a time will meet each ` +\n `in turn; the tree is written for another runtime`\n : \"\";\n // The two codes are written as LITERALS, one per branch, rather than as a ternary inside the\n // options object. `tools/generate-error-codes.mjs` walks the source for the literal assigned to\n // `code:`, so a ternary there is not a literal and it extracted NEITHER — measured 2026-09-15,\n // when `quality:docs-errors` went red and the regenerated reference had lost\n // `subagent_unknown_field` without ever gaining `subagent_foreign_runtime_field`. Two real,\n // throwable codes were absent from the published error reference, which is the one place a\n // consumer looks to find out what they can catch.\n if (foreign)\n return new ConfigurationError(\n `Subagent ${filename}: unknown frontmatter field \"${key}\" (accepted: ${[...ACCEPTED_FIELDS].join(\", \")})${origin}`,\n { code: \"subagent_foreign_runtime_field\" },\n );\n return new ConfigurationError(\n `Subagent ${filename}: unknown frontmatter field \"${key}\" (accepted: ${[...ACCEPTED_FIELDS].join(\", \")})${origin}`,\n { code: \"subagent_unknown_field\" },\n );\n}\n\nfunction rejectUnknownFields(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): void {\n for (const key of Object.keys(fields)) {\n if (INERT_CLAUDE_CODE_FIELDS.has(key)) continue;\n if (!ACCEPTED_FIELDS.has(key)) throw unknownFieldError(key, filename);\n }\n}\n\n// mcp: a known field, but not yet honored on the LOCAL delegation path. The frontmatter YAML can only\n// express server NAMES (parseSimpleYaml has no nested-object support), while a child's `Agent.create`\n// needs `mcpServers` as a Record<name, config>; resolving names→config per-subagent in local delegation\n// is its own follow-up. Rather than silently drop it (the M26/M32 silent-gate class), it is a typed load\n// error that names the field and points at the alternative.\nfunction rejectMcp(fields: Record<string, FrontmatterValue | undefined>, filename: string): void {\n if (fields.mcp !== undefined) {\n throw new ConfigurationError(\n `Subagent ${filename}: per-subagent \"mcp\" is not yet supported on the local delegation path; declare MCP servers in .theokit/mcp.json (or the parent) instead`,\n { code: \"subagent_mcp_unsupported_local\" },\n );\n }\n}\n\n// model + reasoning_effort — effort rides inside `model.params[thinking]`, so it requires a concrete\n// model id to attach to (a child inheriting the parent's model cannot carry the parent's provider-\n// specific effort param safely).\nfunction resolveModel(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): ModelSelection | \"inherit\" | undefined {\n const modelId = asString(fields.model);\n const effort = asString(fields.reasoning_effort);\n // reasoning_effort rides in model.params[thinking], so it needs a CONCRETE model id to attach to.\n // Neither an absent model NOR `model: inherit` can carry it (the inherited id is unknown at load), so\n // both are typed errors rather than a silently-dropped effort — the silent-gate class this guards.\n if (effort !== undefined && (modelId === undefined || modelId === \"inherit\")) {\n throw new ConfigurationError(\n `Subagent ${filename}: reasoning_effort requires a concrete model (effort is a model parameter; an absent model or \"inherit\" cannot carry it)`,\n { code: \"subagent_reasoning_effort_without_model\" },\n );\n }\n if (modelId === undefined) return undefined;\n if (modelId === \"inherit\") return \"inherit\";\n return effort !== undefined\n ? { id: modelId, params: [{ id: \"thinking\", value: effort }] }\n : { id: modelId };\n}\n\n// sandbox: boolean only. A granular mode string (read-only/…) is unsupported by the SDK runtime and is\n// a typed error rather than a silent coercion to a boolean.\nfunction resolveSandbox(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): boolean | undefined {\n if (fields.sandbox === undefined) return undefined;\n if (typeof fields.sandbox !== \"boolean\") {\n throw new ConfigurationError(\n `Subagent ${filename}: sandbox must be a boolean (got \"${String(fields.sandbox)}\"); granular sandbox modes are not supported by the runtime`,\n { code: \"subagent_sandbox_not_boolean\" },\n );\n }\n return fields.sandbox;\n}\n\nfunction asString(v: FrontmatterValue | undefined): string | undefined {\n if (typeof v !== \"string\") return undefined;\n // parseSimpleYaml does not strip quotes (documented), and `model`/`reasoning_effort` are fields users\n // habitually quote (`model: \"openai/gpt-4o\"`). Strip a single matching surrounding quote pair so a\n // quoted id/effort does not slip past validation and fail only at the provider.\n const m = /^([\"'])(.*)\\1$/.exec(v);\n return m ? m[2] : v;\n}\n\n/** Accept a YAML list (`string[]`) or a comma/space-separated scalar; trim + drop empties. */\nfunction toStringList(v: FrontmatterValue | undefined): string[] {\n if (Array.isArray(v)) return v.map((t) => t.trim()).filter((t) => t.length > 0);\n if (typeof v === \"string\") {\n return v\n .split(/[\\s,]+/)\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n }\n return [];\n}\n\n/** Does this file open with a frontmatter block at all? Its ABSENCE means \"not an agent\". */\nfunction hasFrontmatter(raw: string): boolean {\n return /^---\\s*\\n/.test(raw);\n}\n\nfunction splitFrontmatter(raw: string, filename: string): { frontmatter: string; body: string } {\n const match = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/.exec(raw);\n if (match === null) {\n throw new ConfigurationError(`Subagent ${filename} is missing frontmatter`, {\n code: \"subagent_missing_frontmatter\",\n });\n }\n return { frontmatter: match[1] ?? \"\", body: (match[2] ?? \"\").trim() };\n}\n\nfunction parseFrontmatterFields(frontmatter: string): Record<string, FrontmatterValue | undefined> {\n // Preserve the rich YAML value types (boolean/number/string[]): `sandbox: true` and\n // `mcp: [a, b]` are meaningful here, so narrowing everything to string (as the\n // pre-M33 loader did) would drop them. Per-field validation happens in parseSubagentMarkdown.\n return parseSimpleYaml(frontmatter);\n}\n"]}