@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,214 +1,7 @@
1
- import { W as MemoryFact, T as MemoryAdapter, V as MemoryContext, aV as SystemPromptSkillRef, M as McpServerConfig, C as ContextSettings, P as ProviderRoutingSettings, a as PluginsSettings, c as Processor, S as SDKAgent } from './sdk-agent-a3fW1xUK.js';
1
+ import { W as MemoryFact, T as MemoryAdapter, V as MemoryContext, aW as SystemPromptSkillRef, M as McpServerConfig, C as ContextSettings, P as ProviderRoutingSettings, a as PluginsSettings, c as Processor, S as SDKAgent } from './sdk-agent-CnwPODYH.js';
2
+ import { a as SessionStore } from './session-store-Dh07jr9N.js';
2
3
  import { M as ModelSelection, C as CustomTool, P as PermissionMode } from './agent-prims-CZyxfCmS.js';
3
4
 
4
- /**
5
- * Owner: `src/` (1 of 2 importers). Derived from the import graph, not
6
- * declared — `tests/lint/types-name-their-owner.test.ts` re-derives it.
7
- *
8
- * `SessionRecord` — the native on-disk transcript record shape (SE40).
9
- *
10
- * The theokit session format IS the Claude Code record shape: a
11
- * `uuid`/`parentUuid` DAG of records with structured
12
- * `text`/`tool_use`/`tool_result`/`thinking` blocks. This is the contract the
13
- * pluggable {@link SessionStore} seam operates over.
14
- *
15
- * DIP-correct home (SE46): the contract lives in the domain `types/` layer;
16
- * the application-layer DAG core (`internal/persistence/session-transcript.ts`)
17
- * re-exports it for back-compat while owning the record builders + reader.
18
- *
19
- * @public
20
- */
21
- /** A content block inside {@link TranscriptMessage}. */
22
- type TranscriptBlock = {
23
- type: "text";
24
- text: string;
25
- } | {
26
- type: "thinking";
27
- thinking?: string;
28
- signature?: string;
29
- } | {
30
- type: "tool_use";
31
- id: string;
32
- name: string;
33
- input: unknown;
34
- } | {
35
- type: "tool_result";
36
- tool_use_id: string;
37
- content: unknown;
38
- is_error?: boolean;
39
- };
40
- /**
41
- * The message body of a {@link SessionRecord}.
42
- *
43
- * **It is NOT called `SessionMessage`** — that name already exists in
44
- * `internal/session/session-types.ts` with the shape `{role, text}`, incompatible with this one.
45
- * Reusing an exported name for a new shape is
46
- * precisely the silent break M91 cost two patches to undo.
47
- *
48
- * Parsing from disk stays **tolerant** (`readTranscript` skips a malformed line): what changes here
49
- * is the **type**, not leniency — records written by earlier versions stay readable.
50
- *
51
- * @public
52
- */
53
- interface TranscriptMessage {
54
- role: "user" | "assistant";
55
- content: TranscriptBlock[];
56
- /**
57
- * The three fields below appear **only** on the assistant record, and come from the writer
58
- * (`SessionTranscript.appendAssistant`). Declared optional because the user record does not carry
59
- * them — measured in the writer itself, not assumed.
60
- */
61
- id?: string;
62
- type?: "message";
63
- model?: string;
64
- }
65
- /**
66
- * One transcript record — a single line of the session JSONL file, and the unit the pluggable
67
- * `SessionStore` seam reads and writes.
68
- *
69
- * Records form a `uuid`/`parentUuid` DAG, not a flat list: `parentUuid` names the preceding record
70
- * and is `null` at the root. Thread a session by following those links; a reader that assumes file
71
- * order is linear will mis-thread one that branched.
72
- *
73
- * `message` is absent on `system` records — a compaction boundary carries `compactMetadata` instead —
74
- * so it is optional even on records you would expect to be conversational, and `type` is what tells
75
- * you which you are holding.
76
- *
77
- * Reading is deliberately tolerant: a malformed line is skipped rather than failing the whole read.
78
- * Every record you receive is well-formed, but the file may have contained more than you got back,
79
- * so this is not the type to use for an exact-count audit of what was written.
80
- *
81
- * @public
82
- */
83
- interface SessionRecord {
84
- type: "user" | "assistant" | "system";
85
- uuid: string;
86
- parentUuid: string | null;
87
- sessionId: string;
88
- timestamp: string;
89
- isSidechain?: boolean;
90
- userType?: string;
91
- cwd?: string;
92
- version?: string;
93
- subtype?: string;
94
- compactMetadata?: {
95
- preTokens: number;
96
- trigger: string;
97
- };
98
- /**
99
- * The message body, in the shape the transcript writer actually writes.
100
- *
101
- * M94 — it was `Record<string, unknown>`, and the consumer recovered the type with a cast on every read.
102
- * The shape **has always been fixed** (`SessionTranscript.appendToolResults` / `#push` produce
103
- * it); it simply was not declared. It stays optional because system records carry no message.
104
- */
105
- message?: TranscriptMessage;
106
- }
107
-
108
- /**
109
- * Owner: `internal/session/` (4 of 8 importers). Derived from the import graph, not declared —
110
- * `tests/lint/types-name-their-owner.test.ts` re-derives it.
111
- *
112
- * SE41 — the pluggable `SessionStore` seam over the NATIVE session transcript.
113
- *
114
- * A minimal, two-method port so an external store (Postgres / Redis / KV /
115
- * durable object) can be the **primary store AND resume source** — the
116
- * serverless (ephemeral FS) and multi-host / multi-pod use case that SE40
117
- * dropped when it removed the `ConversationStorageAdapter`. This is deliberately
118
- * NOT that removed ~10-method adapter: the seam is JUST record read/append over
119
- * the native {@link SessionRecord} shape (no getMessages / getSessionMeta /
120
- * delete / objective methods).
121
- *
122
- * The SDK ships a real default implementation, `FsSessionStore`, that reads and
123
- * append-writes the native Claude-shaped `.jsonl` transcript — omitting
124
- * `local.sessionStore` yields byte-identical current behavior (back-compat, zero
125
- * consumer change). Injected via `local.sessionStore` for external stores.
126
- *
127
- * THIS SEAM DOES NOT HIDE THE STORAGE, AND IS NOT MEANT TO. A Repository
128
- * abstracts a persistence model away; this one is defined in terms of the
129
- * native one — the port speaks {@link SessionRecord}, "the exact SessionRecord
130
- * the SDK writes", and the on-disk layout's path helpers (`encodeProjectDir`,
131
- * `transcriptPath`, `transcriptRoot`) are published on purpose at
132
- * `@theokit/sdk/persistence` so a consumer can locate a transcript file.
133
- *
134
- * That is the whole design and the reason the seam is two methods rather than
135
- * ten: the format is the contract, and a store implements read/append over it.
136
- * A consumer supplying `local.sessionStore` is NOT bound by those paths — they
137
- * describe where the DEFAULT `FsSessionStore` puts files, not where an external
138
- * store must.
139
- *
140
- * Consistency contract: `appendRecords` is append-only and ordering-preserving.
141
- * The FS default serializes appends per agent with a cross-process file lock;
142
- * external implementations own (and MUST document) their own concurrency
143
- * guarantees for two hosts appending to the same `agentId`.
144
- *
145
- * @public
146
- */
147
-
148
- /**
149
- * The pluggable session-store seam. Exactly two methods over the native
150
- * {@link SessionRecord} shape.
151
- *
152
- * @public
153
- */
154
- interface SessionStore {
155
- /**
156
- * Return every persisted record for `agentId`, in append order. A session
157
- * that was never written MUST resolve to `[]` (not throw) — a fresh agent has
158
- * no history. The SDK reconstructs the resumable `LlmMessage[]` from these
159
- * records via the native DAG reader, so the shape MUST be the exact
160
- * {@link SessionRecord} the SDK writes.
161
- *
162
- * A store that cannot READ (e.g. the backing DB is unreachable on resume)
163
- * MUST throw a typed error rather than silently returning `[]` — a silent
164
- * empty read would masquerade as "no history" and drop the conversation.
165
- */
166
- readRecords(agentId: string): Promise<SessionRecord[]>;
167
- /**
168
- * Append `records` (the new-turn delta) to `agentId`'s session, append-only.
169
- * MUST preserve order and MUST NOT drop or rewrite prior records — the native
170
- * format is an append-only `parentUuid` DAG (compaction is a new-root
171
- * `compact_boundary` record, still an append).
172
- *
173
- * Note on the write path: per-turn persistence is fire-and-forget so `send()`
174
- * is never blocked by store I/O — an `appendRecords` rejection is logged to
175
- * stderr, NOT thrown to the caller (best-effort write). An external store that
176
- * must guarantee durability should make `appendRecords` resilient (retry /
177
- * durable write) internally. This differs from {@link SessionStore.readRecords},
178
- * which MUST throw on failure (a resume cannot proceed on a silent partial history).
179
- */
180
- appendRecords(agentId: string, records: readonly SessionRecord[]): Promise<void>;
181
- /**
182
- * Claim the single-writer lease for `agentId`, if this store has one. OPTIONAL.
183
- *
184
- * The SDK calls it when an agent starts and skips it when absent, so a two-method store keeps
185
- * working unchanged — declaring it here does not require it, which is the whole reason it is
186
- * optional. What declaring it DOES is make the capability discoverable: the SDK probed for this
187
- * method through an `as unknown` cast against an interface that never mentioned it, so a
188
- * third-party store author — the serverless / multi-pod case this port exists to serve — read a
189
- * two-method interface, implemented two methods, and never learned the hook was there.
190
- *
191
- * CONTRACT, and the half that matters: a rejection whose `name` is `"SessionBusyError"` PROPAGATES
192
- * to the caller, because another process holding the session is a decision the caller has to make
193
- * (`exec` forks to a new id). Any other rejection is treated as "no lease available here" —
194
- * logged, and the turn proceeds without single-writer protection, since the write is best-effort
195
- * by contract anyway.
196
- */
197
- acquire?(agentId: string): Promise<void>;
198
- /**
199
- * Release the lease `acquire` claimed, if this store has one. OPTIONAL.
200
- *
201
- * Called on agent disposal. A rejection is not handled specially.
202
- */
203
- release?(agentId: string): Promise<void>;
204
- /**
205
- * Release store-level resources — a connection pool, a file handle. OPTIONAL.
206
- *
207
- * Called once, on agent disposal, after {@link SessionStore.release}.
208
- */
209
- dispose?(): Promise<void>;
210
- }
211
-
212
5
  /**
213
6
  * A discovered skill's metadata. The skill BODY is never included — only the
214
7
  * strict frontmatter fields plus the resolved `source` path.
@@ -299,8 +92,12 @@ interface BudgetUsageEvent {
299
92
  readonly tokens: number;
300
93
  /** Provider/model identifier (e.g., `"openai/gpt-4o-mini"`). */
301
94
  readonly model: string;
302
- /** Whether this is an input (prompt) or output (completion) measurement. */
303
- readonly type: "input" | "output";
95
+ /**
96
+ * Whether this is an input (uncached prompt), output (completion), `cache_read` (prompt tokens
97
+ * served from the provider's cache) or `cache_write` (prompt tokens written to it) measurement.
98
+ * A tracker that has no separate rate for the cache types should treat them as input.
99
+ */
100
+ readonly type: "input" | "output" | "cache_read" | "cache_write";
304
101
  /** Optional ISO 8601 timestamp; defaults to now() if omitted. */
305
102
  readonly at?: string;
306
103
  }
@@ -374,7 +171,13 @@ interface BudgetTracker {
374
171
  *
375
172
  * @public
376
173
  */
377
- /** The five lifecycle events the runtime actually fires. */
174
+ /**
175
+ * The five lifecycle events the runtime actually fires.
176
+ *
177
+ * `postRun` (once per run, including a failed run) is internal-only: it is reachable from the
178
+ * SDK's own hook config and spies, but `.theokit/hooks.json` (Claude Code event names) cannot
179
+ * register it, because no Claude Code event means "end of a run". `Stop` fires only on a finished run.
180
+ */
378
181
  type HookEvent = "preRun" | "postRun" | "preToolUse" | "postToolUse" | "stop";
379
182
  /**
380
183
  * #631 — what the consumer is shown when asked to approve a hook.
@@ -1362,7 +1165,8 @@ type SystemPromptResolver = (ctx: SystemPromptContext) => string | Promise<strin
1362
1165
  */
1363
1166
  interface SkillsSettings {
1364
1167
  /**
1365
- * Names of skills the parent agent may invoke. When omitted, every
1168
+ * Names of skills the local runtime loads: a skill not named here cannot be listed or read.
1169
+ * When omitted, every
1366
1170
  * discovered skill is enabled.
1367
1171
  */
1368
1172
  enabled?: string[];
@@ -1778,6 +1582,18 @@ interface AgentOptions {
1778
1582
  conversationId: string;
1779
1583
  userId?: string;
1780
1584
  }) => Promise<void> | void;
1585
+ /**
1586
+ * Start a fresh conversation when the agent has been idle this many minutes.
1587
+ *
1588
+ * Checked at the start of a local `send`: when more than this long has passed since the previous
1589
+ * `send` on the same agent began, the in-memory conversation is cleared first, so the model
1590
+ * receives no prior messages and `onBeforeSend` reports `previousMessageCount: 0`. Absent (the
1591
+ * default), or not a positive finite number, never resets. The first send of a process has no
1592
+ * previous send, so it never resets. The on-disk transcript is not deleted.
1593
+ *
1594
+ * @public
1595
+ */
1596
+ sessionIdleResetMinutes?: number;
1781
1597
  /**
1782
1598
  * Fires before each `agent.send`. `previousMessageCount` is the count of
1783
1599
  * messages already persisted BEFORE the current send adds the user
@@ -2070,4 +1886,4 @@ interface ListResult<T> {
2070
1886
  nextCursor?: string;
2071
1887
  }
2072
1888
 
2073
- export { type RecordSessionSummaryArgs as $, type AgentOptions as A, type BuiltinToolName as B, type CloudOptions as C, type CreateSkillSpec as D, type HookApprovalRequest as E, type HookName as F, type GetAgentOptions as G, type HookApprovalGate as H, type InlineSkill as I, type LlmCallContext as J, type MemoryProviderAgentRef as K, type LocalOptions as L, type MemorySettings as M, type MemoryProviderFactory as N, type MemoryProviderHandle as O, type Plugin as P, type MemoryProviderInitOptions as Q, type PluginContext as R, type SystemPromptResolver as S, type PluginHookDisposer as T, type PostAssistantReplyContext as U, type PostToolCallContext as V, type PreToolCallContext as W, type PreUserSendContext as X, type PreUserSendResult as Y, type ProviderTransform as Z, type ProviderTransformContext as _, type AgentDefinition as a, type SessionLifecycleContext as a0, type SessionRecord as a1, type SessionStore as a2, type SettingSource as a3, Skill as a4, type SkillsResolver as a5, type SkillsResolverContext as a6, type SystemPromptContext as a7, type SystemPromptMemoryFact as a8, type TelemetrySettings as a9, type ToolCallSummary as aa, type ToolContext as ab, type ToolResultTransformContext as ac, type TransformContext as ad, type SkillsSettings as b, type ListAgentsOptions as c, type ListResult as d, type SDKAgentInfo as e, type ListRunsOptions as f, type GetRunOptions as g, type AgentOperationOptions as h, type AgentDescription as i, type ProviderProfile as j, type Skill$1 as k, type BudgetTracker as l, type MemoryProvider as m, type PreToolCallDecision as n, type ActiveMemoryPassArgs as o, type ActiveMemoryPassResult as p, type AgentSubagentDescription as q, type AgentToolDescription as r, type BudgetCheck as s, type BudgetTotal as t, type BudgetUsageEvent as u, type CloudEnv as v, type CloudRepo as w, type CompatSource as x, type CompatSourceAdapter as y, type CompatSurface as z };
1889
+ export { type RecordSessionSummaryArgs as $, type AgentOptions as A, type BuiltinToolName as B, type CloudOptions as C, type CreateSkillSpec as D, type HookApprovalRequest as E, type HookName as F, type GetAgentOptions as G, type HookApprovalGate as H, type InlineSkill as I, type LlmCallContext as J, type MemoryProviderAgentRef as K, type LocalOptions as L, type MemorySettings as M, type MemoryProviderFactory as N, type MemoryProviderHandle as O, type Plugin as P, type MemoryProviderInitOptions as Q, type PluginContext as R, type SystemPromptResolver as S, type PluginHookDisposer as T, type PostAssistantReplyContext as U, type PostToolCallContext as V, type PreToolCallContext as W, type PreUserSendContext as X, type PreUserSendResult as Y, type ProviderTransform as Z, type ProviderTransformContext as _, type AgentDefinition as a, type SessionLifecycleContext as a0, type SettingSource as a1, Skill as a2, type SkillsResolver as a3, type SkillsResolverContext as a4, type SystemPromptContext as a5, type SystemPromptMemoryFact as a6, type TelemetrySettings as a7, type ToolCallSummary as a8, type ToolContext as a9, type ToolResultTransformContext as aa, type TransformContext as ab, type SkillsSettings as b, type ListAgentsOptions as c, type ListResult as d, type SDKAgentInfo as e, type ListRunsOptions as f, type GetRunOptions as g, type AgentOperationOptions as h, type AgentDescription as i, type ProviderProfile as j, type Skill$1 as k, type BudgetTracker as l, type MemoryProvider as m, type PreToolCallDecision as n, type ActiveMemoryPassArgs as o, type ActiveMemoryPassResult as p, type AgentSubagentDescription as q, type AgentToolDescription as r, type BudgetCheck as s, type BudgetTotal as t, type BudgetUsageEvent as u, type CloudEnv as v, type CloudRepo as w, type CompatSource as x, type CompatSourceAdapter as y, type CompatSurface as z };
@@ -1,27 +1,28 @@
1
1
  'use strict';
2
2
 
3
- var chunk2WY2OFSC_cjs = require('./chunk-2WY2OFSC.cjs');
3
+ var chunk26UQG242_cjs = require('./chunk-26UQG242.cjs');
4
4
  require('./chunk-L7JPXZ2C.cjs');
5
- require('./chunk-LXG6VL6R.cjs');
5
+ require('./chunk-FBIDOOJM.cjs');
6
6
  require('./chunk-BUUUWQMB.cjs');
7
- require('./chunk-CWQPQTUZ.cjs');
7
+ require('./chunk-NEH3BPFD.cjs');
8
8
  require('./chunk-7YUPSBDV.cjs');
9
9
  require('./chunk-BV2MWEMV.cjs');
10
- require('./chunk-CGH4BCIY.cjs');
10
+ require('./chunk-XE3CAY6Z.cjs');
11
11
  require('./chunk-GHX4P3V2.cjs');
12
12
  require('./chunk-RS7YQR4X.cjs');
13
- require('./chunk-SDZ4XDWS.cjs');
14
- require('./chunk-6OCJWGVD.cjs');
15
- require('./chunk-SNVYOX46.cjs');
16
- require('./chunk-SXH37C7X.cjs');
13
+ require('./chunk-VWYFGE27.cjs');
14
+ require('./chunk-FTXY4D44.cjs');
15
+ require('./chunk-3E3VSMB6.cjs');
16
+ require('./chunk-55LLQFHW.cjs');
17
17
  require('./chunk-YJNYDJ2T.cjs');
18
- require('./chunk-NP362THY.cjs');
18
+ require('./chunk-3F53FLQ7.cjs');
19
19
  require('./chunk-QOGNZMHD.cjs');
20
20
  require('./chunk-MSW7LB2V.cjs');
21
21
  require('./chunk-2ZPEDVLM.cjs');
22
22
  require('./chunk-QG4SXZ2A.cjs');
23
23
  require('./chunk-UDAKAE4Z.cjs');
24
24
  require('./chunk-KRD3GQAA.cjs');
25
+ require('./chunk-XOU3CL7S.cjs');
25
26
  require('./chunk-3HA7N2BB.cjs');
26
27
  require('./chunk-MUUQ2WFJ.cjs');
27
28
  require('./chunk-AA27GEYS.cjs');
@@ -41,18 +42,18 @@ require('./chunk-3WKWBYPO.cjs');
41
42
  require('./chunk-A4RAL2ER.cjs');
42
43
  require('./chunk-AT2PESXB.cjs');
43
44
  require('./chunk-POBZXULR.cjs');
44
- require('./chunk-G7XBVM3T.cjs');
45
- require('./chunk-ZF2LDKQQ.cjs');
45
+ require('./chunk-MHUOVS5I.cjs');
46
+ require('./chunk-U3DW3WDE.cjs');
46
47
  require('./chunk-BWYC7RZG.cjs');
47
48
  require('./chunk-ZOFRNNZD.cjs');
48
- require('./chunk-WDVG5R2Q.cjs');
49
+ require('./chunk-AUH2EVWY.cjs');
49
50
  require('./chunk-YQ3XC6C2.cjs');
50
51
  require('./chunk-6XQLTQB6.cjs');
51
52
  require('./chunk-KX5QXLBS.cjs');
52
- require('./chunk-4KBI37F3.cjs');
53
+ require('./chunk-RTDVSHJR.cjs');
53
54
  require('./chunk-3EE6LVWT.cjs');
54
- require('./chunk-R5UQL2R5.cjs');
55
- require('./chunk-4TEGFMSP.cjs');
55
+ require('./chunk-SPEN7RJU.cjs');
56
+ require('./chunk-P7QYG4RZ.cjs');
56
57
  require('./chunk-NVXXWAU7.cjs');
57
58
  require('./chunk-A77UMVMD.cjs');
58
59
  require('./chunk-5645PMVU.cjs');
@@ -65,7 +66,7 @@ require('./chunk-RNXXYF22.cjs');
65
66
 
66
67
  Object.defineProperty(exports, "Agent", {
67
68
  enumerable: true,
68
- get: function () { return chunk2WY2OFSC_cjs.Agent; }
69
+ get: function () { return chunk26UQG242_cjs.Agent; }
69
70
  });
70
- //# sourceMappingURL=agent-TL4K7BTG.cjs.map
71
- //# sourceMappingURL=agent-TL4K7BTG.cjs.map
71
+ //# sourceMappingURL=agent-CB27KF6O.cjs.map
72
+ //# sourceMappingURL=agent-CB27KF6O.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-TL4K7BTG.cjs"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-CB27KF6O.cjs"}
package/dist/agent.d.ts CHANGED
@@ -152,9 +152,8 @@ export declare class Agent {
152
152
  * The agent-builder's M85 interrupt rotates the session id to work around a
153
153
  * constraint that does not exist.
154
154
  *
155
- * - `close()` marks the handle disposed WITHOUT evicting the cache entry. It is
156
- * internal and unused today; if it becomes reachable, this bullet stops being true
157
- * for that path.
155
+ * - `close()` marks the handle disposed AND drops its cache entry, so the next call
156
+ * builds a fresh handle.
158
157
  *
159
158
  * @public
160
159
  */
@@ -1,9 +1,9 @@
1
1
  import { submit, subscribe } from './chunk-HWMGR3HA.js';
2
2
  import './chunk-K2BQQ445.js';
3
- import { newPooledCredential, CredentialPool, withCredentialPool } from './chunk-5AR6O7GW.js';
3
+ import { newPooledCredential, CredentialPool, withCredentialPool } from './chunk-NK5EOTDY.js';
4
4
  import './chunk-24MGQDK3.js';
5
5
  import { createSemaphore } from './chunk-AHKS3DKI.js';
6
- import './chunk-Q5EWJPRY.js';
6
+ import './chunk-PPU2D4FZ.js';
7
7
  import './chunk-MLGETTYX.js';
8
8
  import './chunk-M4U24U6G.js';
9
9
  import { ConfigurationError, TheokitAgentError } from './chunk-TNFOU6SB.js';
@@ -256,5 +256,5 @@ function buildPoolsFromApiKeys(apiKeys, strategy) {
256
256
  }
257
257
 
258
258
  export { batchImpl, validateBatchInput };
259
- //# sourceMappingURL=batch-EP3FCL6D.js.map
260
- //# sourceMappingURL=batch-EP3FCL6D.js.map
259
+ //# sourceMappingURL=batch-N2XDYZED.js.map
260
+ //# sourceMappingURL=batch-N2XDYZED.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/agent/batch.ts"],"names":[],"mappings":";;;;;;;;;;;;AAmDO,SAAS,kBAAA,CACd,SACA,OAAA,EACM;AACN,EAAA,MAAM,EAAE,aAAY,GAAI,OAAA;AACxB,EAAA,IAAI,WAAA,KAAgB,WAAc,CAAC,MAAA,CAAO,UAAU,WAAW,CAAA,IAAK,cAAc,CAAA,CAAA,EAAI;AACpF,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR,2DAA2D,WAAW,CAAA,CAAA;AAAA,MACtE,EAAE,MAAM,qBAAA;AAAsB,KAChC;AAAA,EACF;AACA,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,OAAA,CAAQ,QAAQ,CAAA,EAAA,EAAK;AACvC,IAAA,MAAM,IAAA,GAAO,QAAQ,CAAC,CAAA;AACtB,IAAA,MAAM,MAAA,GAAS,OAAO,IAAA,KAAS,QAAA,GAAW,OAAO,IAAA,EAAM,MAAA;AACvD,IAAA,IAAI,OAAO,MAAA,KAAW,QAAA,IAAY,MAAA,CAAO,WAAW,CAAA,EAAG;AACrD,MAAA,MAAM,IAAI,kBAAA,CAAmB,CAAA,4BAAA,EAA+B,CAAC,CAAA,2BAAA,CAAA,EAA+B;AAAA,QAC1F,IAAA,EAAM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OAAA,CAAQ,OAAO,CAAA,EAAG;AACtD,IAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA,EAAG;AAC1B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,MAAA,CAAO,CAAC,CAAA,KAAmB,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,CAAE,MAAA,GAAS,CAAC,CAAA;AACtF,IAAA,IAAI,QAAA,CAAS,SAAS,CAAA,EAAG;AACzB,IAAA,MAAM,UAAU,QAAA,CAAS,GAAA;AAAA,MAAI,CAAC,KAAA,EAAO,CAAA,KACnC,mBAAA,CAAoB,EAAE,QAAA,EAAU,WAAA,EAAa,KAAA,EAAO,QAAA,EAAU,CAAA,EAAG,MAAA,EAAQ,QAAA,EAAU;AAAA,KACrF;AACA,IAAA,KAAA,CAAM,GAAA;AAAA,MACJ,QAAA;AAAA,MACA,IAAI,cAAA,CAAe,QAAA,EAAU,SAAS,QAAA,GAAW,QAAQ,KAAK,YAAY;AAAA,KAC5E;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT","file":"batch-EP3FCL6D.js","sourcesContent":["/**\n * `Agent.batch(prompts, options)` core (ADRs D134-D140).\n *\n * Fans out N prompts via bounded concurrency, isolates failures per-prompt,\n * preserves input order in the result array, supports streaming callbacks\n * + AbortSignal. The credential pool (D131) is shared across all\n * in-flight agents via `withCredentialPool` ALS scope (EC-A fix).\n *\n * @internal\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { ConfigurationError, TheokitAgentError } from \"../../errors.js\";\nimport { diag } from \"../../internal/diagnostics.js\";\nimport { CredentialPool, newPooledCredential } from \"../../internal/llm/credential-pool.js\";\nimport { withCredentialPool } from \"../../internal/llm/credential-pool-context.js\";\nimport type { CredentialPoolStrategy } from \"../../internal/llm/credential-pool-types.js\";\nimport {\n submit as taskRegistrySubmit,\n subscribe as taskRegistrySubscribe,\n} from \"../../internal/task/registry.js\";\nimport type { AgentOptions, SDKAgent } from \"../../types/agent.js\";\nimport type { BatchItem, BatchOptions, BatchProgress, BatchResult } from \"../../types/batch.js\";\nimport { createSemaphore } from \"../concurrency/async-semaphore.js\";\n\n/** DI contract — keeps batch.ts cycle-free from agent.ts. @internal */\ninterface BatchDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n}\n\n/**\n * Pre-flight boundary validation for `Agent.batch` (arch-review Gap 3).\n *\n * Mirrors the in-repo `validateAgentOptions` / `validateCronExpression`\n * pattern: throws `ConfigurationError` with a stable code on the first\n * violation, returns silently otherwise. Pure — no I/O.\n *\n * Rules:\n * - `concurrency`, when provided, must be a positive integer (rejects\n * 0/negative/non-integer/NaN/Infinity). Previously this was caught only\n * incidentally deep inside `createSemaphore` with a leaky \"permits\"\n * message, AND after task wrapping (dangling Task on invalid input).\n * - every prompt item must carry a non-empty string prompt. Previously\n * `normalizeItem` passed `prompt: \"\"` / non-string straight to\n * `agent.send`. (Whitespace-only strings are intentionally NOT rejected —\n * an empty string is a structural error; judging content is not this\n * validator's job, and the repo's property tests treat any length>=1\n * string as a valid prompt.)\n *\n * @internal\n */\nexport function validateBatchInput(\n prompts: ReadonlyArray<string | BatchItem>,\n options: BatchOptions,\n): void {\n const { concurrency } = options;\n if (concurrency !== undefined && (!Number.isInteger(concurrency) || concurrency < 1)) {\n throw new ConfigurationError(\n `Agent.batch concurrency must be a positive integer, got ${concurrency}`,\n { code: \"invalid_concurrency\" },\n );\n }\n for (let i = 0; i < prompts.length; i++) {\n const item = prompts[i];\n const prompt = typeof item === \"string\" ? item : item?.prompt;\n if (typeof prompt !== \"string\" || prompt.length === 0) {\n throw new ConfigurationError(`Agent.batch prompt at index ${i} must be a non-empty string`, {\n code: \"invalid_batch_item\",\n });\n }\n }\n}\n\n/**\n * Run N prompts in parallel with bounded concurrency.\n *\n * @internal\n */\nexport async function batchImpl(\n prompts: ReadonlyArray<string | BatchItem>,\n options: BatchOptions,\n deps: BatchDeps,\n): Promise<BatchResult[]> {\n // EC-1: empty array → no work, no agents created.\n if (prompts.length === 0) return [];\n\n // Pre-flight boundary validation (arch-review Gap 3). MUST run before pool\n // build AND before wrapBatchAsTask so invalid input never registers a\n // dangling Task or builds a credential pool (fail-fast, Rule 8).\n validateBatchInput(prompts, options);\n\n // EC-A fix: build credential pools ONCE and share via AsyncLocalStorage.\n // Without this each Agent.create() would build its own pool from identical\n // apiKeys → 4× rate-limit wastage per concurrency window.\n const sharedPools = buildPoolsFromApiKeys(\n options.providers?.apiKeys,\n options.providers?.credentialPoolStrategy,\n );\n const exec = (): Promise<BatchResult[]> => runBatch(prompts, options, deps);\n const withPool = (): Promise<BatchResult[]> =>\n sharedPools.size > 0 ? withCredentialPool(sharedPools, exec) : exec();\n // T3.3: opt-in Task wrapping (ADRs D363, D374). Register the whole\n // batch as a single Task (kind=\"batch\") with `b-` prefix (D368/EC-5).\n if (options.task !== undefined) {\n return wrapBatchAsTask(prompts.length, options.task, withPool);\n }\n return withPool();\n}\n\n/**\n * Raises the typed error for a terminal failure event, and returns for anything else.\n *\n * Split out of {@link wrapBatchAsTask} so the wait loop reads as \"finished -> results, terminal\n * failure -> throw\" rather than as three inlined branches; the failure vocabulary is one concern and\n * lives in one place.\n */\nfunction throwIfTerminalFailure(\n id: string,\n event: { type: string } & Record<string, unknown>,\n): void {\n if (event.type === \"errored\") {\n const error = event.error as { message: string; code?: string };\n throw new TheokitAgentError(`Batch task ${id} failed: ${error.message}`, {\n code: \"batch_task_failed\",\n protoErrorCode: error.code,\n });\n }\n if (event.type === \"cancelled\") {\n const reason = event.reason as string | undefined;\n throw new TheokitAgentError(\n `Batch task ${id} was cancelled${reason === undefined ? \"\" : `: ${reason}`}`,\n { code: \"batch_task_cancelled\" },\n );\n }\n}\n\nasync function wrapBatchAsTask(\n total: number,\n taskOpt: true | { id?: string; meta?: Record<string, unknown> },\n exec: () => Promise<BatchResult[]>,\n): Promise<BatchResult[]> {\n const opts = taskOpt === true ? {} : taskOpt;\n const id = opts.id ?? `b-${randomUUID()}`;\n const meta: Record<string, unknown> = {\n total,\n ...(opts.meta ?? {}),\n };\n let results: BatchResult[] = [];\n await taskRegistrySubmit({\n kind: \"batch\",\n work: async (ctx) => {\n results = await exec();\n const succeeded = results.filter((r) => r.ok).length;\n const failed = results.length - succeeded;\n ctx.emit({ total: results.length, succeeded, failed });\n return { total: results.length, succeeded, failed };\n },\n id,\n meta,\n allowReservedPrefix: true,\n });\n // `submit` returns immediately with a queued handle, so this waits for the task's own terminal\n // EVENT rather than polling its state.\n //\n // What this replaced, and why the replacement is not just tidier: the wait was\n // `for (let i = 0; i < 5000; i++) { ...get(id)...; await sleep(5) }` followed by an unconditional\n // `return results`, and `results` is assigned only inside the `work` callback above. So THREE\n // distinct failures produced one indistinguishable value — the work threw, the task was\n // cancelled, or the budget elapsed — and each returned `[]` on a RESOLVED promise, which a caller\n // cannot tell apart from `Agent.batch([])`. The registry had already recorded the failure as\n // `{ code, message }` on the terminal event; the loop read only `handle.state` and dropped it.\n //\n // The budget was not a safety net either. 5000 iterations of a 5 ms sleep is ~25 s, and a batch\n // legitimately longer than that would trip it and return `[]` — the bound generated the bug it\n // appeared to guard against. A task's own lifecycle is the honest bound, and `subscribe` drains\n // the buffered events first (`subscribe.ts:23`), so a task that finished before this line runs\n // still delivers its terminal event rather than hanging.\n for await (const event of taskRegistrySubscribe(id)) {\n if (event.type === \"finished\") return results;\n throwIfTerminalFailure(id, event);\n }\n // The registry's contract says the stream ends only after a terminal event, so this is\n // unreachable. It throws rather than returning `results` because returning here would restore the\n // exact silent-empty-array path this function was rewritten to remove.\n throw new TheokitAgentError(`Batch task ${id} ended without a terminal event`, {\n code: \"batch_task_no_terminal_event\",\n });\n}\n\nasync function runBatch(\n prompts: ReadonlyArray<string | BatchItem>,\n options: BatchOptions,\n deps: BatchDeps,\n): Promise<BatchResult[]> {\n const requested = options.concurrency ?? 4;\n // createSemaphore throws on invalid (EC-2).\n // EC-3: cap to prompts.length to avoid idle workers.\n const effective = Math.min(requested, prompts.length);\n const semaphore = createSemaphore(effective);\n const items = prompts.map(normalizeItem);\n const results: BatchResult[] = new Array(items.length);\n const counters = { completed: 0, failed: 0 };\n let aborted = false;\n\n const onAbort = (): void => {\n aborted = true;\n };\n options.signal?.addEventListener(\"abort\", onAbort);\n // EC-C: pre-aborted signal — treat as already-aborted before any work.\n if (options.signal?.aborted === true) aborted = true;\n\n try {\n await Promise.all(\n items.map(async (item, index) => {\n const release = await semaphore.acquire();\n try {\n if (aborted) {\n results[index] = abortResult(item, index, options.signal);\n } else {\n results[index] = await runOne(item, index, options, deps);\n }\n if (results[index].ok) counters.completed += 1;\n else counters.failed += 1;\n // B-110 (measured 2026-08-19): `onResult` used to run AFTER `release()`, so a caller who\n // asked for `concurrency: 1` still got overlapping `onResult` invocations — the permit was\n // already returned before the callback ran. `concurrency` is documented (`types/batch.ts`)\n // to bound the whole per-item lifecycle, callback included, so the permit is now held\n // until `onResult` finishes: this call moved inside the `try` the `finally` below wraps.\n await safeCallResult(options.onResult, results[index]);\n } finally {\n release();\n }\n safeCallProgress(options.onProgress, {\n total: items.length,\n completed: counters.completed,\n failed: counters.failed,\n inFlight: semaphore.inFlight(),\n pending: Math.max(0, semaphore.pending() - semaphore.inFlight()),\n });\n }),\n );\n } finally {\n options.signal?.removeEventListener(\"abort\", onAbort);\n }\n\n return options.filter ? results.filter(options.filter) : results;\n}\n\nasync function runOne(\n item: BatchItem,\n index: number,\n options: BatchOptions,\n deps: BatchDeps,\n): Promise<BatchResult> {\n const t0 = Date.now();\n const agentOpts = buildAgentOptions(item, options);\n\n try {\n const agent = await deps.create(agentOpts);\n try {\n const run = await agent.send(item.prompt);\n const result = await run.wait();\n return {\n ok: true,\n index,\n prompt: item.prompt,\n result,\n ...(item.metadata !== undefined ? { metadata: item.metadata } : {}),\n durationMs: Date.now() - t0,\n };\n } finally {\n // EC-8: dispose failure → stderr warn, don't fail the result.\n try {\n await agent.dispose();\n } catch (disposeErr) {\n // theokit#147 — the interceptable channel; a batch run must not write onto a TUI's frame.\n diag(\n `[theokit-sdk] batch: agent.dispose failed for prompt ${index}: ${\n disposeErr instanceof Error ? disposeErr.message : String(disposeErr)\n }\\n`,\n );\n }\n }\n } catch (err) {\n return {\n ok: false,\n index,\n prompt: item.prompt,\n error: toTheokitError(err),\n ...(item.metadata !== undefined ? { metadata: item.metadata } : {}),\n durationMs: Date.now() - t0,\n };\n }\n}\n\n/** Every key `BatchOptions` adds on top of `AgentOptions`, derived rather than listed twice. */\ntype BatchOnlyKey = Exclude<keyof BatchOptions, keyof AgentOptions>;\n\n/**\n * The batch-only keys, as values — `buildAgentOptions` has to strip them at runtime and a type\n * cannot do that.\n *\n * Both halves of this declaration are load-bearing, in opposite directions:\n *\n * - `satisfies readonly BatchOnlyKey[]` rejects a key here that is NOT batch-only, so a rename in\n * the interface breaks this list instead of silently stripping a field that should be forwarded.\n * - `NoUnlistedBatchOnlyKey` below rejects a batch-only key MISSING from here, which is the\n * direction that actually bites: adding a seventh option to `BatchOptions` and forgetting this\n * function forwards it into `AgentOptions`, where TypeScript's excess-property check does not\n * fire on a spread and `validateAgentOptions` either rejects it or carries it into every agent\n * the batch creates.\n *\n * The keys are NOT derived into the interface as a mapped type, which would collapse both\n * representations into one: each of the six carries several paragraphs of public API documentation,\n * and a mapped type cannot hold them.\n */\nconst BATCH_ONLY_KEYS = [\n \"concurrency\",\n \"filter\",\n \"onResult\",\n \"onProgress\",\n \"signal\",\n \"task\",\n] as const satisfies readonly BatchOnlyKey[];\n\n/** Compile-time only: resolves to `never` unless every batch-only key is listed above. */\ntype NoUnlistedBatchOnlyKey =\n Exclude<BatchOnlyKey, (typeof BATCH_ONLY_KEYS)[number]> extends never\n ? true\n : [\n \"batch-only key missing from BATCH_ONLY_KEYS\",\n Exclude<BatchOnlyKey, (typeof BATCH_ONLY_KEYS)[number]>,\n ];\n\nconst _batchKeysAreExhaustive: NoUnlistedBatchOnlyKey = true;\nvoid _batchKeysAreExhaustive;\n\nfunction buildAgentOptions(item: BatchItem, options: BatchOptions): AgentOptions {\n const rest: Record<string, unknown> = { ...options };\n for (const key of BATCH_ONLY_KEYS) delete rest[key];\n const agentOpts = rest as AgentOptions;\n if (item.systemPrompt !== undefined) {\n return { ...agentOpts, systemPrompt: item.systemPrompt };\n }\n return agentOpts;\n}\n\nfunction normalizeItem(promptOrItem: string | BatchItem): BatchItem {\n return typeof promptOrItem === \"string\" ? { prompt: promptOrItem } : promptOrItem;\n}\n\nfunction abortResult(item: BatchItem, index: number, signal?: AbortSignal): BatchResult {\n // EC-D: propagate signal.reason when set (preserves caller's error).\n let error: TheokitAgentError;\n if (signal?.reason instanceof TheokitAgentError) {\n error = signal.reason;\n } else if (signal?.reason instanceof Error) {\n error = new TheokitAgentError(signal.reason.message, {\n code: \"aborted\",\n cause: signal.reason,\n });\n } else {\n error = new TheokitAgentError(\"Batch aborted via AbortSignal\", { code: \"aborted\" });\n }\n return {\n ok: false,\n index,\n prompt: item.prompt,\n error,\n ...(item.metadata !== undefined ? { metadata: item.metadata } : {}),\n durationMs: 0,\n };\n}\n\nfunction toTheokitError(err: unknown): TheokitAgentError {\n if (err instanceof TheokitAgentError) return err;\n if (err instanceof Error) {\n return new TheokitAgentError(err.message, { code: \"unknown\", cause: err });\n }\n return new TheokitAgentError(String(err), { code: \"unknown\" });\n}\n\nasync function safeCallResult(cb: BatchOptions[\"onResult\"], result: BatchResult): Promise<void> {\n if (cb === undefined) return;\n try {\n await cb(result);\n } catch (err) {\n diag(\n `[theokit-sdk] batch: onResult callback threw: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n );\n }\n}\n\nfunction safeCallProgress(cb: BatchOptions[\"onProgress\"], progress: BatchProgress): void {\n if (cb === undefined) return;\n try {\n cb(progress);\n } catch (err) {\n diag(\n `[theokit-sdk] batch: onProgress callback threw: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n );\n }\n}\n\n/**\n * EC-A: construct shared pools from options.apiKeys. Empty/invalid → empty Map.\n *\n * @internal\n */\nfunction buildPoolsFromApiKeys(\n apiKeys: Record<string, string[]> | undefined,\n strategy: Record<string, CredentialPoolStrategy> | undefined,\n): Map<string, CredentialPool> {\n const pools = new Map<string, CredentialPool>();\n if (apiKeys === undefined) return pools;\n for (const [provider, keys] of Object.entries(apiKeys)) {\n if (!Array.isArray(keys)) continue;\n const filtered = keys.filter((k): k is string => typeof k === \"string\" && k.length > 0);\n if (filtered.length < 2) continue; // 1-key pools aren't pools\n const entries = filtered.map((token, i) =>\n newPooledCredential({ provider, accessToken: token, priority: i, source: \"manual\" }),\n );\n pools.set(\n provider,\n new CredentialPool(provider, entries, strategy?.[provider] ?? \"fill_first\"),\n );\n }\n return pools;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/agent/batch.ts"],"names":[],"mappings":";;;;;;;;;;;;AAmDO,SAAS,kBAAA,CACd,SACA,OAAA,EACM;AACN,EAAA,MAAM,EAAE,aAAY,GAAI,OAAA;AACxB,EAAA,IAAI,WAAA,KAAgB,WAAc,CAAC,MAAA,CAAO,UAAU,WAAW,CAAA,IAAK,cAAc,CAAA,CAAA,EAAI;AACpF,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR,2DAA2D,WAAW,CAAA,CAAA;AAAA,MACtE,EAAE,MAAM,qBAAA;AAAsB,KAChC;AAAA,EACF;AACA,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,OAAA,CAAQ,QAAQ,CAAA,EAAA,EAAK;AACvC,IAAA,MAAM,IAAA,GAAO,QAAQ,CAAC,CAAA;AACtB,IAAA,MAAM,MAAA,GAAS,OAAO,IAAA,KAAS,QAAA,GAAW,OAAO,IAAA,EAAM,MAAA;AACvD,IAAA,IAAI,OAAO,MAAA,KAAW,QAAA,IAAY,MAAA,CAAO,WAAW,CAAA,EAAG;AACrD,MAAA,MAAM,IAAI,kBAAA,CAAmB,CAAA,4BAAA,EAA+B,CAAC,CAAA,2BAAA,CAAA,EAA+B;AAAA,QAC1F,IAAA,EAAM;AAAA,OACP,CAAA;AAAA,IACH;AA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AACtD,IAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA,EAAG;AAC1B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,MAAA,CAAO,CAAC,CAAA,KAAmB,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,CAAE,MAAA,GAAS,CAAC,CAAA;AACtF,IAAA,IAAI,QAAA,CAAS,SAAS,CAAA,EAAG;AACzB,IAAA,MAAM,UAAU,QAAA,CAAS,GAAA;AAAA,MAAI,CAAC,KAAA,EAAO,CAAA,KACnC,mBAAA,CAAoB,EAAE,QAAA,EAAU,WAAA,EAAa,KAAA,EAAO,QAAA,EAAU,CAAA,EAAG,MAAA,EAAQ,QAAA,EAAU;AAAA,KACrF;AACA,IAAA,KAAA,CAAM,GAAA;AAAA,MACJ,QAAA;AAAA,MACA,IAAI,cAAA,CAAe,QAAA,EAAU,SAAS,QAAA,GAAW,QAAQ,KAAK,YAAY;AAAA,KAC5E;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT","file":"batch-N2XDYZED.js","sourcesContent":["/**\n * `Agent.batch(prompts, options)` core (ADRs D134-D140).\n *\n * Fans out N prompts via bounded concurrency, isolates failures per-prompt,\n * preserves input order in the result array, supports streaming callbacks\n * + AbortSignal. The credential pool (D131) is shared across all\n * in-flight agents via `withCredentialPool` ALS scope (EC-A fix).\n *\n * @internal\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { ConfigurationError, TheokitAgentError } from \"../../errors.js\";\nimport { diag } from \"../../internal/diagnostics.js\";\nimport { CredentialPool, newPooledCredential } from \"../../internal/llm/credential-pool.js\";\nimport { withCredentialPool } from \"../../internal/llm/credential-pool-context.js\";\nimport type { CredentialPoolStrategy } from \"../../internal/llm/credential-pool-types.js\";\nimport {\n submit as taskRegistrySubmit,\n subscribe as taskRegistrySubscribe,\n} from \"../../internal/task/registry.js\";\nimport type { AgentOptions, SDKAgent } from \"../../types/agent.js\";\nimport type { BatchItem, BatchOptions, BatchProgress, BatchResult } from \"../../types/batch.js\";\nimport { createSemaphore } from \"../concurrency/async-semaphore.js\";\n\n/** DI contract — keeps batch.ts cycle-free from agent.ts. @internal */\ninterface BatchDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n}\n\n/**\n * Pre-flight boundary validation for `Agent.batch` (arch-review Gap 3).\n *\n * Mirrors the in-repo `validateAgentOptions` / `validateCronExpression`\n * pattern: throws `ConfigurationError` with a stable code on the first\n * violation, returns silently otherwise. Pure — no I/O.\n *\n * Rules:\n * - `concurrency`, when provided, must be a positive integer (rejects\n * 0/negative/non-integer/NaN/Infinity). Previously this was caught only\n * incidentally deep inside `createSemaphore` with a leaky \"permits\"\n * message, AND after task wrapping (dangling Task on invalid input).\n * - every prompt item must carry a non-empty string prompt. Previously\n * `normalizeItem` passed `prompt: \"\"` / non-string straight to\n * `agent.send`. (Whitespace-only strings are intentionally NOT rejected —\n * an empty string is a structural error; judging content is not this\n * validator's job, and the repo's property tests treat any length>=1\n * string as a valid prompt.)\n *\n * @internal\n */\nexport function validateBatchInput(\n prompts: ReadonlyArray<string | BatchItem>,\n options: BatchOptions,\n): void {\n const { concurrency } = options;\n if (concurrency !== undefined && (!Number.isInteger(concurrency) || concurrency < 1)) {\n throw new ConfigurationError(\n `Agent.batch concurrency must be a positive integer, got ${concurrency}`,\n { code: \"invalid_concurrency\" },\n );\n }\n for (let i = 0; i < prompts.length; i++) {\n const item = prompts[i];\n const prompt = typeof item === \"string\" ? item : item?.prompt;\n if (typeof prompt !== \"string\" || prompt.length === 0) {\n throw new ConfigurationError(`Agent.batch prompt at index ${i} must be a non-empty string`, {\n code: \"invalid_batch_item\",\n });\n }\n }\n}\n\n/**\n * Run N prompts in parallel with bounded concurrency.\n *\n * @internal\n */\nexport async function batchImpl(\n prompts: ReadonlyArray<string | BatchItem>,\n options: BatchOptions,\n deps: BatchDeps,\n): Promise<BatchResult[]> {\n // EC-1: empty array → no work, no agents created.\n if (prompts.length === 0) return [];\n\n // Pre-flight boundary validation (arch-review Gap 3). MUST run before pool\n // build AND before wrapBatchAsTask so invalid input never registers a\n // dangling Task or builds a credential pool (fail-fast, Rule 8).\n validateBatchInput(prompts, options);\n\n // EC-A fix: build credential pools ONCE and share via AsyncLocalStorage.\n // Without this each Agent.create() would build its own pool from identical\n // apiKeys → 4× rate-limit wastage per concurrency window.\n const sharedPools = buildPoolsFromApiKeys(\n options.providers?.apiKeys,\n options.providers?.credentialPoolStrategy,\n );\n const exec = (): Promise<BatchResult[]> => runBatch(prompts, options, deps);\n const withPool = (): Promise<BatchResult[]> =>\n sharedPools.size > 0 ? withCredentialPool(sharedPools, exec) : exec();\n // T3.3: opt-in Task wrapping (ADRs D363, D374). Register the whole\n // batch as a single Task (kind=\"batch\") with `b-` prefix (D368/EC-5).\n if (options.task !== undefined) {\n return wrapBatchAsTask(prompts.length, options.task, withPool);\n }\n return withPool();\n}\n\n/**\n * Raises the typed error for a terminal failure event, and returns for anything else.\n *\n * Split out of {@link wrapBatchAsTask} so the wait loop reads as \"finished -> results, terminal\n * failure -> throw\" rather than as three inlined branches; the failure vocabulary is one concern and\n * lives in one place.\n */\nfunction throwIfTerminalFailure(\n id: string,\n event: { type: string } & Record<string, unknown>,\n): void {\n if (event.type === \"errored\") {\n const error = event.error as { message: string; code?: string };\n throw new TheokitAgentError(`Batch task ${id} failed: ${error.message}`, {\n code: \"batch_task_failed\",\n protoErrorCode: error.code,\n });\n }\n if (event.type === \"cancelled\") {\n const reason = event.reason as string | undefined;\n throw new TheokitAgentError(\n `Batch task ${id} was cancelled${reason === undefined ? \"\" : `: ${reason}`}`,\n { code: \"batch_task_cancelled\" },\n );\n }\n}\n\nasync function wrapBatchAsTask(\n total: number,\n taskOpt: true | { id?: string; meta?: Record<string, unknown> },\n exec: () => Promise<BatchResult[]>,\n): Promise<BatchResult[]> {\n const opts = taskOpt === true ? {} : taskOpt;\n const id = opts.id ?? `b-${randomUUID()}`;\n const meta: Record<string, unknown> = {\n total,\n ...(opts.meta ?? {}),\n };\n let results: BatchResult[] = [];\n await taskRegistrySubmit({\n kind: \"batch\",\n work: async (ctx) => {\n results = await exec();\n const succeeded = results.filter((r) => r.ok).length;\n const failed = results.length - succeeded;\n ctx.emit({ total: results.length, succeeded, failed });\n return { total: results.length, succeeded, failed };\n },\n id,\n meta,\n allowReservedPrefix: true,\n });\n // `submit` returns immediately with a queued handle, so this waits for the task's own terminal\n // EVENT rather than polling its state.\n //\n // What this replaced, and why the replacement is not just tidier: the wait was\n // `for (let i = 0; i < 5000; i++) { ...get(id)...; await sleep(5) }` followed by an unconditional\n // `return results`, and `results` is assigned only inside the `work` callback above. So THREE\n // distinct failures produced one indistinguishable value — the work threw, the task was\n // cancelled, or the budget elapsed — and each returned `[]` on a RESOLVED promise, which a caller\n // cannot tell apart from `Agent.batch([])`. The registry had already recorded the failure as\n // `{ code, message }` on the terminal event; the loop read only `handle.state` and dropped it.\n //\n // The budget was not a safety net either. 5000 iterations of a 5 ms sleep is ~25 s, and a batch\n // legitimately longer than that would trip it and return `[]` — the bound generated the bug it\n // appeared to guard against. A task's own lifecycle is the honest bound, and `subscribe` drains\n // the buffered events first (`subscribe.ts:23`), so a task that finished before this line runs\n // still delivers its terminal event rather than hanging.\n for await (const event of taskRegistrySubscribe(id)) {\n if (event.type === \"finished\") return results;\n throwIfTerminalFailure(id, event);\n }\n // The registry's contract says the stream ends only after a terminal event, so this is\n // unreachable. It throws rather than returning `results` because returning here would restore the\n // exact silent-empty-array path this function was rewritten to remove.\n throw new TheokitAgentError(`Batch task ${id} ended without a terminal event`, {\n code: \"batch_task_no_terminal_event\",\n });\n}\n\nasync function runBatch(\n prompts: ReadonlyArray<string | BatchItem>,\n options: BatchOptions,\n deps: BatchDeps,\n): Promise<BatchResult[]> {\n const requested = options.concurrency ?? 4;\n // createSemaphore throws on invalid (EC-2).\n // EC-3: cap to prompts.length to avoid idle workers.\n const effective = Math.min(requested, prompts.length);\n const semaphore = createSemaphore(effective);\n const items = prompts.map(normalizeItem);\n const results: BatchResult[] = new Array(items.length);\n const counters = { completed: 0, failed: 0 };\n let aborted = false;\n\n const onAbort = (): void => {\n aborted = true;\n };\n options.signal?.addEventListener(\"abort\", onAbort);\n // EC-C: pre-aborted signal — treat as already-aborted before any work.\n if (options.signal?.aborted === true) aborted = true;\n\n try {\n await Promise.all(\n items.map(async (item, index) => {\n const release = await semaphore.acquire();\n try {\n if (aborted) {\n results[index] = abortResult(item, index, options.signal);\n } else {\n results[index] = await runOne(item, index, options, deps);\n }\n if (results[index].ok) counters.completed += 1;\n else counters.failed += 1;\n // B-110 (measured 2026-08-19): `onResult` used to run AFTER `release()`, so a caller who\n // asked for `concurrency: 1` still got overlapping `onResult` invocations — the permit was\n // already returned before the callback ran. `concurrency` is documented (`types/batch.ts`)\n // to bound the whole per-item lifecycle, callback included, so the permit is now held\n // until `onResult` finishes: this call moved inside the `try` the `finally` below wraps.\n await safeCallResult(options.onResult, results[index]);\n } finally {\n release();\n }\n safeCallProgress(options.onProgress, {\n total: items.length,\n completed: counters.completed,\n failed: counters.failed,\n inFlight: semaphore.inFlight(),\n pending: Math.max(0, semaphore.pending() - semaphore.inFlight()),\n });\n }),\n );\n } finally {\n options.signal?.removeEventListener(\"abort\", onAbort);\n }\n\n return options.filter ? results.filter(options.filter) : results;\n}\n\nasync function runOne(\n item: BatchItem,\n index: number,\n options: BatchOptions,\n deps: BatchDeps,\n): Promise<BatchResult> {\n const t0 = Date.now();\n const agentOpts = buildAgentOptions(item, options);\n\n try {\n const agent = await deps.create(agentOpts);\n try {\n const run = await agent.send(item.prompt);\n const result = await run.wait();\n return {\n ok: true,\n index,\n prompt: item.prompt,\n result,\n ...(item.metadata !== undefined ? { metadata: item.metadata } : {}),\n durationMs: Date.now() - t0,\n };\n } finally {\n // EC-8: dispose failure → stderr warn, don't fail the result.\n try {\n await agent.dispose();\n } catch (disposeErr) {\n // theokit#147 — the interceptable channel; a batch run must not write onto a TUI's frame.\n diag(\n `[theokit-sdk] batch: agent.dispose failed for prompt ${index}: ${\n disposeErr instanceof Error ? disposeErr.message : String(disposeErr)\n }\\n`,\n );\n }\n }\n } catch (err) {\n return {\n ok: false,\n index,\n prompt: item.prompt,\n error: toTheokitError(err),\n ...(item.metadata !== undefined ? { metadata: item.metadata } : {}),\n durationMs: Date.now() - t0,\n };\n }\n}\n\n/** Every key `BatchOptions` adds on top of `AgentOptions`, derived rather than listed twice. */\ntype BatchOnlyKey = Exclude<keyof BatchOptions, keyof AgentOptions>;\n\n/**\n * The batch-only keys, as values — `buildAgentOptions` has to strip them at runtime and a type\n * cannot do that.\n *\n * Both halves of this declaration are load-bearing, in opposite directions:\n *\n * - `satisfies readonly BatchOnlyKey[]` rejects a key here that is NOT batch-only, so a rename in\n * the interface breaks this list instead of silently stripping a field that should be forwarded.\n * - `NoUnlistedBatchOnlyKey` below rejects a batch-only key MISSING from here, which is the\n * direction that actually bites: adding a seventh option to `BatchOptions` and forgetting this\n * function forwards it into `AgentOptions`, where TypeScript's excess-property check does not\n * fire on a spread and `validateAgentOptions` either rejects it or carries it into every agent\n * the batch creates.\n *\n * The keys are NOT derived into the interface as a mapped type, which would collapse both\n * representations into one: each of the six carries several paragraphs of public API documentation,\n * and a mapped type cannot hold them.\n */\nconst BATCH_ONLY_KEYS = [\n \"concurrency\",\n \"filter\",\n \"onResult\",\n \"onProgress\",\n \"signal\",\n \"task\",\n] as const satisfies readonly BatchOnlyKey[];\n\n/** Compile-time only: resolves to `never` unless every batch-only key is listed above. */\ntype NoUnlistedBatchOnlyKey =\n Exclude<BatchOnlyKey, (typeof BATCH_ONLY_KEYS)[number]> extends never\n ? true\n : [\n \"batch-only key missing from BATCH_ONLY_KEYS\",\n Exclude<BatchOnlyKey, (typeof BATCH_ONLY_KEYS)[number]>,\n ];\n\nconst _batchKeysAreExhaustive: NoUnlistedBatchOnlyKey = true;\nvoid _batchKeysAreExhaustive;\n\nfunction buildAgentOptions(item: BatchItem, options: BatchOptions): AgentOptions {\n const rest: Record<string, unknown> = { ...options };\n for (const key of BATCH_ONLY_KEYS) delete rest[key];\n const agentOpts = rest as AgentOptions;\n if (item.systemPrompt !== undefined) {\n return { ...agentOpts, systemPrompt: item.systemPrompt };\n }\n return agentOpts;\n}\n\nfunction normalizeItem(promptOrItem: string | BatchItem): BatchItem {\n return typeof promptOrItem === \"string\" ? { prompt: promptOrItem } : promptOrItem;\n}\n\nfunction abortResult(item: BatchItem, index: number, signal?: AbortSignal): BatchResult {\n // EC-D: propagate signal.reason when set (preserves caller's error).\n let error: TheokitAgentError;\n if (signal?.reason instanceof TheokitAgentError) {\n error = signal.reason;\n } else if (signal?.reason instanceof Error) {\n error = new TheokitAgentError(signal.reason.message, {\n code: \"aborted\",\n cause: signal.reason,\n });\n } else {\n error = new TheokitAgentError(\"Batch aborted via AbortSignal\", { code: \"aborted\" });\n }\n return {\n ok: false,\n index,\n prompt: item.prompt,\n error,\n ...(item.metadata !== undefined ? { metadata: item.metadata } : {}),\n durationMs: 0,\n };\n}\n\nfunction toTheokitError(err: unknown): TheokitAgentError {\n if (err instanceof TheokitAgentError) return err;\n if (err instanceof Error) {\n return new TheokitAgentError(err.message, { code: \"unknown\", cause: err });\n }\n return new TheokitAgentError(String(err), { code: \"unknown\" });\n}\n\nasync function safeCallResult(cb: BatchOptions[\"onResult\"], result: BatchResult): Promise<void> {\n if (cb === undefined) return;\n try {\n await cb(result);\n } catch (err) {\n diag(\n `[theokit-sdk] batch: onResult callback threw: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n );\n }\n}\n\nfunction safeCallProgress(cb: BatchOptions[\"onProgress\"], progress: BatchProgress): void {\n if (cb === undefined) return;\n try {\n cb(progress);\n } catch (err) {\n diag(\n `[theokit-sdk] batch: onProgress callback threw: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n );\n }\n}\n\n/**\n * EC-A: construct shared pools from options.apiKeys. Empty/invalid → empty Map.\n *\n * @internal\n */\nfunction buildPoolsFromApiKeys(\n apiKeys: Record<string, string[]> | undefined,\n strategy: Record<string, CredentialPoolStrategy> | undefined,\n): Map<string, CredentialPool> {\n const pools = new Map<string, CredentialPool>();\n if (apiKeys === undefined) return pools;\n for (const [provider, keys] of Object.entries(apiKeys)) {\n if (!Array.isArray(keys)) continue;\n const filtered = keys.filter((k): k is string => typeof k === \"string\" && k.length > 0);\n if (filtered.length < 2) continue; // 1-key pools aren't pools\n const entries = filtered.map((token, i) =>\n newPooledCredential({ provider, accessToken: token, priority: i, source: \"manual\" }),\n );\n pools.set(\n provider,\n new CredentialPool(provider, entries, strategy?.[provider] ?? \"fill_first\"),\n );\n }\n return pools;\n}\n"]}
@@ -2,10 +2,10 @@
2
2
 
3
3
  var chunkL7JPXZ2C_cjs = require('./chunk-L7JPXZ2C.cjs');
4
4
  require('./chunk-BUUUWQMB.cjs');
5
- var chunkSXH37C7X_cjs = require('./chunk-SXH37C7X.cjs');
5
+ var chunk55LLQFHW_cjs = require('./chunk-55LLQFHW.cjs');
6
6
  require('./chunk-QOGNZMHD.cjs');
7
7
  var chunkFLDMPVUC_cjs = require('./chunk-FLDMPVUC.cjs');
8
- require('./chunk-ZF2LDKQQ.cjs');
8
+ require('./chunk-U3DW3WDE.cjs');
9
9
  require('./chunk-BWYC7RZG.cjs');
10
10
  require('./chunk-ZOFRNNZD.cjs');
11
11
  var chunkCEGU5AVD_cjs = require('./chunk-CEGU5AVD.cjs');
@@ -38,7 +38,7 @@ async function batchImpl(prompts, options, deps) {
38
38
  options.providers?.credentialPoolStrategy
39
39
  );
40
40
  const exec = () => runBatch(prompts, options, deps);
41
- const withPool = () => sharedPools.size > 0 ? chunkSXH37C7X_cjs.withCredentialPool(sharedPools, exec) : exec();
41
+ const withPool = () => sharedPools.size > 0 ? chunk55LLQFHW_cjs.withCredentialPool(sharedPools, exec) : exec();
42
42
  if (options.task !== void 0) {
43
43
  return wrapBatchAsTask(prompts.length, options.task, withPool);
44
44
  }
@@ -247,11 +247,11 @@ function buildPoolsFromApiKeys(apiKeys, strategy) {
247
247
  const filtered = keys.filter((k) => typeof k === "string" && k.length > 0);
248
248
  if (filtered.length < 2) continue;
249
249
  const entries = filtered.map(
250
- (token, i) => chunkSXH37C7X_cjs.newPooledCredential({ provider, accessToken: token, priority: i, source: "manual" })
250
+ (token, i) => chunk55LLQFHW_cjs.newPooledCredential({ provider, accessToken: token, priority: i, source: "manual" })
251
251
  );
252
252
  pools.set(
253
253
  provider,
254
- new chunkSXH37C7X_cjs.CredentialPool(provider, entries, strategy?.[provider] ?? "fill_first")
254
+ new chunk55LLQFHW_cjs.CredentialPool(provider, entries, strategy?.[provider] ?? "fill_first")
255
255
  );
256
256
  }
257
257
  return pools;
@@ -259,5 +259,5 @@ function buildPoolsFromApiKeys(apiKeys, strategy) {
259
259
 
260
260
  exports.batchImpl = batchImpl;
261
261
  exports.validateBatchInput = validateBatchInput;
262
- //# sourceMappingURL=batch-IZ5EDKJ5.cjs.map
263
- //# sourceMappingURL=batch-IZ5EDKJ5.cjs.map
262
+ //# sourceMappingURL=batch-VFR2MAUE.cjs.map
263
+ //# sourceMappingURL=batch-VFR2MAUE.cjs.map