@theokit/sdk 5.9.0 → 5.9.2

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 (168) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/dist/{agent-6STOEBGQ.js → agent-GZVZXKME.js} +18 -17
  3. package/dist/{agent-6STOEBGQ.js.map → agent-GZVZXKME.js.map} +1 -1
  4. package/dist/{agent-ZM4FDDL7.cjs → agent-WQ4LLTSY.cjs} +19 -18
  5. package/dist/{agent-ZM4FDDL7.cjs.map → agent-WQ4LLTSY.cjs.map} +1 -1
  6. package/dist/agent-session-store-ODD3IZCW.js +6 -0
  7. package/dist/{agent-session-store-AFML3AXC.js.map → agent-session-store-ODD3IZCW.js.map} +1 -1
  8. package/dist/agent-session-store-SVEJHSUA.cjs +23 -0
  9. package/dist/{agent-session-store-MTSIY3MH.cjs.map → agent-session-store-SVEJHSUA.cjs.map} +1 -1
  10. package/dist/auth/index.cjs +8 -7
  11. package/dist/auth/index.cjs.map +1 -1
  12. package/dist/auth/index.js +3 -2
  13. package/dist/auth/index.js.map +1 -1
  14. package/dist/{chunk-TC4RWP3Y.js → chunk-47Z6LP3I.js} +3 -3
  15. package/dist/{chunk-TC4RWP3Y.js.map → chunk-47Z6LP3I.js.map} +1 -1
  16. package/dist/{chunk-DDRX4LYS.js → chunk-7QJYKVP6.js} +3 -3
  17. package/dist/{chunk-DDRX4LYS.js.map → chunk-7QJYKVP6.js.map} +1 -1
  18. package/dist/{chunk-TTBIQTO5.cjs → chunk-DLUCTZ56.cjs} +15 -15
  19. package/dist/{chunk-TTBIQTO5.cjs.map → chunk-DLUCTZ56.cjs.map} +1 -1
  20. package/dist/chunk-EHD25JBZ.cjs +10 -0
  21. package/dist/chunk-EHD25JBZ.cjs.map +1 -0
  22. package/dist/{chunk-NOO6GZTZ.js → chunk-EVH3OUMY.js} +13 -12
  23. package/dist/chunk-EVH3OUMY.js.map +1 -0
  24. package/dist/{chunk-5522X223.js → chunk-EXI7EHDN.js} +4 -4
  25. package/dist/{chunk-5522X223.js.map → chunk-EXI7EHDN.js.map} +1 -1
  26. package/dist/{chunk-PSLCVSCS.cjs → chunk-FR6COQXZ.cjs} +6 -6
  27. package/dist/{chunk-PSLCVSCS.cjs.map → chunk-FR6COQXZ.cjs.map} +1 -1
  28. package/dist/{chunk-JOFVLOFY.js → chunk-FTZTZBCU.js} +12 -4
  29. package/dist/chunk-FTZTZBCU.js.map +1 -0
  30. package/dist/{chunk-HOHR75KF.js → chunk-HI3W37FY.js} +4 -3
  31. package/dist/chunk-HI3W37FY.js.map +1 -0
  32. package/dist/chunk-HU666T3Q.cjs +1891 -0
  33. package/dist/chunk-HU666T3Q.cjs.map +1 -0
  34. package/dist/{chunk-53RDNK3H.js → chunk-I2ORT6QD.js} +3 -3
  35. package/dist/{chunk-53RDNK3H.js.map → chunk-I2ORT6QD.js.map} +1 -1
  36. package/dist/{chunk-BM6PDJW3.cjs → chunk-JU76WCW7.cjs} +113 -112
  37. package/dist/chunk-JU76WCW7.cjs.map +1 -0
  38. package/dist/{chunk-J4SA2ZEJ.cjs → chunk-KIKKTW5O.cjs} +4 -4
  39. package/dist/{chunk-J4SA2ZEJ.cjs.map → chunk-KIKKTW5O.cjs.map} +1 -1
  40. package/dist/{chunk-5WR33BHA.cjs → chunk-KXKT3HSD.cjs} +4 -4
  41. package/dist/{chunk-5WR33BHA.cjs.map → chunk-KXKT3HSD.cjs.map} +1 -1
  42. package/dist/{chunk-UKBBYVNS.js → chunk-M2CCHC66.js} +3 -3
  43. package/dist/{chunk-UKBBYVNS.js.map → chunk-M2CCHC66.js.map} +1 -1
  44. package/dist/{chunk-OCEQ6DW2.cjs → chunk-N6OEX5TN.cjs} +2 -2
  45. package/dist/chunk-N6OEX5TN.cjs.map +1 -0
  46. package/dist/{chunk-QDQQYRJI.js → chunk-N7KYUNFO.js} +3 -3
  47. package/dist/{chunk-QDQQYRJI.js.map → chunk-N7KYUNFO.js.map} +1 -1
  48. package/dist/{chunk-7GDHFV2M.js → chunk-OPAKPEPG.js} +2 -2
  49. package/dist/chunk-OPAKPEPG.js.map +1 -0
  50. package/dist/{chunk-UNZOJVVC.js → chunk-OZLQ6ZFM.js} +3 -3
  51. package/dist/{chunk-UNZOJVVC.js.map → chunk-OZLQ6ZFM.js.map} +1 -1
  52. package/dist/{chunk-PYFBS6OQ.js → chunk-PEIV7LOU.js} +22 -21
  53. package/dist/chunk-PEIV7LOU.js.map +1 -0
  54. package/dist/chunk-Q7GYMXVC.js +8 -0
  55. package/dist/chunk-Q7GYMXVC.js.map +1 -0
  56. package/dist/{chunk-ARMFXTY6.cjs → chunk-QY3CIMUV.cjs} +34 -33
  57. package/dist/chunk-QY3CIMUV.cjs.map +1 -0
  58. package/dist/{chunk-B3XXQX6L.cjs → chunk-RX3CFWQ2.cjs} +6 -6
  59. package/dist/{chunk-B3XXQX6L.cjs.map → chunk-RX3CFWQ2.cjs.map} +1 -1
  60. package/dist/chunk-SGC7LSHF.cjs +18 -0
  61. package/dist/{chunk-R3ZQBPA5.cjs.map → chunk-SGC7LSHF.cjs.map} +1 -1
  62. package/dist/{chunk-RA7IE4NK.cjs → chunk-SKDNCTXG.cjs} +4 -3
  63. package/dist/chunk-SKDNCTXG.cjs.map +1 -0
  64. package/dist/chunk-SVCPJRUB.js +1874 -0
  65. package/dist/chunk-SVCPJRUB.js.map +1 -0
  66. package/dist/{chunk-EJROML3Q.js → chunk-TX56N7FR.js} +4 -3
  67. package/dist/chunk-TX56N7FR.js.map +1 -0
  68. package/dist/{chunk-76PIKR4P.cjs → chunk-VZ2JZ2EH.cjs} +5 -5
  69. package/dist/{chunk-76PIKR4P.cjs.map → chunk-VZ2JZ2EH.cjs.map} +1 -1
  70. package/dist/{chunk-T5KOSR5Y.cjs → chunk-X7Z2FEI7.cjs} +8 -8
  71. package/dist/{chunk-T5KOSR5Y.cjs.map → chunk-X7Z2FEI7.cjs.map} +1 -1
  72. package/dist/{chunk-2WXHA33T.js → chunk-XERM7PDQ.js} +3 -3
  73. package/dist/{chunk-2WXHA33T.js.map → chunk-XERM7PDQ.js.map} +1 -1
  74. package/dist/{chunk-KTA7YTZQ.cjs → chunk-XKZFIP7Z.cjs} +4 -4
  75. package/dist/{chunk-KTA7YTZQ.cjs.map → chunk-XKZFIP7Z.cjs.map} +1 -1
  76. package/dist/{chunk-MEUBLCM4.cjs → chunk-YEHQ3SIC.cjs} +4 -3
  77. package/dist/chunk-YEHQ3SIC.cjs.map +1 -0
  78. package/dist/{chunk-YIFFF23U.cjs → chunk-ZAM7BJXJ.cjs} +5 -5
  79. package/dist/{chunk-YIFFF23U.cjs.map → chunk-ZAM7BJXJ.cjs.map} +1 -1
  80. package/dist/{chunk-R2C3HXR3.js → chunk-ZDF2IJKC.js} +3 -3
  81. package/dist/{chunk-R2C3HXR3.js.map → chunk-ZDF2IJKC.js.map} +1 -1
  82. package/dist/{chunk-PQCTDMUI.js → chunk-ZHWKT2NI.js} +3 -3
  83. package/dist/{chunk-PQCTDMUI.js.map → chunk-ZHWKT2NI.js.map} +1 -1
  84. package/dist/{chunk-GZV6AVRL.cjs → chunk-ZWACQM5U.cjs} +11 -3
  85. package/dist/chunk-ZWACQM5U.cjs.map +1 -0
  86. package/dist/{compact-session-RBPLUPCK.cjs → compact-session-4QHBBGEY.cjs} +16 -15
  87. package/dist/{compact-session-RBPLUPCK.cjs.map → compact-session-4QHBBGEY.cjs.map} +1 -1
  88. package/dist/{compact-session-2N3ZYJTW.js → compact-session-PVAWTKKL.js} +7 -6
  89. package/dist/{compact-session-2N3ZYJTW.js.map → compact-session-PVAWTKKL.js.map} +1 -1
  90. package/dist/context/index.cjs +6 -6
  91. package/dist/context/index.js +3 -3
  92. package/dist/context-3FZRAO5K.js +7 -0
  93. package/dist/{context-SXR2HLHT.js.map → context-3FZRAO5K.js.map} +1 -1
  94. package/dist/{context-ZOULM2RB.cjs → context-B5J4GX2F.cjs} +7 -7
  95. package/dist/{context-ZOULM2RB.cjs.map → context-B5J4GX2F.cjs.map} +1 -1
  96. package/dist/cron.cjs +18 -17
  97. package/dist/cron.js +17 -16
  98. package/dist/eval.cjs +17 -16
  99. package/dist/eval.cjs.map +1 -1
  100. package/dist/eval.js +16 -15
  101. package/dist/eval.js.map +1 -1
  102. package/dist/fs-session-store-LCZBM3LT.js +10 -0
  103. package/dist/{fs-session-store-STZZFXH2.js.map → fs-session-store-LCZBM3LT.js.map} +1 -1
  104. package/dist/{fs-session-store-JHBJFKVV.cjs → fs-session-store-SVEMRE4K.cjs} +5 -5
  105. package/dist/{fs-session-store-JHBJFKVV.cjs.map → fs-session-store-SVEMRE4K.cjs.map} +1 -1
  106. package/dist/{index-manager-ONQJSWX5.js → index-manager-6B2UF5S3.js} +5 -5
  107. package/dist/{index-manager-ONQJSWX5.js.map → index-manager-6B2UF5S3.js.map} +1 -1
  108. package/dist/{index-manager-ZGJN25FD.cjs → index-manager-M3FHJCHQ.cjs} +6 -6
  109. package/dist/{index-manager-ZGJN25FD.cjs.map → index-manager-M3FHJCHQ.cjs.map} +1 -1
  110. package/dist/index.cjs +58 -57
  111. package/dist/index.cjs.map +1 -1
  112. package/dist/index.d.cts +30 -3
  113. package/dist/index.d.ts +30 -3
  114. package/dist/index.js +21 -20
  115. package/dist/index.js.map +1 -1
  116. package/dist/{inject-session-YNNOE3O6.js → inject-session-O24XGRR6.js} +5 -5
  117. package/dist/{inject-session-YNNOE3O6.js.map → inject-session-O24XGRR6.js.map} +1 -1
  118. package/dist/{inject-session-3FPXJDJP.cjs → inject-session-OMLFL2V3.cjs} +7 -7
  119. package/dist/{inject-session-3FPXJDJP.cjs.map → inject-session-OMLFL2V3.cjs.map} +1 -1
  120. package/dist/internal/memory/adapters/index.cjs +3 -2
  121. package/dist/internal/memory/adapters/index.js +2 -1
  122. package/dist/internal/memory/storage/index.cjs +32 -32
  123. package/dist/internal/memory/storage/index.js +3 -3
  124. package/dist/internal/persistence/persistence-schema.d.cts +1 -1
  125. package/dist/internal/persistence/persistence-schema.d.ts +1 -1
  126. package/dist/internal/providers/catalog-loader.d.ts +30 -3
  127. package/dist/internal/runtime/hooks/hooks-source.d.ts +24 -0
  128. package/dist/internal/runtime-fetch.d.ts +1 -0
  129. package/dist/models.cjs +12 -11
  130. package/dist/models.cjs.map +1 -1
  131. package/dist/models.js +4 -3
  132. package/dist/models.js.map +1 -1
  133. package/dist/persistence.cjs +7 -7
  134. package/dist/persistence.js +2 -2
  135. package/dist/providers.cjs +6 -5
  136. package/dist/providers.js +4 -3
  137. package/dist/{session-transcript-VTBTCGQX.js → session-transcript-AR7IBICT.js} +3 -3
  138. package/dist/{session-transcript-VTBTCGQX.js.map → session-transcript-AR7IBICT.js.map} +1 -1
  139. package/dist/{session-transcript-LGHSNVY5.cjs → session-transcript-RACG7BK2.cjs} +16 -16
  140. package/dist/{session-transcript-LGHSNVY5.cjs.map → session-transcript-RACG7BK2.cjs.map} +1 -1
  141. package/dist/subscription/index.cjs +2 -1
  142. package/dist/subscription/index.cjs.map +1 -1
  143. package/dist/subscription/index.js +2 -1
  144. package/dist/subscription/index.js.map +1 -1
  145. package/docs/error-codes.md +16 -16
  146. package/package.json +2 -2
  147. package/dist/agent-session-store-AFML3AXC.js +0 -6
  148. package/dist/agent-session-store-MTSIY3MH.cjs +0 -23
  149. package/dist/chunk-7GDHFV2M.js.map +0 -1
  150. package/dist/chunk-ARMFXTY6.cjs.map +0 -1
  151. package/dist/chunk-BM6PDJW3.cjs.map +0 -1
  152. package/dist/chunk-EJROML3Q.js.map +0 -1
  153. package/dist/chunk-GZV6AVRL.cjs.map +0 -1
  154. package/dist/chunk-HOHR75KF.js.map +0 -1
  155. package/dist/chunk-JOFVLOFY.js.map +0 -1
  156. package/dist/chunk-MEUBLCM4.cjs.map +0 -1
  157. package/dist/chunk-MFZODA5Y.js +0 -583
  158. package/dist/chunk-MFZODA5Y.js.map +0 -1
  159. package/dist/chunk-NOO6GZTZ.js.map +0 -1
  160. package/dist/chunk-OCEQ6DW2.cjs.map +0 -1
  161. package/dist/chunk-PYFBS6OQ.js.map +0 -1
  162. package/dist/chunk-R3ZQBPA5.cjs +0 -18
  163. package/dist/chunk-RA7IE4NK.cjs.map +0 -1
  164. package/dist/chunk-YRJA2POB.cjs +0 -601
  165. package/dist/chunk-YRJA2POB.cjs.map +0 -1
  166. package/dist/context-SXR2HLHT.js +0 -7
  167. package/dist/fs-session-store-STZZFXH2.js +0 -10
  168. package/dist/provider-catalog.json +0 -1295
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/subscription/define-subscription.ts","../../src/subscription/internal/sse-parser.ts","../../src/subscription/types.ts","../../src/subscription/theokit-subscribe.ts"],"names":["TheokitAgentError"],"mappings":";;;;;;AAoEO,SAAS,mBACd,IAAA,EACyC;AACzC,EAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AAC7C,IAAA,MAAM,IAAI,UAAU,gDAAgD,CAAA;AAAA,EACtE;AACA,EAAA,IAAI,KAAK,KAAA,KAAU,MAAA,IAAa,OAAO,IAAA,CAAK,KAAA,CAAM,cAAc,UAAA,EAAY;AAC1E,IAAA,MAAM,IAAI,UAAU,kEAAkE,CAAA;AAAA,EACxF;AACA,EAAA,IAAI,KAAK,MAAA,KAAW,MAAA,IAAa,OAAO,IAAA,CAAK,MAAA,CAAO,cAAc,UAAA,EAAY;AAC5E,IAAA,MAAM,IAAI,UAAU,mEAAmE,CAAA;AAAA,EACzF;AACA,EAAA,IAAI,OAAO,IAAA,CAAK,OAAA,KAAY,UAAA,EAAY;AACtC,IAAA,MAAM,IAAI,UAAU,sEAAsE,CAAA;AAAA,EAC5F;AACA,EAAA,OAAO;AAAA,IACL,GAAI,KAAK,IAAA,KAAS,MAAA,GAAY,EAAE,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK,GAAI,EAAC;AAAA,IACrD,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,SAAS,IAAA,CA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,iBAAA,EAAmB;AACtB,MAAA,IAAI;AACF,QAAA,MAAM,OAAO,MAAA,EAAO;AAAA,MACtB,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF;AACA,IAAA,MAAA,CAAO,WAAA,EAAY;AAAA,EACrB;AACF;AAEA,SAAS,KAAA,CAAM,IAAY,MAAA,EAAqC;AAC9D,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,MAAA,CAAO,IAAI,KAAA,CAAM,SAAS,CAAC,CAAA;AAC3B,MAAA;AAAA,IACF;AACA,IAAA,MAAM,CAAA,GAAI,WAAW,MAAM;AACzB,MAAA,MAAA,EAAQ,mBAAA,CAAoB,SAAS,OAAO,CAAA;AAC5C,MAAA,OAAA,EAAQ;AAAA,IACV,GAAG,EAAE,CAAA;AACL,IAAA,MAAM,UAAU,MAAM;AACpB,MAAA,YAAA,CAAa,CAAC,CAAA;AACd,MAAA,MAAA,CAAO,IAAI,KAAA,CAAM,SAAS,CAAC,CAAA;AAAA,IAC7B,CAAA;AACA,IAAA,MAAA,EAAQ,iBAAiB,OAAA,EAAS,OAAA,EAAS,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,EAC3D,CAAC,CAAA;AACH","file":"index.cjs","sourcesContent":["/**\n * `defineSubscription` DSL (G8 public API) — `@theokit/sdk`.\n *\n * Per ADR D426 (AsyncGenerator handler + Zod input/output schemas).\n *\n * @public\n */\n\nimport type { SubscriptionCtx, SubscriptionDescriptor, TrackedEnvelope, ZodLike } from \"./types.js\";\n\n/**\n * Options accepted by {@link defineSubscription}.\n *\n * @public\n */\nexport interface DefineSubscriptionOptions<TInput, TOutput> {\n /** Optional explicit name. Falls back to filename derivation by the scanner. */\n name?: string;\n /** Zod schema validating subscription input. Required (typed RPC contract). */\n input: ZodLike<TInput>;\n /** Zod schema describing each output frame. Informational; not enforced per-frame. */\n output: ZodLike<TOutput>;\n /**\n * Handler that produces the subscription stream.\n *\n * Receives the validated input + {@link SubscriptionCtx}. Yielding a value\n * emits a plain output frame. Yielding a `tracked(id, payload)` envelope\n * additionally advertises a resume token to the client so reconnects can\n * resume from that point.\n */\n handler: (\n input: TInput,\n ctx: SubscriptionCtx,\n ) => AsyncGenerator<TOutput | TrackedEnvelope<TOutput>, void, void>;\n}\n\n/**\n * Define a typed subscription. Pair with `Theokit.subscribe(name, input)`\n * on the client side.\n *\n * Per ADR D426 — handler is `AsyncGenerator<TOutput | TrackedEnvelope<TOutput>>`.\n * The runtime validates input via `opts.input.safeParse` BEFORE invoking the\n * handler; failure throws {@link import('./types.js').SubscriptionInputError}.\n *\n * @example\n * ```ts\n * import { Subscription } from \"@theokit/sdk/subscription\";\n * import { z } from \"zod\";\n *\n * export default Subscription.create({\n * input: z.object({ topic: z.string() }),\n * output: z.object({ message: z.string(), ts: z.number() }),\n * async *handler(input, ctx) {\n * let cursor = ctx.lastEventId ?? \"0\";\n * while (!ctx.signal.aborted) {\n * const msgs = await fetchMessagesSince(input.topic, cursor);\n * for (const m of msgs) {\n * cursor = m.id;\n * yield ctx.tracked(m.id, { message: m.body, ts: m.ts });\n * }\n * await sleep(1000);\n * }\n * },\n * });\n * ```\n *\n * @public\n */\nexport function defineSubscription<TInput, TOutput>(\n opts: DefineSubscriptionOptions<TInput, TOutput>,\n): SubscriptionDescriptor<TInput, TOutput> {\n if (opts === null || typeof opts !== \"object\") {\n throw new TypeError(\"defineSubscription: options object is required\");\n }\n if (opts.input === undefined || typeof opts.input.safeParse !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.input must be a Zod schema (or ZodLike)\");\n }\n if (opts.output === undefined || typeof opts.output.safeParse !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.output must be a Zod schema (or ZodLike)\");\n }\n if (typeof opts.handler !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.handler must be an async generator function\");\n }\n return {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n input: opts.input,\n output: opts.output,\n handler: opts.handler,\n };\n}\n\n/** SE36 — `Subscription.create` replaces `defineSubscription` (ADR 0015). @public *\n * `Subscription.create` returns a **`SubscriptionDescriptor<TInput, TOutput>`**, not a\n * `Subscription`. The class is the namespace; the descriptor is the product.\n */\nexport class Subscription {\n private constructor() {}\n static create<TInput, TOutput>(\n opts: DefineSubscriptionOptions<TInput, TOutput>,\n ): SubscriptionDescriptor<TInput, TOutput> {\n return defineSubscription(opts);\n }\n}\n","/**\n * W3C SSE parser (G8 internal) — `@theokit/sdk`.\n *\n * Per ADR D428. Reads from `ReadableStream<Uint8Array>` or async iterable of\n * UTF-8 chunks; yields parsed {@link SSEvent} objects per W3C SSE spec.\n *\n * Independent of `internal/llm/sse.ts:parseSseStream` (LLM-specific a peer vendor AI\n * Data Stream v1; locked by D38). This parser handles the `id:` field needed\n * for tracked envelopes (G8 resume mechanism), which the LLM parser ignores.\n *\n * Reference: https://html.spec.whatwg.org/multipage/server-sent-events.html\n *\n * @internal\n */\n\nimport type { SSEvent } from \"./sse-encoder.js\";\n\nconst decoder = new TextDecoder(\"utf-8\");\n\n/**\n * Parse an async iterable of UTF-8 byte chunks into a stream of SSE events.\n *\n * Implements the W3C event stream parser:\n * - Lines are split by `\\n`, `\\r\\n`, or `\\r`\n * - Events are dispatched on blank line (no `:` and no field name)\n * - Fields: `event`, `data` (multi-line concat with `\\n`), `id`, `retry`\n * - Lines starting with `:` are comments (ignored, except dispatched as `comment`)\n * - Unknown fields silently ignored per spec\n *\n * Empty events (no fields) are NOT dispatched per spec.\n *\n * @internal\n */\nexport async function* parseSseW3C(\n source: AsyncIterable<Uint8Array>,\n): AsyncGenerator<SSEvent, void, void> {\n let buffer = \"\";\n let eventName: string | undefined;\n let dataLines: string[] = [];\n let id: string | undefined;\n let retry: number | undefined;\n let commentLines: string[] = [];\n let hasField = false;\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: dispatch builds SSEvent from per-field state per W3C spec — refactor candidate\n const dispatch = (): SSEvent | null => {\n if (!hasField) {\n // Blank line with no preceding fields → reset state, no dispatch (per spec § 9.2.6)\n eventName = undefined;\n dataLines = [];\n id = undefined;\n retry = undefined;\n commentLines = [];\n return null;\n }\n const chunk: SSEvent = {};\n if (eventName !== undefined) (chunk as { event?: string }).event = eventName;\n if (dataLines.length > 0) (chunk as { data?: string }).data = dataLines.join(\"\\n\");\n if (id !== undefined) (chunk as { id?: string }).id = id;\n if (retry !== undefined) (chunk as { retry?: number }).retry = retry;\n if (commentLines.length > 0) (chunk as { comment?: string }).comment = commentLines.join(\"\\n\");\n eventName = undefined;\n dataLines = [];\n id = undefined;\n retry = undefined;\n commentLines = [];\n hasField = false;\n return chunk;\n };\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: handleLine dispatches across all SSE field kinds per W3C spec — refactor candidate\n const handleLine = (line: string): SSEvent | null => {\n if (line === \"\") {\n return dispatch();\n }\n if (line.startsWith(\":\")) {\n // Comment line — per spec ignored, but we surface it for keepalive visibility.\n commentLines.push(line.slice(1).replace(/^ /, \"\"));\n hasField = true;\n return null;\n }\n const colonIdx = line.indexOf(\":\");\n let field: string;\n let value: string;\n if (colonIdx === -1) {\n field = line;\n value = \"\";\n } else {\n field = line.slice(0, colonIdx);\n value = line.slice(colonIdx + 1);\n // Strip ONE leading space if present (per spec § 9.2.6)\n if (value.startsWith(\" \")) value = value.slice(1);\n }\n switch (field) {\n case \"event\":\n eventName = value;\n hasField = true;\n break;\n case \"data\":\n dataLines.push(value);\n hasField = true;\n break;\n case \"id\":\n // Per spec: id with NULL is ignored\n if (!value.includes(\"\\0\")) {\n id = value;\n hasField = true;\n }\n break;\n case \"retry\":\n if (/^\\d+$/.test(value)) {\n retry = Number.parseInt(value, 10);\n hasField = true;\n }\n break;\n default:\n // Unknown field — ignored per spec\n break;\n }\n return null;\n };\n\n for await (const bytes of source) {\n // Normalize CRLF / CR to LF then split\n buffer += decoder.decode(bytes, { stream: true }).replace(/\\r\\n|\\r/g, \"\\n\");\n let idx: number;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic while-assignment loop for buffered line parsing\n while ((idx = buffer.indexOf(\"\\n\")) !== -1) {\n const line = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 1);\n const event = handleLine(line);\n if (event !== null) yield event;\n }\n }\n // Flush remaining buffer as a final line (no trailing newline case)\n buffer += decoder.decode();\n if (buffer.length > 0) {\n const event = handleLine(buffer);\n if (event !== null) yield event;\n }\n // Final dispatch in case last event lacked terminating blank line\n const tail = dispatch();\n if (tail !== null) yield tail;\n}\n","/**\n * Subscription type contract (G8 v1.7.0) — `@theokit/sdk`.\n *\n * Per ADRs D423 (resume token opaque), D424 (transport selection),\n * D426 (defineSubscription DSL shape).\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"../errors.js\";\n\n/**\n * Transport selection for subscriptions.\n *\n * - `'ws'`: WebSocket (bidirectional). Required for inbound client→server frames.\n * v1.7 ships Node-canonical `ws` adapter; CF/Bun/Deno deferred to v1.8.x per ADR D425.\n * - `'sse'`: W3C Server-Sent Events (server→client only). Browser-native EventSource.\n * - `'auto'`: Prefer WS, fall back SSE on upgrade failure. Default.\n *\n * @public\n */\nexport type SubscriptionTransport = \"ws\" | \"sse\" | \"auto\";\n\n/**\n * Context passed to a subscription `handler` on each invocation.\n *\n * @public\n */\nexport interface SubscriptionCtx {\n /**\n * Opaque resume token forwarded by the client when reconnecting.\n * Handler defines its own semantics (monotonic int, ULID, timestamp,\n * encrypted cursor). SDK passes through unchanged. Per ADR D423.\n */\n readonly lastEventId?: string;\n\n /**\n * AbortSignal that fires when the subscription is cancelled\n * (client disconnect, consumer abort, server shutdown).\n * Handler MUST honor `signal.aborted` in long-running loops.\n */\n readonly signal: AbortSignal;\n\n /**\n * Stable identifier for the underlying transport connection.\n * Different from the subscription name — one connection may host\n * many subscriptions. Useful for logging / per-connection state.\n */\n readonly connectionId: string;\n\n /**\n * Force-close the underlying transport with optional WS close code + reason.\n * Used by consumer code (e.g., auth middleware revoking a session) to\n * terminate a subscription that should not continue.\n */\n disconnect(code?: number, reason?: string): void;\n\n /**\n * Helper to mint a tracked envelope `[id, payload]`.\n * Yielding tracked envelopes lets the client advance `lastEventId`\n * so reconnects can resume from that point.\n */\n tracked<TPayload>(id: string, payload: TPayload): TrackedEnvelope<TPayload>;\n}\n\n/**\n * Tracked envelope: `[id, payload]` tuple yielded by subscription handlers\n * to advertise the resume token associated with the payload.\n *\n * The encoder writes the `id` as an SSE `id:` field or WS payload metadata\n * so the client can echo it back on reconnect (`input.lastEventId`).\n *\n * Per ADR D423.\n *\n * @public\n */\nexport type TrackedEnvelope<T> = readonly [id: string, payload: T];\n\n/**\n * Type guard for {@link TrackedEnvelope}.\n *\n * @public\n */\nexport function isTrackedEnvelope(value: unknown): value is TrackedEnvelope<unknown> {\n return Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\";\n}\n\n/**\n * Mint a tracked envelope. Equivalent to `[id, payload] as const`,\n * exported as a function so consumers don't repeat the tuple cast.\n *\n * @public\n */\nexport function tracked<T>(id: string, payload: T): TrackedEnvelope<T> {\n if (typeof id !== \"string\" || id.length === 0) {\n throw new TypeError(\"tracked(): id must be a non-empty string\");\n }\n return [id, payload] as const;\n}\n\n/**\n * Base error for the subscription subsystem. Extends {@link TheokitAgentError}\n * so existing `instanceof TheokitAgentError` branches keep working.\n *\n * @public\n */\nexport class SubscriptionError extends TheokitAgentError {\n override readonly name: string = \"SubscriptionError\";\n\n constructor(message: string, options: { code?: string; cause?: unknown } = {}) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown when subscription input fails Zod schema validation.\n *\n * @public\n */\nexport class SubscriptionInputError extends SubscriptionError {\n override readonly name: string = \"SubscriptionInputError\";\n\n readonly issues: unknown;\n\n constructor(message: string, options: { issues: unknown; cause?: unknown }) {\n super(message, { code: \"subscription_input_invalid\", cause: options.cause });\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown when a subscription transport disconnects unexpectedly\n * AND the client did not opt out of reconnect.\n *\n * @public\n */\nexport class SubscriptionDisconnectError extends SubscriptionError {\n override readonly name: string = \"SubscriptionDisconnectError\";\n\n readonly closeCode?: number;\n readonly closeReason?: string;\n\n constructor(\n message: string,\n options: { closeCode?: number; closeReason?: string; cause?: unknown } = {},\n ) {\n super(message, { code: \"subscription_disconnected\", cause: options.cause });\n if (options.closeCode !== undefined) this.closeCode = options.closeCode;\n if (options.closeReason !== undefined) this.closeReason = options.closeReason;\n }\n}\n\n/**\n * Descriptor returned by {@link Subscription.create}. Carries the typed\n * input/output Zod schemas + handler factory.\n *\n * @public\n */\nexport interface SubscriptionDescriptor<TInput = unknown, TOutput = unknown> {\n /** Optional explicit name; the runtime may also derive name from file path. */\n readonly name?: string;\n /** Zod schema for the subscription input. Validated at dispatch boundary. */\n readonly input: ZodLike<TInput>;\n /** Zod schema for each output frame (informational; not enforced per-frame). */\n readonly output: ZodLike<TOutput>;\n /** Async handler that yields output frames (or tracked envelopes). */\n readonly handler: (\n input: TInput,\n ctx: SubscriptionCtx,\n ) => AsyncGenerator<TOutput | TrackedEnvelope<TOutput>, void, void>;\n}\n\n/**\n * Minimal structural Zod type used to avoid hard peer-dep import.\n * Mirrors the surface used by other SDK modules (e.g., `define-tool.ts`).\n *\n * Emitted rather than erased: it appears in the signature of `defineSubscription`, which\n * `@theokit/sdk/subscription` publishes, so a consumer's type-aware lint has to be able to\n * resolve it.\n */\nexport interface ZodLike<T> {\n safeParse(value: unknown): { success: true; data: T } | { success: false; error: unknown };\n parse(value: unknown): T;\n}\n","/**\n * `Theokit.subscribe` client (G8 public API) — `@theokit/sdk`.\n *\n * Per ADR D427 (Theokit.subscribe namespace) + D424 (transport selection)\n * + D423 (lastEventId opaque propagation).\n *\n * Returns an AsyncGenerator that yields server-sent values. Transparent\n * reconnect with exponential backoff. Propagates `lastEventId` from the last\n * received tracked envelope on each reconnect attempt.\n *\n * @public\n */\n\nimport { parseSseW3C } from \"./internal/sse-parser.js\";\nimport type { WireFrame } from \"./internal/subscription-runtime.js\";\nimport {\n SubscriptionDisconnectError,\n SubscriptionError,\n type SubscriptionTransport,\n} from \"./types.js\";\n\n/**\n * Options accepted by `Theokit.subscribe(name, input, opts?)`.\n *\n * @public\n */\nexport interface SubscribeOptions {\n /** Base URL of the server (e.g., `\"http://localhost:3000\"`). Required. */\n baseUrl: string;\n /** Preferred transport. Default `\"auto\"` (WS preferred, SSE fallback). */\n transport?: SubscriptionTransport;\n /** Max reconnect attempts (default 10). 0 disables reconnect. */\n maxReconnectAttempts?: number;\n /** Backoff strategy. Default exponential `min(30_000, 1000 * 2^attempt)` ms. */\n retryDelayMs?: (attempt: number) => number;\n /** Caller-supplied abort signal. Cancels the subscription entirely. */\n signal?: AbortSignal;\n /** Additional fetch-style headers (e.g., `Authorization`). */\n headers?: Record<string, string>;\n /**\n * Override the SSE transport's `fetch`. Defaults to `globalThis.fetch`.\n * Lets a consumer supply a proxying agent or instrumented fetch without\n * mutating the runtime global.\n */\n fetch?: typeof globalThis.fetch;\n /**\n * Override the WS transport's `WebSocket` constructor. Defaults to\n * `globalThis.WebSocket`. Lets a consumer polyfill WS on a runtime that\n * lacks it, or supply an instrumented implementation, without mutating\n * the runtime global.\n */\n WebSocket?: typeof WebSocket;\n}\n\nconst defaultRetry = (attempt: number) => Math.min(30_000, 1000 * 2 ** attempt);\n\n/**\n * Subscribe to a typed subscription. Yields values produced by the server\n * handler. On disconnect with reconnect enabled, transparently re-establishes\n * the connection and forwards `lastEventId` from the last received tracked\n * envelope so the server handler can resume.\n *\n * @public\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: subscribe orchestrates reconnect + transport switch + resume, and the interleaving is the contract. THE DEBT IS UNOWNED — this used to claim it was \"tracked in subscription/theokit-subscribe.ts:52 followup\", which is a line in an unrelated JSDoc block in this same file, and grepping the file for followup/todo/fixme/#NNN returns only this comment. The citation was its own only evidence. Saying the debt is unowned is worse news and true; a maintainer who checks the tracking before touching the module's @public entry point now learns that in one grep instead of three.\nexport async function* subscribe<TInput, TOutput>(\n name: string,\n input: TInput,\n opts: SubscribeOptions,\n): AsyncGenerator<TOutput, void, void> {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new SubscriptionError(\"Theokit.subscribe: name must be a non-empty string\", {\n code: \"subscribe_name_invalid\",\n });\n }\n if (opts === null || typeof opts !== \"object\" || typeof opts.baseUrl !== \"string\") {\n throw new SubscriptionError(\"Theokit.subscribe: opts.baseUrl is required\", {\n code: \"subscribe_baseUrl_missing\",\n });\n }\n const transport = opts.transport ?? \"auto\";\n const maxReconnects = opts.maxReconnectAttempts ?? 10;\n const retry = opts.retryDelayMs ?? defaultRetry;\n\n let lastEventId: string | undefined;\n let attempt = 0;\n\n while (true) {\n if (opts.signal?.aborted) return;\n try {\n const inputWithCursor = mergeLastEventId(input, lastEventId);\n const chosen = await selectTransport(transport, name, opts);\n if (chosen === \"ws\") {\n for await (const out of openWs<TOutput>(name, inputWithCursor, opts)) {\n if (out.lastEventId !== undefined) lastEventId = out.lastEventId;\n attempt = 0; // reset backoff on successful frame\n yield out.value;\n }\n } else {\n for await (const out of openSse<TOutput>(name, inputWithCursor, opts)) {\n if (out.lastEventId !== undefined) lastEventId = out.lastEventId;\n attempt = 0;\n yield out.value;\n }\n }\n // Clean end-of-stream — no reconnect.\n return;\n } catch (cause) {\n if (opts.signal?.aborted) return;\n if (maxReconnects === 0 || attempt >= maxReconnects) {\n if (cause instanceof SubscriptionError) throw cause;\n throw new SubscriptionDisconnectError(\n `subscription \"${name}\" disconnected; reconnect exhausted`,\n { cause },\n );\n }\n const delay = retry(attempt);\n attempt++;\n await sleep(delay, opts.signal);\n }\n }\n}\n\ninterface FrameOut<T> {\n readonly value: T;\n readonly lastEventId?: string;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: openSse parses framed SSE stream with abort/error/retry branches — refactor candidate\nasync function* openSse<T>(\n name: string,\n input: unknown,\n opts: SubscribeOptions,\n): AsyncIterable<FrameOut<T>> {\n const url = `${stripTrailingSlash(opts.baseUrl)}/api/subscriptions/${encodeURIComponent(name)}?input=${encodeURIComponent(JSON.stringify(input))}`;\n const fetchFn = opts.fetch ?? globalThis.fetch;\n const res = await fetchFn(url, {\n method: \"GET\",\n headers: {\n accept: \"text/event-stream\",\n ...(opts.headers ?? {}),\n },\n ...(opts.signal !== undefined ? { signal: opts.signal } : {}),\n });\n if (!res.ok || res.body === null) {\n throw new SubscriptionError(`SSE subscribe failed: HTTP ${res.status} ${res.statusText}`, {\n code: \"sse_http_error\",\n });\n }\n const events = parseSseW3C(streamToAsyncIterable(res.body));\n for await (const ev of events) {\n if (ev.event === \"end\") return;\n if (ev.event === \"error\") {\n throw new SubscriptionError(`SSE server emitted error: ${ev.data ?? \"(no body)\"}`, {\n code: \"sse_server_error\",\n });\n }\n if (ev.event === \"connected\") continue;\n if (ev.data === undefined) continue;\n const parsedValue = safeJsonParse<T>(ev.data);\n if (parsedValue === undefined) continue;\n yield {\n value: parsedValue,\n ...(ev.id !== undefined ? { lastEventId: ev.id } : {}),\n };\n }\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: openWs orchestrates WS lifecycle + envelope decode + cleanup — refactor candidate\nasync function* openWs<T>(\n name: string,\n input: unknown,\n opts: SubscribeOptions,\n): AsyncIterable<FrameOut<T>> {\n const baseUrl = stripTrailingSlash(opts.baseUrl);\n const wsUrl = baseUrl\n .replace(/^http:/, \"ws:\")\n .replace(/^https:/, \"wss:\")\n .concat(\"/api/ws\");\n\n const WS = opts.WebSocket ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;\n if (WS === undefined) {\n throw new SubscriptionError(\n \"Theokit.subscribe(transport='ws'): no global WebSocket available. Use Node >=22 or install 'ws' as a runtime dep + assign to globalThis.WebSocket, or pass opts.WebSocket.\",\n { code: \"ws_global_missing\" },\n );\n }\n const ws = new WS(wsUrl);\n\n // Set up async iterator-like state.\n const incoming: WireFrame[] = [];\n // biome-ignore lint/suspicious/noConfusingVoidType: idiomatic event-callback signature; refactoring to undefined would mask the no-value semantics\n let waiter: ((value: void) => void) | null = null;\n let closed = false;\n let closeError: Error | undefined;\n\n ws.addEventListener(\"message\", (ev: MessageEvent) => {\n const data = typeof ev.data === \"string\" ? ev.data : \"\";\n const frame = safeJsonParse<WireFrame>(data);\n if (frame !== undefined) {\n incoming.push(frame);\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n }\n });\n ws.addEventListener(\"close\", () => {\n closed = true;\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n });\n ws.addEventListener(\"error\", () => {\n closed = true;\n closeError = new Error(\"WebSocket error\");\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n });\n\n await new Promise<void>((resolve, reject) => {\n ws.addEventListener(\"open\", () => resolve(), { once: true });\n ws.addEventListener(\"error\", () => reject(new Error(\"WS connect failed\")), { once: true });\n });\n\n // Send subscribe request after handshake.\n ws.send(JSON.stringify({ kind: \"subscribe\", name, input }));\n\n if (opts.signal !== undefined) {\n opts.signal.addEventListener(\"abort\", () => ws.close(), { once: true });\n }\n\n try {\n while (true) {\n if (incoming.length === 0) {\n if (closed) {\n if (closeError !== undefined) throw closeError;\n return;\n }\n await new Promise<void>((resolve) => {\n waiter = resolve;\n });\n continue;\n }\n const frame = incoming.shift() as WireFrame;\n if (frame.type === \"end\") return;\n if (frame.type === \"error\") {\n // The server's own code wins. `ws_server_error` is the fallback for a frame that carries\n // none — it used to be the code for EVERY server-side failure, so a caller could not tell an\n // invalid input from a disconnect without reading English out of the message.\n throw new SubscriptionError(\n `WS server emitted error: ${frame.error?.message ?? \"(unknown)\"}`,\n { code: frame.error?.code ?? \"ws_server_error\" },\n );\n }\n const value = frame.data as T;\n yield {\n value,\n ...(frame.id !== undefined ? { lastEventId: frame.id } : {}),\n };\n }\n } finally {\n try {\n ws.close();\n } catch {\n /* ignore */\n }\n }\n}\n\nasync function selectTransport(\n pref: SubscriptionTransport,\n _name: string,\n opts: SubscribeOptions,\n): Promise<\"ws\" | \"sse\"> {\n if (pref === \"ws\") return \"ws\";\n if (pref === \"sse\") return \"sse\";\n // auto — prefer WS if available (injected or global), else SSE.\n const WS = opts.WebSocket ?? (globalThis as { WebSocket?: unknown }).WebSocket;\n if (typeof WS === \"function\") {\n return \"ws\";\n }\n return \"sse\";\n}\n\nfunction mergeLastEventId(input: unknown, lastEventId: string | undefined): unknown {\n if (lastEventId === undefined) return input;\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n // Cannot merge into primitive — return as-is.\n return input;\n }\n return { ...(input as object), lastEventId };\n}\n\nfunction stripTrailingSlash(s: string): string {\n return s.endsWith(\"/\") ? s.slice(0, -1) : s;\n}\n\nfunction safeJsonParse<T>(s: string): T | undefined {\n try {\n return JSON.parse(s) as T;\n } catch {\n return undefined;\n }\n}\n\nasync function* streamToAsyncIterable(\n stream: ReadableStream<Uint8Array>,\n): AsyncIterable<Uint8Array> {\n const reader = stream.getReader();\n let finishedNaturally = false;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n finishedNaturally = true;\n return;\n }\n if (value !== undefined) yield value;\n }\n } finally {\n // B-131: `releaseLock()` alone detaches the reader WITHOUT canceling the stream (WHATWG\n // Streams spec) — the underlying `fetch` response body, and its socket, stays open until\n // something else cancels it or reads it to completion. A consumer that breaks out of the\n // subscription mid-stream (the ordinary shape: `for await ... break`) used to leave that\n // connection dangling. `cancel()` is a no-op once the stream is already closed, so it is safe\n // to call unconditionally on the early-exit path; skip it on natural completion, where the\n // stream is already done and canceling only risks surfacing a spurious rejection.\n if (!finishedNaturally) {\n try {\n await reader.cancel();\n } catch {\n /* best-effort cleanup — the caller's own error (if any) already takes precedence */\n }\n }\n reader.releaseLock();\n }\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error(\"aborted\"));\n return;\n }\n const t = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(new Error(\"aborted\"));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n"]}
1
+ {"version":3,"sources":["../../src/subscription/define-subscription.ts","../../src/subscription/internal/sse-parser.ts","../../src/subscription/types.ts","../../src/subscription/theokit-subscribe.ts"],"names":["TheokitAgentError","boundFetch"],"mappings":";;;;;;;AAoEO,SAAS,mBACd,IAAA,EACyC;AACzC,EAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AAC7C,IAAA,MAAM,IAAI,UAAU,gDAAgD,CAAA;AAAA,EACtE;AACA,EAAA,IAAI,KAAK,KAAA,KAAU,MAAA,IAAa,OAAO,IAAA,CAAK,KAAA,CAAM,cAAc,UAAA,EAAY;AAC1E,IAAA,MAAM,IAAI,UAAU,kEAAkE,CAAA;AAAA,EACxF;AACA,EAAA,IAAI,KAAK,MAAA,KAAW,MAAA,IAAa,OAAO,IAAA,CAAK,MAAA,CAAO,cAAc,UAAA,EAAY;AAC5E,IAAA,MAAM,IAAI,UAAU,mEAAmE,CAAA;AAAA,EACzF;AACA,EAAA,IAAI,OAAO,IAAA,CAAK,OAAA,KAAY,UAAA,EAAY;AACtC,IAAA,MAAM,IAAI,UAAU,sEAAsE,CAAA;AAAA,EAC5F;AACA,EAAA,OAAO;AAAA,IACL,GAAI,KAAK,IAAA,KAAS,MAAA,GAAY,EAAE,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK,GAAI,EAAC;AAAA,IACrD,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,SAAS,IAAA,CAAK;AAAA,GAChB;AACF;AAMO,IAAM,eAAN,MAAmB;AAAA,EAChB,WAAA,GAAc;AAAA,EAAC;AAAA,EACvB,OAAO,OACL,IAAA,EACyC;AACzC,IAAA,OAAO,mBAAmB,IAAI,CAAA;AAAA,EAChC;AACF;;;ACrFA,IAAM,O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CAAM,IAAY,MAAA,EAAqC;AAC9D,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,MAAA,CAAO,IAAI,KAAA,CAAM,SAAS,CAAC,CAAA;AAC3B,MAAA;AAAA,IACF;AACA,IAAA,MAAM,CAAA,GAAI,WAAW,MAAM;AACzB,MAAA,MAAA,EAAQ,mBAAA,CAAoB,SAAS,OAAO,CAAA;AAC5C,MAAA,OAAA,EAAQ;AAAA,IACV,GAAG,EAAE,CAAA;AACL,IAAA,MAAM,UAAU,MAAM;AACpB,MAAA,YAAA,CAAa,CAAC,CAAA;AACd,MAAA,MAAA,CAAO,IAAI,KAAA,CAAM,SAAS,CAAC,CAAA;AAAA,IAC7B,CAAA;AACA,IAAA,MAAA,EAAQ,iBAAiB,OAAA,EAAS,OAAA,EAAS,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,EAC3D,CAAC,CAAA;AACH","file":"index.cjs","sourcesContent":["/**\n * `defineSubscription` DSL (G8 public API) — `@theokit/sdk`.\n *\n * Per ADR D426 (AsyncGenerator handler + Zod input/output schemas).\n *\n * @public\n */\n\nimport type { SubscriptionCtx, SubscriptionDescriptor, TrackedEnvelope, ZodLike } from \"./types.js\";\n\n/**\n * Options accepted by {@link defineSubscription}.\n *\n * @public\n */\nexport interface DefineSubscriptionOptions<TInput, TOutput> {\n /** Optional explicit name. Falls back to filename derivation by the scanner. */\n name?: string;\n /** Zod schema validating subscription input. Required (typed RPC contract). */\n input: ZodLike<TInput>;\n /** Zod schema describing each output frame. Informational; not enforced per-frame. */\n output: ZodLike<TOutput>;\n /**\n * Handler that produces the subscription stream.\n *\n * Receives the validated input + {@link SubscriptionCtx}. Yielding a value\n * emits a plain output frame. Yielding a `tracked(id, payload)` envelope\n * additionally advertises a resume token to the client so reconnects can\n * resume from that point.\n */\n handler: (\n input: TInput,\n ctx: SubscriptionCtx,\n ) => AsyncGenerator<TOutput | TrackedEnvelope<TOutput>, void, void>;\n}\n\n/**\n * Define a typed subscription. Pair with `Theokit.subscribe(name, input)`\n * on the client side.\n *\n * Per ADR D426 — handler is `AsyncGenerator<TOutput | TrackedEnvelope<TOutput>>`.\n * The runtime validates input via `opts.input.safeParse` BEFORE invoking the\n * handler; failure throws {@link import('./types.js').SubscriptionInputError}.\n *\n * @example\n * ```ts\n * import { Subscription } from \"@theokit/sdk/subscription\";\n * import { z } from \"zod\";\n *\n * export default Subscription.create({\n * input: z.object({ topic: z.string() }),\n * output: z.object({ message: z.string(), ts: z.number() }),\n * async *handler(input, ctx) {\n * let cursor = ctx.lastEventId ?? \"0\";\n * while (!ctx.signal.aborted) {\n * const msgs = await fetchMessagesSince(input.topic, cursor);\n * for (const m of msgs) {\n * cursor = m.id;\n * yield ctx.tracked(m.id, { message: m.body, ts: m.ts });\n * }\n * await sleep(1000);\n * }\n * },\n * });\n * ```\n *\n * @public\n */\nexport function defineSubscription<TInput, TOutput>(\n opts: DefineSubscriptionOptions<TInput, TOutput>,\n): SubscriptionDescriptor<TInput, TOutput> {\n if (opts === null || typeof opts !== \"object\") {\n throw new TypeError(\"defineSubscription: options object is required\");\n }\n if (opts.input === undefined || typeof opts.input.safeParse !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.input must be a Zod schema (or ZodLike)\");\n }\n if (opts.output === undefined || typeof opts.output.safeParse !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.output must be a Zod schema (or ZodLike)\");\n }\n if (typeof opts.handler !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.handler must be an async generator function\");\n }\n return {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n input: opts.input,\n output: opts.output,\n handler: opts.handler,\n };\n}\n\n/** SE36 — `Subscription.create` replaces `defineSubscription` (ADR 0015). @public *\n * `Subscription.create` returns a **`SubscriptionDescriptor<TInput, TOutput>`**, not a\n * `Subscription`. The class is the namespace; the descriptor is the product.\n */\nexport class Subscription {\n private constructor() {}\n static create<TInput, TOutput>(\n opts: DefineSubscriptionOptions<TInput, TOutput>,\n ): SubscriptionDescriptor<TInput, TOutput> {\n return defineSubscription(opts);\n }\n}\n","/**\n * W3C SSE parser (G8 internal) — `@theokit/sdk`.\n *\n * Per ADR D428. Reads from `ReadableStream<Uint8Array>` or async iterable of\n * UTF-8 chunks; yields parsed {@link SSEvent} objects per W3C SSE spec.\n *\n * Independent of `internal/llm/sse.ts:parseSseStream` (LLM-specific a peer vendor AI\n * Data Stream v1; locked by D38). This parser handles the `id:` field needed\n * for tracked envelopes (G8 resume mechanism), which the LLM parser ignores.\n *\n * Reference: https://html.spec.whatwg.org/multipage/server-sent-events.html\n *\n * @internal\n */\n\nimport type { SSEvent } from \"./sse-encoder.js\";\n\nconst decoder = new TextDecoder(\"utf-8\");\n\n/**\n * Parse an async iterable of UTF-8 byte chunks into a stream of SSE events.\n *\n * Implements the W3C event stream parser:\n * - Lines are split by `\\n`, `\\r\\n`, or `\\r`\n * - Events are dispatched on blank line (no `:` and no field name)\n * - Fields: `event`, `data` (multi-line concat with `\\n`), `id`, `retry`\n * - Lines starting with `:` are comments (ignored, except dispatched as `comment`)\n * - Unknown fields silently ignored per spec\n *\n * Empty events (no fields) are NOT dispatched per spec.\n *\n * @internal\n */\nexport async function* parseSseW3C(\n source: AsyncIterable<Uint8Array>,\n): AsyncGenerator<SSEvent, void, void> {\n let buffer = \"\";\n let eventName: string | undefined;\n let dataLines: string[] = [];\n let id: string | undefined;\n let retry: number | undefined;\n let commentLines: string[] = [];\n let hasField = false;\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: dispatch builds SSEvent from per-field state per W3C spec — refactor candidate\n const dispatch = (): SSEvent | null => {\n if (!hasField) {\n // Blank line with no preceding fields → reset state, no dispatch (per spec § 9.2.6)\n eventName = undefined;\n dataLines = [];\n id = undefined;\n retry = undefined;\n commentLines = [];\n return null;\n }\n const chunk: SSEvent = {};\n if (eventName !== undefined) (chunk as { event?: string }).event = eventName;\n if (dataLines.length > 0) (chunk as { data?: string }).data = dataLines.join(\"\\n\");\n if (id !== undefined) (chunk as { id?: string }).id = id;\n if (retry !== undefined) (chunk as { retry?: number }).retry = retry;\n if (commentLines.length > 0) (chunk as { comment?: string }).comment = commentLines.join(\"\\n\");\n eventName = undefined;\n dataLines = [];\n id = undefined;\n retry = undefined;\n commentLines = [];\n hasField = false;\n return chunk;\n };\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: handleLine dispatches across all SSE field kinds per W3C spec — refactor candidate\n const handleLine = (line: string): SSEvent | null => {\n if (line === \"\") {\n return dispatch();\n }\n if (line.startsWith(\":\")) {\n // Comment line — per spec ignored, but we surface it for keepalive visibility.\n commentLines.push(line.slice(1).replace(/^ /, \"\"));\n hasField = true;\n return null;\n }\n const colonIdx = line.indexOf(\":\");\n let field: string;\n let value: string;\n if (colonIdx === -1) {\n field = line;\n value = \"\";\n } else {\n field = line.slice(0, colonIdx);\n value = line.slice(colonIdx + 1);\n // Strip ONE leading space if present (per spec § 9.2.6)\n if (value.startsWith(\" \")) value = value.slice(1);\n }\n switch (field) {\n case \"event\":\n eventName = value;\n hasField = true;\n break;\n case \"data\":\n dataLines.push(value);\n hasField = true;\n break;\n case \"id\":\n // Per spec: id with NULL is ignored\n if (!value.includes(\"\\0\")) {\n id = value;\n hasField = true;\n }\n break;\n case \"retry\":\n if (/^\\d+$/.test(value)) {\n retry = Number.parseInt(value, 10);\n hasField = true;\n }\n break;\n default:\n // Unknown field — ignored per spec\n break;\n }\n return null;\n };\n\n for await (const bytes of source) {\n // Normalize CRLF / CR to LF then split\n buffer += decoder.decode(bytes, { stream: true }).replace(/\\r\\n|\\r/g, \"\\n\");\n let idx: number;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic while-assignment loop for buffered line parsing\n while ((idx = buffer.indexOf(\"\\n\")) !== -1) {\n const line = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 1);\n const event = handleLine(line);\n if (event !== null) yield event;\n }\n }\n // Flush remaining buffer as a final line (no trailing newline case)\n buffer += decoder.decode();\n if (buffer.length > 0) {\n const event = handleLine(buffer);\n if (event !== null) yield event;\n }\n // Final dispatch in case last event lacked terminating blank line\n const tail = dispatch();\n if (tail !== null) yield tail;\n}\n","/**\n * Subscription type contract (G8 v1.7.0) — `@theokit/sdk`.\n *\n * Per ADRs D423 (resume token opaque), D424 (transport selection),\n * D426 (defineSubscription DSL shape).\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"../errors.js\";\n\n/**\n * Transport selection for subscriptions.\n *\n * - `'ws'`: WebSocket (bidirectional). Required for inbound client→server frames.\n * v1.7 ships Node-canonical `ws` adapter; CF/Bun/Deno deferred to v1.8.x per ADR D425.\n * - `'sse'`: W3C Server-Sent Events (server→client only). Browser-native EventSource.\n * - `'auto'`: Prefer WS, fall back SSE on upgrade failure. Default.\n *\n * @public\n */\nexport type SubscriptionTransport = \"ws\" | \"sse\" | \"auto\";\n\n/**\n * Context passed to a subscription `handler` on each invocation.\n *\n * @public\n */\nexport interface SubscriptionCtx {\n /**\n * Opaque resume token forwarded by the client when reconnecting.\n * Handler defines its own semantics (monotonic int, ULID, timestamp,\n * encrypted cursor). SDK passes through unchanged. Per ADR D423.\n */\n readonly lastEventId?: string;\n\n /**\n * AbortSignal that fires when the subscription is cancelled\n * (client disconnect, consumer abort, server shutdown).\n * Handler MUST honor `signal.aborted` in long-running loops.\n */\n readonly signal: AbortSignal;\n\n /**\n * Stable identifier for the underlying transport connection.\n * Different from the subscription name — one connection may host\n * many subscriptions. Useful for logging / per-connection state.\n */\n readonly connectionId: string;\n\n /**\n * Force-close the underlying transport with optional WS close code + reason.\n * Used by consumer code (e.g., auth middleware revoking a session) to\n * terminate a subscription that should not continue.\n */\n disconnect(code?: number, reason?: string): void;\n\n /**\n * Helper to mint a tracked envelope `[id, payload]`.\n * Yielding tracked envelopes lets the client advance `lastEventId`\n * so reconnects can resume from that point.\n */\n tracked<TPayload>(id: string, payload: TPayload): TrackedEnvelope<TPayload>;\n}\n\n/**\n * Tracked envelope: `[id, payload]` tuple yielded by subscription handlers\n * to advertise the resume token associated with the payload.\n *\n * The encoder writes the `id` as an SSE `id:` field or WS payload metadata\n * so the client can echo it back on reconnect (`input.lastEventId`).\n *\n * Per ADR D423.\n *\n * @public\n */\nexport type TrackedEnvelope<T> = readonly [id: string, payload: T];\n\n/**\n * Type guard for {@link TrackedEnvelope}.\n *\n * @public\n */\nexport function isTrackedEnvelope(value: unknown): value is TrackedEnvelope<unknown> {\n return Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\";\n}\n\n/**\n * Mint a tracked envelope. Equivalent to `[id, payload] as const`,\n * exported as a function so consumers don't repeat the tuple cast.\n *\n * @public\n */\nexport function tracked<T>(id: string, payload: T): TrackedEnvelope<T> {\n if (typeof id !== \"string\" || id.length === 0) {\n throw new TypeError(\"tracked(): id must be a non-empty string\");\n }\n return [id, payload] as const;\n}\n\n/**\n * Base error for the subscription subsystem. Extends {@link TheokitAgentError}\n * so existing `instanceof TheokitAgentError` branches keep working.\n *\n * @public\n */\nexport class SubscriptionError extends TheokitAgentError {\n override readonly name: string = \"SubscriptionError\";\n\n constructor(message: string, options: { code?: string; cause?: unknown } = {}) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown when subscription input fails Zod schema validation.\n *\n * @public\n */\nexport class SubscriptionInputError extends SubscriptionError {\n override readonly name: string = \"SubscriptionInputError\";\n\n readonly issues: unknown;\n\n constructor(message: string, options: { issues: unknown; cause?: unknown }) {\n super(message, { code: \"subscription_input_invalid\", cause: options.cause });\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown when a subscription transport disconnects unexpectedly\n * AND the client did not opt out of reconnect.\n *\n * @public\n */\nexport class SubscriptionDisconnectError extends SubscriptionError {\n override readonly name: string = \"SubscriptionDisconnectError\";\n\n readonly closeCode?: number;\n readonly closeReason?: string;\n\n constructor(\n message: string,\n options: { closeCode?: number; closeReason?: string; cause?: unknown } = {},\n ) {\n super(message, { code: \"subscription_disconnected\", cause: options.cause });\n if (options.closeCode !== undefined) this.closeCode = options.closeCode;\n if (options.closeReason !== undefined) this.closeReason = options.closeReason;\n }\n}\n\n/**\n * Descriptor returned by {@link Subscription.create}. Carries the typed\n * input/output Zod schemas + handler factory.\n *\n * @public\n */\nexport interface SubscriptionDescriptor<TInput = unknown, TOutput = unknown> {\n /** Optional explicit name; the runtime may also derive name from file path. */\n readonly name?: string;\n /** Zod schema for the subscription input. Validated at dispatch boundary. */\n readonly input: ZodLike<TInput>;\n /** Zod schema for each output frame (informational; not enforced per-frame). */\n readonly output: ZodLike<TOutput>;\n /** Async handler that yields output frames (or tracked envelopes). */\n readonly handler: (\n input: TInput,\n ctx: SubscriptionCtx,\n ) => AsyncGenerator<TOutput | TrackedEnvelope<TOutput>, void, void>;\n}\n\n/**\n * Minimal structural Zod type used to avoid hard peer-dep import.\n * Mirrors the surface used by other SDK modules (e.g., `define-tool.ts`).\n *\n * Emitted rather than erased: it appears in the signature of `defineSubscription`, which\n * `@theokit/sdk/subscription` publishes, so a consumer's type-aware lint has to be able to\n * resolve it.\n */\nexport interface ZodLike<T> {\n safeParse(value: unknown): { success: true; data: T } | { success: false; error: unknown };\n parse(value: unknown): T;\n}\n","/**\n * `Theokit.subscribe` client (G8 public API) — `@theokit/sdk`.\n *\n * Per ADR D427 (Theokit.subscribe namespace) + D424 (transport selection)\n * + D423 (lastEventId opaque propagation).\n *\n * Returns an AsyncGenerator that yields server-sent values. Transparent\n * reconnect with exponential backoff. Propagates `lastEventId` from the last\n * received tracked envelope on each reconnect attempt.\n *\n * @public\n */\n\nimport { boundFetch } from \"../internal/runtime-fetch.js\";\nimport { parseSseW3C } from \"./internal/sse-parser.js\";\nimport type { WireFrame } from \"./internal/subscription-runtime.js\";\nimport {\n SubscriptionDisconnectError,\n SubscriptionError,\n type SubscriptionTransport,\n} from \"./types.js\";\n\n/**\n * Options accepted by `Theokit.subscribe(name, input, opts?)`.\n *\n * @public\n */\nexport interface SubscribeOptions {\n /** Base URL of the server (e.g., `\"http://localhost:3000\"`). Required. */\n baseUrl: string;\n /** Preferred transport. Default `\"auto\"` (WS preferred, SSE fallback). */\n transport?: SubscriptionTransport;\n /** Max reconnect attempts (default 10). 0 disables reconnect. */\n maxReconnectAttempts?: number;\n /** Backoff strategy. Default exponential `min(30_000, 1000 * 2^attempt)` ms. */\n retryDelayMs?: (attempt: number) => number;\n /** Caller-supplied abort signal. Cancels the subscription entirely. */\n signal?: AbortSignal;\n /** Additional fetch-style headers (e.g., `Authorization`). */\n headers?: Record<string, string>;\n /**\n * Override the SSE transport's `fetch`. Defaults to `globalThis.fetch`.\n * Lets a consumer supply a proxying agent or instrumented fetch without\n * mutating the runtime global.\n */\n fetch?: typeof globalThis.fetch;\n /**\n * Override the WS transport's `WebSocket` constructor. Defaults to\n * `globalThis.WebSocket`. Lets a consumer polyfill WS on a runtime that\n * lacks it, or supply an instrumented implementation, without mutating\n * the runtime global.\n */\n WebSocket?: typeof WebSocket;\n}\n\nconst defaultRetry = (attempt: number) => Math.min(30_000, 1000 * 2 ** attempt);\n\n/**\n * Subscribe to a typed subscription. Yields values produced by the server\n * handler. On disconnect with reconnect enabled, transparently re-establishes\n * the connection and forwards `lastEventId` from the last received tracked\n * envelope so the server handler can resume.\n *\n * @public\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: subscribe orchestrates reconnect + transport switch + resume, and the interleaving is the contract. THE DEBT IS UNOWNED — this used to claim it was \"tracked in subscription/theokit-subscribe.ts:52 followup\", which is a line in an unrelated JSDoc block in this same file, and grepping the file for followup/todo/fixme/#NNN returns only this comment. The citation was its own only evidence. Saying the debt is unowned is worse news and true; a maintainer who checks the tracking before touching the module's @public entry point now learns that in one grep instead of three.\nexport async function* subscribe<TInput, TOutput>(\n name: string,\n input: TInput,\n opts: SubscribeOptions,\n): AsyncGenerator<TOutput, void, void> {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new SubscriptionError(\"Theokit.subscribe: name must be a non-empty string\", {\n code: \"subscribe_name_invalid\",\n });\n }\n if (opts === null || typeof opts !== \"object\" || typeof opts.baseUrl !== \"string\") {\n throw new SubscriptionError(\"Theokit.subscribe: opts.baseUrl is required\", {\n code: \"subscribe_baseUrl_missing\",\n });\n }\n const transport = opts.transport ?? \"auto\";\n const maxReconnects = opts.maxReconnectAttempts ?? 10;\n const retry = opts.retryDelayMs ?? defaultRetry;\n\n let lastEventId: string | undefined;\n let attempt = 0;\n\n while (true) {\n if (opts.signal?.aborted) return;\n try {\n const inputWithCursor = mergeLastEventId(input, lastEventId);\n const chosen = await selectTransport(transport, name, opts);\n if (chosen === \"ws\") {\n for await (const out of openWs<TOutput>(name, inputWithCursor, opts)) {\n if (out.lastEventId !== undefined) lastEventId = out.lastEventId;\n attempt = 0; // reset backoff on successful frame\n yield out.value;\n }\n } else {\n for await (const out of openSse<TOutput>(name, inputWithCursor, opts)) {\n if (out.lastEventId !== undefined) lastEventId = out.lastEventId;\n attempt = 0;\n yield out.value;\n }\n }\n // Clean end-of-stream — no reconnect.\n return;\n } catch (cause) {\n if (opts.signal?.aborted) return;\n if (maxReconnects === 0 || attempt >= maxReconnects) {\n if (cause instanceof SubscriptionError) throw cause;\n throw new SubscriptionDisconnectError(\n `subscription \"${name}\" disconnected; reconnect exhausted`,\n { cause },\n );\n }\n const delay = retry(attempt);\n attempt++;\n await sleep(delay, opts.signal);\n }\n }\n}\n\ninterface FrameOut<T> {\n readonly value: T;\n readonly lastEventId?: string;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: openSse parses framed SSE stream with abort/error/retry branches — refactor candidate\nasync function* openSse<T>(\n name: string,\n input: unknown,\n opts: SubscribeOptions,\n): AsyncIterable<FrameOut<T>> {\n const url = `${stripTrailingSlash(opts.baseUrl)}/api/subscriptions/${encodeURIComponent(name)}?input=${encodeURIComponent(JSON.stringify(input))}`;\n const fetchFn = boundFetch(opts.fetch);\n const res = await fetchFn(url, {\n method: \"GET\",\n headers: {\n accept: \"text/event-stream\",\n ...(opts.headers ?? {}),\n },\n ...(opts.signal !== undefined ? { signal: opts.signal } : {}),\n });\n if (!res.ok || res.body === null) {\n throw new SubscriptionError(`SSE subscribe failed: HTTP ${res.status} ${res.statusText}`, {\n code: \"sse_http_error\",\n });\n }\n const events = parseSseW3C(streamToAsyncIterable(res.body));\n for await (const ev of events) {\n if (ev.event === \"end\") return;\n if (ev.event === \"error\") {\n throw new SubscriptionError(`SSE server emitted error: ${ev.data ?? \"(no body)\"}`, {\n code: \"sse_server_error\",\n });\n }\n if (ev.event === \"connected\") continue;\n if (ev.data === undefined) continue;\n const parsedValue = safeJsonParse<T>(ev.data);\n if (parsedValue === undefined) continue;\n yield {\n value: parsedValue,\n ...(ev.id !== undefined ? { lastEventId: ev.id } : {}),\n };\n }\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: openWs orchestrates WS lifecycle + envelope decode + cleanup — refactor candidate\nasync function* openWs<T>(\n name: string,\n input: unknown,\n opts: SubscribeOptions,\n): AsyncIterable<FrameOut<T>> {\n const baseUrl = stripTrailingSlash(opts.baseUrl);\n const wsUrl = baseUrl\n .replace(/^http:/, \"ws:\")\n .replace(/^https:/, \"wss:\")\n .concat(\"/api/ws\");\n\n const WS = opts.WebSocket ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;\n if (WS === undefined) {\n throw new SubscriptionError(\n \"Theokit.subscribe(transport='ws'): no global WebSocket available. Use Node >=22 or install 'ws' as a runtime dep + assign to globalThis.WebSocket, or pass opts.WebSocket.\",\n { code: \"ws_global_missing\" },\n );\n }\n const ws = new WS(wsUrl);\n\n // Set up async iterator-like state.\n const incoming: WireFrame[] = [];\n // biome-ignore lint/suspicious/noConfusingVoidType: idiomatic event-callback signature; refactoring to undefined would mask the no-value semantics\n let waiter: ((value: void) => void) | null = null;\n let closed = false;\n let closeError: Error | undefined;\n\n ws.addEventListener(\"message\", (ev: MessageEvent) => {\n const data = typeof ev.data === \"string\" ? ev.data : \"\";\n const frame = safeJsonParse<WireFrame>(data);\n if (frame !== undefined) {\n incoming.push(frame);\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n }\n });\n ws.addEventListener(\"close\", () => {\n closed = true;\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n });\n ws.addEventListener(\"error\", () => {\n closed = true;\n closeError = new Error(\"WebSocket error\");\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n });\n\n await new Promise<void>((resolve, reject) => {\n ws.addEventListener(\"open\", () => resolve(), { once: true });\n ws.addEventListener(\"error\", () => reject(new Error(\"WS connect failed\")), { once: true });\n });\n\n // Send subscribe request after handshake.\n ws.send(JSON.stringify({ kind: \"subscribe\", name, input }));\n\n if (opts.signal !== undefined) {\n opts.signal.addEventListener(\"abort\", () => ws.close(), { once: true });\n }\n\n try {\n while (true) {\n if (incoming.length === 0) {\n if (closed) {\n if (closeError !== undefined) throw closeError;\n return;\n }\n await new Promise<void>((resolve) => {\n waiter = resolve;\n });\n continue;\n }\n const frame = incoming.shift() as WireFrame;\n if (frame.type === \"end\") return;\n if (frame.type === \"error\") {\n // The server's own code wins. `ws_server_error` is the fallback for a frame that carries\n // none — it used to be the code for EVERY server-side failure, so a caller could not tell an\n // invalid input from a disconnect without reading English out of the message.\n throw new SubscriptionError(\n `WS server emitted error: ${frame.error?.message ?? \"(unknown)\"}`,\n { code: frame.error?.code ?? \"ws_server_error\" },\n );\n }\n const value = frame.data as T;\n yield {\n value,\n ...(frame.id !== undefined ? { lastEventId: frame.id } : {}),\n };\n }\n } finally {\n try {\n ws.close();\n } catch {\n /* ignore */\n }\n }\n}\n\nasync function selectTransport(\n pref: SubscriptionTransport,\n _name: string,\n opts: SubscribeOptions,\n): Promise<\"ws\" | \"sse\"> {\n if (pref === \"ws\") return \"ws\";\n if (pref === \"sse\") return \"sse\";\n // auto — prefer WS if available (injected or global), else SSE.\n const WS = opts.WebSocket ?? (globalThis as { WebSocket?: unknown }).WebSocket;\n if (typeof WS === \"function\") {\n return \"ws\";\n }\n return \"sse\";\n}\n\nfunction mergeLastEventId(input: unknown, lastEventId: string | undefined): unknown {\n if (lastEventId === undefined) return input;\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n // Cannot merge into primitive — return as-is.\n return input;\n }\n return { ...(input as object), lastEventId };\n}\n\nfunction stripTrailingSlash(s: string): string {\n return s.endsWith(\"/\") ? s.slice(0, -1) : s;\n}\n\nfunction safeJsonParse<T>(s: string): T | undefined {\n try {\n return JSON.parse(s) as T;\n } catch {\n return undefined;\n }\n}\n\nasync function* streamToAsyncIterable(\n stream: ReadableStream<Uint8Array>,\n): AsyncIterable<Uint8Array> {\n const reader = stream.getReader();\n let finishedNaturally = false;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n finishedNaturally = true;\n return;\n }\n if (value !== undefined) yield value;\n }\n } finally {\n // B-131: `releaseLock()` alone detaches the reader WITHOUT canceling the stream (WHATWG\n // Streams spec) — the underlying `fetch` response body, and its socket, stays open until\n // something else cancels it or reads it to completion. A consumer that breaks out of the\n // subscription mid-stream (the ordinary shape: `for await ... break`) used to leave that\n // connection dangling. `cancel()` is a no-op once the stream is already closed, so it is safe\n // to call unconditionally on the early-exit path; skip it on natural completion, where the\n // stream is already done and canceling only risks surfacing a spurious rejection.\n if (!finishedNaturally) {\n try {\n await reader.cancel();\n } catch {\n /* best-effort cleanup — the caller's own error (if any) already takes precedence */\n }\n }\n reader.releaseLock();\n }\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error(\"aborted\"));\n return;\n }\n const t = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(new Error(\"aborted\"));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { boundFetch } from '../chunk-Q7GYMXVC.js';
1
2
  import { TheokitAgentError } from '../chunk-B5MHRQJZ.js';
2
3
  import '../chunk-CZJ6Q7CW.js';
3
4
 
@@ -215,7 +216,7 @@ async function* subscribe(name, input, opts) {
215
216
  }
216
217
  async function* openSse(name, input, opts) {
217
218
  const url = `${stripTrailingSlash(opts.baseUrl)}/api/subscriptions/${encodeURIComponent(name)}?input=${encodeURIComponent(JSON.stringify(input))}`;
218
- const fetchFn = opts.fetch ?? globalThis.fetch;
219
+ const fetchFn = boundFetch(opts.fetch);
219
220
  const res = await fetchFn(url, {
220
221
  method: "GET",
221
222
  headers: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/subscription/define-subscription.ts","../../src/subscription/internal/sse-parser.ts","../../src/subscription/types.ts","../../src/subscription/theokit-subscribe.ts"],"names":[],"mappings":";;;;AAoEO,SAAS,mBACd,IAAA,EACyC;AACzC,EAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AAC7C,IAAA,MAAM,IAAI,UAAU,gDAAgD,CAAA;AAAA,EACtE;AACA,EAAA,IAAI,KAAK,KAAA,KAAU,MAAA,IAAa,OAAO,IAAA,CAAK,KAAA,CAAM,cAAc,UAAA,EAAY;AAC1E,IAAA,MAAM,IAAI,UAAU,kEAAkE,CAAA;AAAA,EACxF;AACA,EAAA,IAAI,KAAK,MAAA,KAAW,MAAA,IAAa,OAAO,IAAA,CAAK,MAAA,CAAO,cAAc,UAAA,EAAY;AAC5E,IAAA,MAAM,IAAI,UAAU,mEAAmE,CAAA;AAAA,EACzF;AACA,EAAA,IAAI,OAAO,IAAA,CAAK,OAAA,KAAY,UAAA,EAAY;AACtC,IAAA,MAAM,IAAI,UAAU,sEAAsE,CAAA;AAAA,EAC5F;AACA,EAAA,OAAO;AAAA,IACL,GAAI,KAAK,IAAA,KAAS,MAAA,GAAY,EAAE,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK,GAAI,EAAC;AAAA,IACrD,OAAO,IAAA,CAAK,KAAA;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AA;AAAA,IACjC;AAAA,EACF,CAAA,SAAE;AAQA,IAAA,IAAI,CAAC,iBAAA,EAAmB;AACtB,MAAA,IAAI;AACF,QAAA,MAAM,OAAO,MAAA,EAAO;AAAA,MACtB,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF;AACA,IAAA,MAAA,CAAO,WAAA,EAAY;AAAA,EACrB;AACF;AAEA,SAAS,KAAA,CAAM,IAAY,MAAA,EAAqC;AAC9D,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,MAAA,CAAO,IAAI,KAAA,CAAM,SAAS,CAAC,CAAA;AAC3B,MAAA;AAAA,IACF;AACA,IAAA,MAAM,CAAA,GAAI,WAAW,MAAM;AACzB,MAAA,MAAA,EAAQ,mBAAA,CAAoB,SAAS,OAAO,CAAA;AAC5C,MAAA,OAAA,EAAQ;AAAA,IACV,GAAG,EAAE,CAAA;AACL,IAAA,MAAM,UAAU,MAAM;AACpB,MAAA,YAAA,CAAa,CAAC,CAAA;AACd,MAAA,MAAA,CAAO,IAAI,KAAA,CAAM,SAAS,CAAC,CAAA;AAAA,IAC7B,CAAA;AACA,IAAA,MAAA,EAAQ,iBAAiB,OAAA,EAAS,OAAA,EAAS,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,EAC3D,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * `defineSubscription` DSL (G8 public API) — `@theokit/sdk`.\n *\n * Per ADR D426 (AsyncGenerator handler + Zod input/output schemas).\n *\n * @public\n */\n\nimport type { SubscriptionCtx, SubscriptionDescriptor, TrackedEnvelope, ZodLike } from \"./types.js\";\n\n/**\n * Options accepted by {@link defineSubscription}.\n *\n * @public\n */\nexport interface DefineSubscriptionOptions<TInput, TOutput> {\n /** Optional explicit name. Falls back to filename derivation by the scanner. */\n name?: string;\n /** Zod schema validating subscription input. Required (typed RPC contract). */\n input: ZodLike<TInput>;\n /** Zod schema describing each output frame. Informational; not enforced per-frame. */\n output: ZodLike<TOutput>;\n /**\n * Handler that produces the subscription stream.\n *\n * Receives the validated input + {@link SubscriptionCtx}. Yielding a value\n * emits a plain output frame. Yielding a `tracked(id, payload)` envelope\n * additionally advertises a resume token to the client so reconnects can\n * resume from that point.\n */\n handler: (\n input: TInput,\n ctx: SubscriptionCtx,\n ) => AsyncGenerator<TOutput | TrackedEnvelope<TOutput>, void, void>;\n}\n\n/**\n * Define a typed subscription. Pair with `Theokit.subscribe(name, input)`\n * on the client side.\n *\n * Per ADR D426 — handler is `AsyncGenerator<TOutput | TrackedEnvelope<TOutput>>`.\n * The runtime validates input via `opts.input.safeParse` BEFORE invoking the\n * handler; failure throws {@link import('./types.js').SubscriptionInputError}.\n *\n * @example\n * ```ts\n * import { Subscription } from \"@theokit/sdk/subscription\";\n * import { z } from \"zod\";\n *\n * export default Subscription.create({\n * input: z.object({ topic: z.string() }),\n * output: z.object({ message: z.string(), ts: z.number() }),\n * async *handler(input, ctx) {\n * let cursor = ctx.lastEventId ?? \"0\";\n * while (!ctx.signal.aborted) {\n * const msgs = await fetchMessagesSince(input.topic, cursor);\n * for (const m of msgs) {\n * cursor = m.id;\n * yield ctx.tracked(m.id, { message: m.body, ts: m.ts });\n * }\n * await sleep(1000);\n * }\n * },\n * });\n * ```\n *\n * @public\n */\nexport function defineSubscription<TInput, TOutput>(\n opts: DefineSubscriptionOptions<TInput, TOutput>,\n): SubscriptionDescriptor<TInput, TOutput> {\n if (opts === null || typeof opts !== \"object\") {\n throw new TypeError(\"defineSubscription: options object is required\");\n }\n if (opts.input === undefined || typeof opts.input.safeParse !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.input must be a Zod schema (or ZodLike)\");\n }\n if (opts.output === undefined || typeof opts.output.safeParse !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.output must be a Zod schema (or ZodLike)\");\n }\n if (typeof opts.handler !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.handler must be an async generator function\");\n }\n return {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n input: opts.input,\n output: opts.output,\n handler: opts.handler,\n };\n}\n\n/** SE36 — `Subscription.create` replaces `defineSubscription` (ADR 0015). @public *\n * `Subscription.create` returns a **`SubscriptionDescriptor<TInput, TOutput>`**, not a\n * `Subscription`. The class is the namespace; the descriptor is the product.\n */\nexport class Subscription {\n private constructor() {}\n static create<TInput, TOutput>(\n opts: DefineSubscriptionOptions<TInput, TOutput>,\n ): SubscriptionDescriptor<TInput, TOutput> {\n return defineSubscription(opts);\n }\n}\n","/**\n * W3C SSE parser (G8 internal) — `@theokit/sdk`.\n *\n * Per ADR D428. Reads from `ReadableStream<Uint8Array>` or async iterable of\n * UTF-8 chunks; yields parsed {@link SSEvent} objects per W3C SSE spec.\n *\n * Independent of `internal/llm/sse.ts:parseSseStream` (LLM-specific a peer vendor AI\n * Data Stream v1; locked by D38). This parser handles the `id:` field needed\n * for tracked envelopes (G8 resume mechanism), which the LLM parser ignores.\n *\n * Reference: https://html.spec.whatwg.org/multipage/server-sent-events.html\n *\n * @internal\n */\n\nimport type { SSEvent } from \"./sse-encoder.js\";\n\nconst decoder = new TextDecoder(\"utf-8\");\n\n/**\n * Parse an async iterable of UTF-8 byte chunks into a stream of SSE events.\n *\n * Implements the W3C event stream parser:\n * - Lines are split by `\\n`, `\\r\\n`, or `\\r`\n * - Events are dispatched on blank line (no `:` and no field name)\n * - Fields: `event`, `data` (multi-line concat with `\\n`), `id`, `retry`\n * - Lines starting with `:` are comments (ignored, except dispatched as `comment`)\n * - Unknown fields silently ignored per spec\n *\n * Empty events (no fields) are NOT dispatched per spec.\n *\n * @internal\n */\nexport async function* parseSseW3C(\n source: AsyncIterable<Uint8Array>,\n): AsyncGenerator<SSEvent, void, void> {\n let buffer = \"\";\n let eventName: string | undefined;\n let dataLines: string[] = [];\n let id: string | undefined;\n let retry: number | undefined;\n let commentLines: string[] = [];\n let hasField = false;\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: dispatch builds SSEvent from per-field state per W3C spec — refactor candidate\n const dispatch = (): SSEvent | null => {\n if (!hasField) {\n // Blank line with no preceding fields → reset state, no dispatch (per spec § 9.2.6)\n eventName = undefined;\n dataLines = [];\n id = undefined;\n retry = undefined;\n commentLines = [];\n return null;\n }\n const chunk: SSEvent = {};\n if (eventName !== undefined) (chunk as { event?: string }).event = eventName;\n if (dataLines.length > 0) (chunk as { data?: string }).data = dataLines.join(\"\\n\");\n if (id !== undefined) (chunk as { id?: string }).id = id;\n if (retry !== undefined) (chunk as { retry?: number }).retry = retry;\n if (commentLines.length > 0) (chunk as { comment?: string }).comment = commentLines.join(\"\\n\");\n eventName = undefined;\n dataLines = [];\n id = undefined;\n retry = undefined;\n commentLines = [];\n hasField = false;\n return chunk;\n };\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: handleLine dispatches across all SSE field kinds per W3C spec — refactor candidate\n const handleLine = (line: string): SSEvent | null => {\n if (line === \"\") {\n return dispatch();\n }\n if (line.startsWith(\":\")) {\n // Comment line — per spec ignored, but we surface it for keepalive visibility.\n commentLines.push(line.slice(1).replace(/^ /, \"\"));\n hasField = true;\n return null;\n }\n const colonIdx = line.indexOf(\":\");\n let field: string;\n let value: string;\n if (colonIdx === -1) {\n field = line;\n value = \"\";\n } else {\n field = line.slice(0, colonIdx);\n value = line.slice(colonIdx + 1);\n // Strip ONE leading space if present (per spec § 9.2.6)\n if (value.startsWith(\" \")) value = value.slice(1);\n }\n switch (field) {\n case \"event\":\n eventName = value;\n hasField = true;\n break;\n case \"data\":\n dataLines.push(value);\n hasField = true;\n break;\n case \"id\":\n // Per spec: id with NULL is ignored\n if (!value.includes(\"\\0\")) {\n id = value;\n hasField = true;\n }\n break;\n case \"retry\":\n if (/^\\d+$/.test(value)) {\n retry = Number.parseInt(value, 10);\n hasField = true;\n }\n break;\n default:\n // Unknown field — ignored per spec\n break;\n }\n return null;\n };\n\n for await (const bytes of source) {\n // Normalize CRLF / CR to LF then split\n buffer += decoder.decode(bytes, { stream: true }).replace(/\\r\\n|\\r/g, \"\\n\");\n let idx: number;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic while-assignment loop for buffered line parsing\n while ((idx = buffer.indexOf(\"\\n\")) !== -1) {\n const line = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 1);\n const event = handleLine(line);\n if (event !== null) yield event;\n }\n }\n // Flush remaining buffer as a final line (no trailing newline case)\n buffer += decoder.decode();\n if (buffer.length > 0) {\n const event = handleLine(buffer);\n if (event !== null) yield event;\n }\n // Final dispatch in case last event lacked terminating blank line\n const tail = dispatch();\n if (tail !== null) yield tail;\n}\n","/**\n * Subscription type contract (G8 v1.7.0) — `@theokit/sdk`.\n *\n * Per ADRs D423 (resume token opaque), D424 (transport selection),\n * D426 (defineSubscription DSL shape).\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"../errors.js\";\n\n/**\n * Transport selection for subscriptions.\n *\n * - `'ws'`: WebSocket (bidirectional). Required for inbound client→server frames.\n * v1.7 ships Node-canonical `ws` adapter; CF/Bun/Deno deferred to v1.8.x per ADR D425.\n * - `'sse'`: W3C Server-Sent Events (server→client only). Browser-native EventSource.\n * - `'auto'`: Prefer WS, fall back SSE on upgrade failure. Default.\n *\n * @public\n */\nexport type SubscriptionTransport = \"ws\" | \"sse\" | \"auto\";\n\n/**\n * Context passed to a subscription `handler` on each invocation.\n *\n * @public\n */\nexport interface SubscriptionCtx {\n /**\n * Opaque resume token forwarded by the client when reconnecting.\n * Handler defines its own semantics (monotonic int, ULID, timestamp,\n * encrypted cursor). SDK passes through unchanged. Per ADR D423.\n */\n readonly lastEventId?: string;\n\n /**\n * AbortSignal that fires when the subscription is cancelled\n * (client disconnect, consumer abort, server shutdown).\n * Handler MUST honor `signal.aborted` in long-running loops.\n */\n readonly signal: AbortSignal;\n\n /**\n * Stable identifier for the underlying transport connection.\n * Different from the subscription name — one connection may host\n * many subscriptions. Useful for logging / per-connection state.\n */\n readonly connectionId: string;\n\n /**\n * Force-close the underlying transport with optional WS close code + reason.\n * Used by consumer code (e.g., auth middleware revoking a session) to\n * terminate a subscription that should not continue.\n */\n disconnect(code?: number, reason?: string): void;\n\n /**\n * Helper to mint a tracked envelope `[id, payload]`.\n * Yielding tracked envelopes lets the client advance `lastEventId`\n * so reconnects can resume from that point.\n */\n tracked<TPayload>(id: string, payload: TPayload): TrackedEnvelope<TPayload>;\n}\n\n/**\n * Tracked envelope: `[id, payload]` tuple yielded by subscription handlers\n * to advertise the resume token associated with the payload.\n *\n * The encoder writes the `id` as an SSE `id:` field or WS payload metadata\n * so the client can echo it back on reconnect (`input.lastEventId`).\n *\n * Per ADR D423.\n *\n * @public\n */\nexport type TrackedEnvelope<T> = readonly [id: string, payload: T];\n\n/**\n * Type guard for {@link TrackedEnvelope}.\n *\n * @public\n */\nexport function isTrackedEnvelope(value: unknown): value is TrackedEnvelope<unknown> {\n return Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\";\n}\n\n/**\n * Mint a tracked envelope. Equivalent to `[id, payload] as const`,\n * exported as a function so consumers don't repeat the tuple cast.\n *\n * @public\n */\nexport function tracked<T>(id: string, payload: T): TrackedEnvelope<T> {\n if (typeof id !== \"string\" || id.length === 0) {\n throw new TypeError(\"tracked(): id must be a non-empty string\");\n }\n return [id, payload] as const;\n}\n\n/**\n * Base error for the subscription subsystem. Extends {@link TheokitAgentError}\n * so existing `instanceof TheokitAgentError` branches keep working.\n *\n * @public\n */\nexport class SubscriptionError extends TheokitAgentError {\n override readonly name: string = \"SubscriptionError\";\n\n constructor(message: string, options: { code?: string; cause?: unknown } = {}) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown when subscription input fails Zod schema validation.\n *\n * @public\n */\nexport class SubscriptionInputError extends SubscriptionError {\n override readonly name: string = \"SubscriptionInputError\";\n\n readonly issues: unknown;\n\n constructor(message: string, options: { issues: unknown; cause?: unknown }) {\n super(message, { code: \"subscription_input_invalid\", cause: options.cause });\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown when a subscription transport disconnects unexpectedly\n * AND the client did not opt out of reconnect.\n *\n * @public\n */\nexport class SubscriptionDisconnectError extends SubscriptionError {\n override readonly name: string = \"SubscriptionDisconnectError\";\n\n readonly closeCode?: number;\n readonly closeReason?: string;\n\n constructor(\n message: string,\n options: { closeCode?: number; closeReason?: string; cause?: unknown } = {},\n ) {\n super(message, { code: \"subscription_disconnected\", cause: options.cause });\n if (options.closeCode !== undefined) this.closeCode = options.closeCode;\n if (options.closeReason !== undefined) this.closeReason = options.closeReason;\n }\n}\n\n/**\n * Descriptor returned by {@link Subscription.create}. Carries the typed\n * input/output Zod schemas + handler factory.\n *\n * @public\n */\nexport interface SubscriptionDescriptor<TInput = unknown, TOutput = unknown> {\n /** Optional explicit name; the runtime may also derive name from file path. */\n readonly name?: string;\n /** Zod schema for the subscription input. Validated at dispatch boundary. */\n readonly input: ZodLike<TInput>;\n /** Zod schema for each output frame (informational; not enforced per-frame). */\n readonly output: ZodLike<TOutput>;\n /** Async handler that yields output frames (or tracked envelopes). */\n readonly handler: (\n input: TInput,\n ctx: SubscriptionCtx,\n ) => AsyncGenerator<TOutput | TrackedEnvelope<TOutput>, void, void>;\n}\n\n/**\n * Minimal structural Zod type used to avoid hard peer-dep import.\n * Mirrors the surface used by other SDK modules (e.g., `define-tool.ts`).\n *\n * Emitted rather than erased: it appears in the signature of `defineSubscription`, which\n * `@theokit/sdk/subscription` publishes, so a consumer's type-aware lint has to be able to\n * resolve it.\n */\nexport interface ZodLike<T> {\n safeParse(value: unknown): { success: true; data: T } | { success: false; error: unknown };\n parse(value: unknown): T;\n}\n","/**\n * `Theokit.subscribe` client (G8 public API) — `@theokit/sdk`.\n *\n * Per ADR D427 (Theokit.subscribe namespace) + D424 (transport selection)\n * + D423 (lastEventId opaque propagation).\n *\n * Returns an AsyncGenerator that yields server-sent values. Transparent\n * reconnect with exponential backoff. Propagates `lastEventId` from the last\n * received tracked envelope on each reconnect attempt.\n *\n * @public\n */\n\nimport { parseSseW3C } from \"./internal/sse-parser.js\";\nimport type { WireFrame } from \"./internal/subscription-runtime.js\";\nimport {\n SubscriptionDisconnectError,\n SubscriptionError,\n type SubscriptionTransport,\n} from \"./types.js\";\n\n/**\n * Options accepted by `Theokit.subscribe(name, input, opts?)`.\n *\n * @public\n */\nexport interface SubscribeOptions {\n /** Base URL of the server (e.g., `\"http://localhost:3000\"`). Required. */\n baseUrl: string;\n /** Preferred transport. Default `\"auto\"` (WS preferred, SSE fallback). */\n transport?: SubscriptionTransport;\n /** Max reconnect attempts (default 10). 0 disables reconnect. */\n maxReconnectAttempts?: number;\n /** Backoff strategy. Default exponential `min(30_000, 1000 * 2^attempt)` ms. */\n retryDelayMs?: (attempt: number) => number;\n /** Caller-supplied abort signal. Cancels the subscription entirely. */\n signal?: AbortSignal;\n /** Additional fetch-style headers (e.g., `Authorization`). */\n headers?: Record<string, string>;\n /**\n * Override the SSE transport's `fetch`. Defaults to `globalThis.fetch`.\n * Lets a consumer supply a proxying agent or instrumented fetch without\n * mutating the runtime global.\n */\n fetch?: typeof globalThis.fetch;\n /**\n * Override the WS transport's `WebSocket` constructor. Defaults to\n * `globalThis.WebSocket`. Lets a consumer polyfill WS on a runtime that\n * lacks it, or supply an instrumented implementation, without mutating\n * the runtime global.\n */\n WebSocket?: typeof WebSocket;\n}\n\nconst defaultRetry = (attempt: number) => Math.min(30_000, 1000 * 2 ** attempt);\n\n/**\n * Subscribe to a typed subscription. Yields values produced by the server\n * handler. On disconnect with reconnect enabled, transparently re-establishes\n * the connection and forwards `lastEventId` from the last received tracked\n * envelope so the server handler can resume.\n *\n * @public\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: subscribe orchestrates reconnect + transport switch + resume, and the interleaving is the contract. THE DEBT IS UNOWNED — this used to claim it was \"tracked in subscription/theokit-subscribe.ts:52 followup\", which is a line in an unrelated JSDoc block in this same file, and grepping the file for followup/todo/fixme/#NNN returns only this comment. The citation was its own only evidence. Saying the debt is unowned is worse news and true; a maintainer who checks the tracking before touching the module's @public entry point now learns that in one grep instead of three.\nexport async function* subscribe<TInput, TOutput>(\n name: string,\n input: TInput,\n opts: SubscribeOptions,\n): AsyncGenerator<TOutput, void, void> {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new SubscriptionError(\"Theokit.subscribe: name must be a non-empty string\", {\n code: \"subscribe_name_invalid\",\n });\n }\n if (opts === null || typeof opts !== \"object\" || typeof opts.baseUrl !== \"string\") {\n throw new SubscriptionError(\"Theokit.subscribe: opts.baseUrl is required\", {\n code: \"subscribe_baseUrl_missing\",\n });\n }\n const transport = opts.transport ?? \"auto\";\n const maxReconnects = opts.maxReconnectAttempts ?? 10;\n const retry = opts.retryDelayMs ?? defaultRetry;\n\n let lastEventId: string | undefined;\n let attempt = 0;\n\n while (true) {\n if (opts.signal?.aborted) return;\n try {\n const inputWithCursor = mergeLastEventId(input, lastEventId);\n const chosen = await selectTransport(transport, name, opts);\n if (chosen === \"ws\") {\n for await (const out of openWs<TOutput>(name, inputWithCursor, opts)) {\n if (out.lastEventId !== undefined) lastEventId = out.lastEventId;\n attempt = 0; // reset backoff on successful frame\n yield out.value;\n }\n } else {\n for await (const out of openSse<TOutput>(name, inputWithCursor, opts)) {\n if (out.lastEventId !== undefined) lastEventId = out.lastEventId;\n attempt = 0;\n yield out.value;\n }\n }\n // Clean end-of-stream — no reconnect.\n return;\n } catch (cause) {\n if (opts.signal?.aborted) return;\n if (maxReconnects === 0 || attempt >= maxReconnects) {\n if (cause instanceof SubscriptionError) throw cause;\n throw new SubscriptionDisconnectError(\n `subscription \"${name}\" disconnected; reconnect exhausted`,\n { cause },\n );\n }\n const delay = retry(attempt);\n attempt++;\n await sleep(delay, opts.signal);\n }\n }\n}\n\ninterface FrameOut<T> {\n readonly value: T;\n readonly lastEventId?: string;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: openSse parses framed SSE stream with abort/error/retry branches — refactor candidate\nasync function* openSse<T>(\n name: string,\n input: unknown,\n opts: SubscribeOptions,\n): AsyncIterable<FrameOut<T>> {\n const url = `${stripTrailingSlash(opts.baseUrl)}/api/subscriptions/${encodeURIComponent(name)}?input=${encodeURIComponent(JSON.stringify(input))}`;\n const fetchFn = opts.fetch ?? globalThis.fetch;\n const res = await fetchFn(url, {\n method: \"GET\",\n headers: {\n accept: \"text/event-stream\",\n ...(opts.headers ?? {}),\n },\n ...(opts.signal !== undefined ? { signal: opts.signal } : {}),\n });\n if (!res.ok || res.body === null) {\n throw new SubscriptionError(`SSE subscribe failed: HTTP ${res.status} ${res.statusText}`, {\n code: \"sse_http_error\",\n });\n }\n const events = parseSseW3C(streamToAsyncIterable(res.body));\n for await (const ev of events) {\n if (ev.event === \"end\") return;\n if (ev.event === \"error\") {\n throw new SubscriptionError(`SSE server emitted error: ${ev.data ?? \"(no body)\"}`, {\n code: \"sse_server_error\",\n });\n }\n if (ev.event === \"connected\") continue;\n if (ev.data === undefined) continue;\n const parsedValue = safeJsonParse<T>(ev.data);\n if (parsedValue === undefined) continue;\n yield {\n value: parsedValue,\n ...(ev.id !== undefined ? { lastEventId: ev.id } : {}),\n };\n }\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: openWs orchestrates WS lifecycle + envelope decode + cleanup — refactor candidate\nasync function* openWs<T>(\n name: string,\n input: unknown,\n opts: SubscribeOptions,\n): AsyncIterable<FrameOut<T>> {\n const baseUrl = stripTrailingSlash(opts.baseUrl);\n const wsUrl = baseUrl\n .replace(/^http:/, \"ws:\")\n .replace(/^https:/, \"wss:\")\n .concat(\"/api/ws\");\n\n const WS = opts.WebSocket ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;\n if (WS === undefined) {\n throw new SubscriptionError(\n \"Theokit.subscribe(transport='ws'): no global WebSocket available. Use Node >=22 or install 'ws' as a runtime dep + assign to globalThis.WebSocket, or pass opts.WebSocket.\",\n { code: \"ws_global_missing\" },\n );\n }\n const ws = new WS(wsUrl);\n\n // Set up async iterator-like state.\n const incoming: WireFrame[] = [];\n // biome-ignore lint/suspicious/noConfusingVoidType: idiomatic event-callback signature; refactoring to undefined would mask the no-value semantics\n let waiter: ((value: void) => void) | null = null;\n let closed = false;\n let closeError: Error | undefined;\n\n ws.addEventListener(\"message\", (ev: MessageEvent) => {\n const data = typeof ev.data === \"string\" ? ev.data : \"\";\n const frame = safeJsonParse<WireFrame>(data);\n if (frame !== undefined) {\n incoming.push(frame);\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n }\n });\n ws.addEventListener(\"close\", () => {\n closed = true;\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n });\n ws.addEventListener(\"error\", () => {\n closed = true;\n closeError = new Error(\"WebSocket error\");\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n });\n\n await new Promise<void>((resolve, reject) => {\n ws.addEventListener(\"open\", () => resolve(), { once: true });\n ws.addEventListener(\"error\", () => reject(new Error(\"WS connect failed\")), { once: true });\n });\n\n // Send subscribe request after handshake.\n ws.send(JSON.stringify({ kind: \"subscribe\", name, input }));\n\n if (opts.signal !== undefined) {\n opts.signal.addEventListener(\"abort\", () => ws.close(), { once: true });\n }\n\n try {\n while (true) {\n if (incoming.length === 0) {\n if (closed) {\n if (closeError !== undefined) throw closeError;\n return;\n }\n await new Promise<void>((resolve) => {\n waiter = resolve;\n });\n continue;\n }\n const frame = incoming.shift() as WireFrame;\n if (frame.type === \"end\") return;\n if (frame.type === \"error\") {\n // The server's own code wins. `ws_server_error` is the fallback for a frame that carries\n // none — it used to be the code for EVERY server-side failure, so a caller could not tell an\n // invalid input from a disconnect without reading English out of the message.\n throw new SubscriptionError(\n `WS server emitted error: ${frame.error?.message ?? \"(unknown)\"}`,\n { code: frame.error?.code ?? \"ws_server_error\" },\n );\n }\n const value = frame.data as T;\n yield {\n value,\n ...(frame.id !== undefined ? { lastEventId: frame.id } : {}),\n };\n }\n } finally {\n try {\n ws.close();\n } catch {\n /* ignore */\n }\n }\n}\n\nasync function selectTransport(\n pref: SubscriptionTransport,\n _name: string,\n opts: SubscribeOptions,\n): Promise<\"ws\" | \"sse\"> {\n if (pref === \"ws\") return \"ws\";\n if (pref === \"sse\") return \"sse\";\n // auto — prefer WS if available (injected or global), else SSE.\n const WS = opts.WebSocket ?? (globalThis as { WebSocket?: unknown }).WebSocket;\n if (typeof WS === \"function\") {\n return \"ws\";\n }\n return \"sse\";\n}\n\nfunction mergeLastEventId(input: unknown, lastEventId: string | undefined): unknown {\n if (lastEventId === undefined) return input;\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n // Cannot merge into primitive — return as-is.\n return input;\n }\n return { ...(input as object), lastEventId };\n}\n\nfunction stripTrailingSlash(s: string): string {\n return s.endsWith(\"/\") ? s.slice(0, -1) : s;\n}\n\nfunction safeJsonParse<T>(s: string): T | undefined {\n try {\n return JSON.parse(s) as T;\n } catch {\n return undefined;\n }\n}\n\nasync function* streamToAsyncIterable(\n stream: ReadableStream<Uint8Array>,\n): AsyncIterable<Uint8Array> {\n const reader = stream.getReader();\n let finishedNaturally = false;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n finishedNaturally = true;\n return;\n }\n if (value !== undefined) yield value;\n }\n } finally {\n // B-131: `releaseLock()` alone detaches the reader WITHOUT canceling the stream (WHATWG\n // Streams spec) — the underlying `fetch` response body, and its socket, stays open until\n // something else cancels it or reads it to completion. A consumer that breaks out of the\n // subscription mid-stream (the ordinary shape: `for await ... break`) used to leave that\n // connection dangling. `cancel()` is a no-op once the stream is already closed, so it is safe\n // to call unconditionally on the early-exit path; skip it on natural completion, where the\n // stream is already done and canceling only risks surfacing a spurious rejection.\n if (!finishedNaturally) {\n try {\n await reader.cancel();\n } catch {\n /* best-effort cleanup — the caller's own error (if any) already takes precedence */\n }\n }\n reader.releaseLock();\n }\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error(\"aborted\"));\n return;\n }\n const t = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(new Error(\"aborted\"));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n"]}
1
+ {"version":3,"sources":["../../src/subscription/define-subscription.ts","../../src/subscription/internal/sse-parser.ts","../../src/subscription/types.ts","../../src/subscription/theokit-subscribe.ts"],"names":[],"mappings":";;;;;AAoEO,SAAS,mBACd,IAAA,EACyC;AACzC,EAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AAC7C,IAAA,MAAM,IAAI,UAAU,gDAAgD,CAAA;AAAA,EACtE;AACA,EAAA,IAAI,KAAK,KAAA,KAAU,MAAA,IAAa,OAAO,IAAA,CAAK,KAAA,CAAM,cAAc,UAAA,EAAY;AAC1E,IAAA,MAAM,IAAI,UAAU,kEAAkE,CAAA;AAAA,EACxF;AACA,EAAA,IAAI,KAAK,MAAA,KAAW,MAAA,IAAa,OAAO,IAAA,CAAK,MAAA,CAAO,cAAc,UAAA,EAAY;AAC5E,IAAA,MAAM,IAAI,UAAU,mEAAmE,CAAA;AAAA,EACzF;AACA,EAAA,IAAI,OAAO,IAAA,CAAK,OAAA,KAAY,UAAA,EAAY;AACtC,IAAA,MAAM,IAAI,UAAU,sEAAsE,CAAA;AAAA,EAC5F;AACA,EAAA,OAAO;AAAA,IACL,GAAI,KAAK,IAAA,KAAS,MAAA,GAAY,EAAE,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK,GAAI,EAAC;AAAA,IACrD,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,SAAS,IAAA,CAAK;AAAA,GAChB;AACF;AAMO,IAAM,eAAN,MAAmB;AAAA,EAChB,WAAA,GAAc;AAAA,EAAC;AAAA,EACvB,OAAO,OACL,IAAA,EACyC;AACzC,IAAA,OAAO,mBAAmB,IAAI,C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AAAA,EACrB;AACF;AAEA,SAAS,KAAA,CAAM,IAAY,MAAA,EAAqC;AAC9D,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,MAAA,CAAO,IAAI,KAAA,CAAM,SAAS,CAAC,CAAA;AAC3B,MAAA;AAAA,IACF;AACA,IAAA,MAAM,CAAA,GAAI,WAAW,MAAM;AACzB,MAAA,MAAA,EAAQ,mBAAA,CAAoB,SAAS,OAAO,CAAA;AAC5C,MAAA,OAAA,EAAQ;AAAA,IACV,GAAG,EAAE,CAAA;AACL,IAAA,MAAM,UAAU,MAAM;AACpB,MAAA,YAAA,CAAa,CAAC,CAAA;AACd,MAAA,MAAA,CAAO,IAAI,KAAA,CAAM,SAAS,CAAC,CAAA;AAAA,IAC7B,CAAA;AACA,IAAA,MAAA,EAAQ,iBAAiB,OAAA,EAAS,OAAA,EAAS,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,EAC3D,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * `defineSubscription` DSL (G8 public API) — `@theokit/sdk`.\n *\n * Per ADR D426 (AsyncGenerator handler + Zod input/output schemas).\n *\n * @public\n */\n\nimport type { SubscriptionCtx, SubscriptionDescriptor, TrackedEnvelope, ZodLike } from \"./types.js\";\n\n/**\n * Options accepted by {@link defineSubscription}.\n *\n * @public\n */\nexport interface DefineSubscriptionOptions<TInput, TOutput> {\n /** Optional explicit name. Falls back to filename derivation by the scanner. */\n name?: string;\n /** Zod schema validating subscription input. Required (typed RPC contract). */\n input: ZodLike<TInput>;\n /** Zod schema describing each output frame. Informational; not enforced per-frame. */\n output: ZodLike<TOutput>;\n /**\n * Handler that produces the subscription stream.\n *\n * Receives the validated input + {@link SubscriptionCtx}. Yielding a value\n * emits a plain output frame. Yielding a `tracked(id, payload)` envelope\n * additionally advertises a resume token to the client so reconnects can\n * resume from that point.\n */\n handler: (\n input: TInput,\n ctx: SubscriptionCtx,\n ) => AsyncGenerator<TOutput | TrackedEnvelope<TOutput>, void, void>;\n}\n\n/**\n * Define a typed subscription. Pair with `Theokit.subscribe(name, input)`\n * on the client side.\n *\n * Per ADR D426 — handler is `AsyncGenerator<TOutput | TrackedEnvelope<TOutput>>`.\n * The runtime validates input via `opts.input.safeParse` BEFORE invoking the\n * handler; failure throws {@link import('./types.js').SubscriptionInputError}.\n *\n * @example\n * ```ts\n * import { Subscription } from \"@theokit/sdk/subscription\";\n * import { z } from \"zod\";\n *\n * export default Subscription.create({\n * input: z.object({ topic: z.string() }),\n * output: z.object({ message: z.string(), ts: z.number() }),\n * async *handler(input, ctx) {\n * let cursor = ctx.lastEventId ?? \"0\";\n * while (!ctx.signal.aborted) {\n * const msgs = await fetchMessagesSince(input.topic, cursor);\n * for (const m of msgs) {\n * cursor = m.id;\n * yield ctx.tracked(m.id, { message: m.body, ts: m.ts });\n * }\n * await sleep(1000);\n * }\n * },\n * });\n * ```\n *\n * @public\n */\nexport function defineSubscription<TInput, TOutput>(\n opts: DefineSubscriptionOptions<TInput, TOutput>,\n): SubscriptionDescriptor<TInput, TOutput> {\n if (opts === null || typeof opts !== \"object\") {\n throw new TypeError(\"defineSubscription: options object is required\");\n }\n if (opts.input === undefined || typeof opts.input.safeParse !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.input must be a Zod schema (or ZodLike)\");\n }\n if (opts.output === undefined || typeof opts.output.safeParse !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.output must be a Zod schema (or ZodLike)\");\n }\n if (typeof opts.handler !== \"function\") {\n throw new TypeError(\"defineSubscription: opts.handler must be an async generator function\");\n }\n return {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n input: opts.input,\n output: opts.output,\n handler: opts.handler,\n };\n}\n\n/** SE36 — `Subscription.create` replaces `defineSubscription` (ADR 0015). @public *\n * `Subscription.create` returns a **`SubscriptionDescriptor<TInput, TOutput>`**, not a\n * `Subscription`. The class is the namespace; the descriptor is the product.\n */\nexport class Subscription {\n private constructor() {}\n static create<TInput, TOutput>(\n opts: DefineSubscriptionOptions<TInput, TOutput>,\n ): SubscriptionDescriptor<TInput, TOutput> {\n return defineSubscription(opts);\n }\n}\n","/**\n * W3C SSE parser (G8 internal) — `@theokit/sdk`.\n *\n * Per ADR D428. Reads from `ReadableStream<Uint8Array>` or async iterable of\n * UTF-8 chunks; yields parsed {@link SSEvent} objects per W3C SSE spec.\n *\n * Independent of `internal/llm/sse.ts:parseSseStream` (LLM-specific a peer vendor AI\n * Data Stream v1; locked by D38). This parser handles the `id:` field needed\n * for tracked envelopes (G8 resume mechanism), which the LLM parser ignores.\n *\n * Reference: https://html.spec.whatwg.org/multipage/server-sent-events.html\n *\n * @internal\n */\n\nimport type { SSEvent } from \"./sse-encoder.js\";\n\nconst decoder = new TextDecoder(\"utf-8\");\n\n/**\n * Parse an async iterable of UTF-8 byte chunks into a stream of SSE events.\n *\n * Implements the W3C event stream parser:\n * - Lines are split by `\\n`, `\\r\\n`, or `\\r`\n * - Events are dispatched on blank line (no `:` and no field name)\n * - Fields: `event`, `data` (multi-line concat with `\\n`), `id`, `retry`\n * - Lines starting with `:` are comments (ignored, except dispatched as `comment`)\n * - Unknown fields silently ignored per spec\n *\n * Empty events (no fields) are NOT dispatched per spec.\n *\n * @internal\n */\nexport async function* parseSseW3C(\n source: AsyncIterable<Uint8Array>,\n): AsyncGenerator<SSEvent, void, void> {\n let buffer = \"\";\n let eventName: string | undefined;\n let dataLines: string[] = [];\n let id: string | undefined;\n let retry: number | undefined;\n let commentLines: string[] = [];\n let hasField = false;\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: dispatch builds SSEvent from per-field state per W3C spec — refactor candidate\n const dispatch = (): SSEvent | null => {\n if (!hasField) {\n // Blank line with no preceding fields → reset state, no dispatch (per spec § 9.2.6)\n eventName = undefined;\n dataLines = [];\n id = undefined;\n retry = undefined;\n commentLines = [];\n return null;\n }\n const chunk: SSEvent = {};\n if (eventName !== undefined) (chunk as { event?: string }).event = eventName;\n if (dataLines.length > 0) (chunk as { data?: string }).data = dataLines.join(\"\\n\");\n if (id !== undefined) (chunk as { id?: string }).id = id;\n if (retry !== undefined) (chunk as { retry?: number }).retry = retry;\n if (commentLines.length > 0) (chunk as { comment?: string }).comment = commentLines.join(\"\\n\");\n eventName = undefined;\n dataLines = [];\n id = undefined;\n retry = undefined;\n commentLines = [];\n hasField = false;\n return chunk;\n };\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: handleLine dispatches across all SSE field kinds per W3C spec — refactor candidate\n const handleLine = (line: string): SSEvent | null => {\n if (line === \"\") {\n return dispatch();\n }\n if (line.startsWith(\":\")) {\n // Comment line — per spec ignored, but we surface it for keepalive visibility.\n commentLines.push(line.slice(1).replace(/^ /, \"\"));\n hasField = true;\n return null;\n }\n const colonIdx = line.indexOf(\":\");\n let field: string;\n let value: string;\n if (colonIdx === -1) {\n field = line;\n value = \"\";\n } else {\n field = line.slice(0, colonIdx);\n value = line.slice(colonIdx + 1);\n // Strip ONE leading space if present (per spec § 9.2.6)\n if (value.startsWith(\" \")) value = value.slice(1);\n }\n switch (field) {\n case \"event\":\n eventName = value;\n hasField = true;\n break;\n case \"data\":\n dataLines.push(value);\n hasField = true;\n break;\n case \"id\":\n // Per spec: id with NULL is ignored\n if (!value.includes(\"\\0\")) {\n id = value;\n hasField = true;\n }\n break;\n case \"retry\":\n if (/^\\d+$/.test(value)) {\n retry = Number.parseInt(value, 10);\n hasField = true;\n }\n break;\n default:\n // Unknown field — ignored per spec\n break;\n }\n return null;\n };\n\n for await (const bytes of source) {\n // Normalize CRLF / CR to LF then split\n buffer += decoder.decode(bytes, { stream: true }).replace(/\\r\\n|\\r/g, \"\\n\");\n let idx: number;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic while-assignment loop for buffered line parsing\n while ((idx = buffer.indexOf(\"\\n\")) !== -1) {\n const line = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 1);\n const event = handleLine(line);\n if (event !== null) yield event;\n }\n }\n // Flush remaining buffer as a final line (no trailing newline case)\n buffer += decoder.decode();\n if (buffer.length > 0) {\n const event = handleLine(buffer);\n if (event !== null) yield event;\n }\n // Final dispatch in case last event lacked terminating blank line\n const tail = dispatch();\n if (tail !== null) yield tail;\n}\n","/**\n * Subscription type contract (G8 v1.7.0) — `@theokit/sdk`.\n *\n * Per ADRs D423 (resume token opaque), D424 (transport selection),\n * D426 (defineSubscription DSL shape).\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"../errors.js\";\n\n/**\n * Transport selection for subscriptions.\n *\n * - `'ws'`: WebSocket (bidirectional). Required for inbound client→server frames.\n * v1.7 ships Node-canonical `ws` adapter; CF/Bun/Deno deferred to v1.8.x per ADR D425.\n * - `'sse'`: W3C Server-Sent Events (server→client only). Browser-native EventSource.\n * - `'auto'`: Prefer WS, fall back SSE on upgrade failure. Default.\n *\n * @public\n */\nexport type SubscriptionTransport = \"ws\" | \"sse\" | \"auto\";\n\n/**\n * Context passed to a subscription `handler` on each invocation.\n *\n * @public\n */\nexport interface SubscriptionCtx {\n /**\n * Opaque resume token forwarded by the client when reconnecting.\n * Handler defines its own semantics (monotonic int, ULID, timestamp,\n * encrypted cursor). SDK passes through unchanged. Per ADR D423.\n */\n readonly lastEventId?: string;\n\n /**\n * AbortSignal that fires when the subscription is cancelled\n * (client disconnect, consumer abort, server shutdown).\n * Handler MUST honor `signal.aborted` in long-running loops.\n */\n readonly signal: AbortSignal;\n\n /**\n * Stable identifier for the underlying transport connection.\n * Different from the subscription name — one connection may host\n * many subscriptions. Useful for logging / per-connection state.\n */\n readonly connectionId: string;\n\n /**\n * Force-close the underlying transport with optional WS close code + reason.\n * Used by consumer code (e.g., auth middleware revoking a session) to\n * terminate a subscription that should not continue.\n */\n disconnect(code?: number, reason?: string): void;\n\n /**\n * Helper to mint a tracked envelope `[id, payload]`.\n * Yielding tracked envelopes lets the client advance `lastEventId`\n * so reconnects can resume from that point.\n */\n tracked<TPayload>(id: string, payload: TPayload): TrackedEnvelope<TPayload>;\n}\n\n/**\n * Tracked envelope: `[id, payload]` tuple yielded by subscription handlers\n * to advertise the resume token associated with the payload.\n *\n * The encoder writes the `id` as an SSE `id:` field or WS payload metadata\n * so the client can echo it back on reconnect (`input.lastEventId`).\n *\n * Per ADR D423.\n *\n * @public\n */\nexport type TrackedEnvelope<T> = readonly [id: string, payload: T];\n\n/**\n * Type guard for {@link TrackedEnvelope}.\n *\n * @public\n */\nexport function isTrackedEnvelope(value: unknown): value is TrackedEnvelope<unknown> {\n return Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\";\n}\n\n/**\n * Mint a tracked envelope. Equivalent to `[id, payload] as const`,\n * exported as a function so consumers don't repeat the tuple cast.\n *\n * @public\n */\nexport function tracked<T>(id: string, payload: T): TrackedEnvelope<T> {\n if (typeof id !== \"string\" || id.length === 0) {\n throw new TypeError(\"tracked(): id must be a non-empty string\");\n }\n return [id, payload] as const;\n}\n\n/**\n * Base error for the subscription subsystem. Extends {@link TheokitAgentError}\n * so existing `instanceof TheokitAgentError` branches keep working.\n *\n * @public\n */\nexport class SubscriptionError extends TheokitAgentError {\n override readonly name: string = \"SubscriptionError\";\n\n constructor(message: string, options: { code?: string; cause?: unknown } = {}) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown when subscription input fails Zod schema validation.\n *\n * @public\n */\nexport class SubscriptionInputError extends SubscriptionError {\n override readonly name: string = \"SubscriptionInputError\";\n\n readonly issues: unknown;\n\n constructor(message: string, options: { issues: unknown; cause?: unknown }) {\n super(message, { code: \"subscription_input_invalid\", cause: options.cause });\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown when a subscription transport disconnects unexpectedly\n * AND the client did not opt out of reconnect.\n *\n * @public\n */\nexport class SubscriptionDisconnectError extends SubscriptionError {\n override readonly name: string = \"SubscriptionDisconnectError\";\n\n readonly closeCode?: number;\n readonly closeReason?: string;\n\n constructor(\n message: string,\n options: { closeCode?: number; closeReason?: string; cause?: unknown } = {},\n ) {\n super(message, { code: \"subscription_disconnected\", cause: options.cause });\n if (options.closeCode !== undefined) this.closeCode = options.closeCode;\n if (options.closeReason !== undefined) this.closeReason = options.closeReason;\n }\n}\n\n/**\n * Descriptor returned by {@link Subscription.create}. Carries the typed\n * input/output Zod schemas + handler factory.\n *\n * @public\n */\nexport interface SubscriptionDescriptor<TInput = unknown, TOutput = unknown> {\n /** Optional explicit name; the runtime may also derive name from file path. */\n readonly name?: string;\n /** Zod schema for the subscription input. Validated at dispatch boundary. */\n readonly input: ZodLike<TInput>;\n /** Zod schema for each output frame (informational; not enforced per-frame). */\n readonly output: ZodLike<TOutput>;\n /** Async handler that yields output frames (or tracked envelopes). */\n readonly handler: (\n input: TInput,\n ctx: SubscriptionCtx,\n ) => AsyncGenerator<TOutput | TrackedEnvelope<TOutput>, void, void>;\n}\n\n/**\n * Minimal structural Zod type used to avoid hard peer-dep import.\n * Mirrors the surface used by other SDK modules (e.g., `define-tool.ts`).\n *\n * Emitted rather than erased: it appears in the signature of `defineSubscription`, which\n * `@theokit/sdk/subscription` publishes, so a consumer's type-aware lint has to be able to\n * resolve it.\n */\nexport interface ZodLike<T> {\n safeParse(value: unknown): { success: true; data: T } | { success: false; error: unknown };\n parse(value: unknown): T;\n}\n","/**\n * `Theokit.subscribe` client (G8 public API) — `@theokit/sdk`.\n *\n * Per ADR D427 (Theokit.subscribe namespace) + D424 (transport selection)\n * + D423 (lastEventId opaque propagation).\n *\n * Returns an AsyncGenerator that yields server-sent values. Transparent\n * reconnect with exponential backoff. Propagates `lastEventId` from the last\n * received tracked envelope on each reconnect attempt.\n *\n * @public\n */\n\nimport { boundFetch } from \"../internal/runtime-fetch.js\";\nimport { parseSseW3C } from \"./internal/sse-parser.js\";\nimport type { WireFrame } from \"./internal/subscription-runtime.js\";\nimport {\n SubscriptionDisconnectError,\n SubscriptionError,\n type SubscriptionTransport,\n} from \"./types.js\";\n\n/**\n * Options accepted by `Theokit.subscribe(name, input, opts?)`.\n *\n * @public\n */\nexport interface SubscribeOptions {\n /** Base URL of the server (e.g., `\"http://localhost:3000\"`). Required. */\n baseUrl: string;\n /** Preferred transport. Default `\"auto\"` (WS preferred, SSE fallback). */\n transport?: SubscriptionTransport;\n /** Max reconnect attempts (default 10). 0 disables reconnect. */\n maxReconnectAttempts?: number;\n /** Backoff strategy. Default exponential `min(30_000, 1000 * 2^attempt)` ms. */\n retryDelayMs?: (attempt: number) => number;\n /** Caller-supplied abort signal. Cancels the subscription entirely. */\n signal?: AbortSignal;\n /** Additional fetch-style headers (e.g., `Authorization`). */\n headers?: Record<string, string>;\n /**\n * Override the SSE transport's `fetch`. Defaults to `globalThis.fetch`.\n * Lets a consumer supply a proxying agent or instrumented fetch without\n * mutating the runtime global.\n */\n fetch?: typeof globalThis.fetch;\n /**\n * Override the WS transport's `WebSocket` constructor. Defaults to\n * `globalThis.WebSocket`. Lets a consumer polyfill WS on a runtime that\n * lacks it, or supply an instrumented implementation, without mutating\n * the runtime global.\n */\n WebSocket?: typeof WebSocket;\n}\n\nconst defaultRetry = (attempt: number) => Math.min(30_000, 1000 * 2 ** attempt);\n\n/**\n * Subscribe to a typed subscription. Yields values produced by the server\n * handler. On disconnect with reconnect enabled, transparently re-establishes\n * the connection and forwards `lastEventId` from the last received tracked\n * envelope so the server handler can resume.\n *\n * @public\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: subscribe orchestrates reconnect + transport switch + resume, and the interleaving is the contract. THE DEBT IS UNOWNED — this used to claim it was \"tracked in subscription/theokit-subscribe.ts:52 followup\", which is a line in an unrelated JSDoc block in this same file, and grepping the file for followup/todo/fixme/#NNN returns only this comment. The citation was its own only evidence. Saying the debt is unowned is worse news and true; a maintainer who checks the tracking before touching the module's @public entry point now learns that in one grep instead of three.\nexport async function* subscribe<TInput, TOutput>(\n name: string,\n input: TInput,\n opts: SubscribeOptions,\n): AsyncGenerator<TOutput, void, void> {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new SubscriptionError(\"Theokit.subscribe: name must be a non-empty string\", {\n code: \"subscribe_name_invalid\",\n });\n }\n if (opts === null || typeof opts !== \"object\" || typeof opts.baseUrl !== \"string\") {\n throw new SubscriptionError(\"Theokit.subscribe: opts.baseUrl is required\", {\n code: \"subscribe_baseUrl_missing\",\n });\n }\n const transport = opts.transport ?? \"auto\";\n const maxReconnects = opts.maxReconnectAttempts ?? 10;\n const retry = opts.retryDelayMs ?? defaultRetry;\n\n let lastEventId: string | undefined;\n let attempt = 0;\n\n while (true) {\n if (opts.signal?.aborted) return;\n try {\n const inputWithCursor = mergeLastEventId(input, lastEventId);\n const chosen = await selectTransport(transport, name, opts);\n if (chosen === \"ws\") {\n for await (const out of openWs<TOutput>(name, inputWithCursor, opts)) {\n if (out.lastEventId !== undefined) lastEventId = out.lastEventId;\n attempt = 0; // reset backoff on successful frame\n yield out.value;\n }\n } else {\n for await (const out of openSse<TOutput>(name, inputWithCursor, opts)) {\n if (out.lastEventId !== undefined) lastEventId = out.lastEventId;\n attempt = 0;\n yield out.value;\n }\n }\n // Clean end-of-stream — no reconnect.\n return;\n } catch (cause) {\n if (opts.signal?.aborted) return;\n if (maxReconnects === 0 || attempt >= maxReconnects) {\n if (cause instanceof SubscriptionError) throw cause;\n throw new SubscriptionDisconnectError(\n `subscription \"${name}\" disconnected; reconnect exhausted`,\n { cause },\n );\n }\n const delay = retry(attempt);\n attempt++;\n await sleep(delay, opts.signal);\n }\n }\n}\n\ninterface FrameOut<T> {\n readonly value: T;\n readonly lastEventId?: string;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: openSse parses framed SSE stream with abort/error/retry branches — refactor candidate\nasync function* openSse<T>(\n name: string,\n input: unknown,\n opts: SubscribeOptions,\n): AsyncIterable<FrameOut<T>> {\n const url = `${stripTrailingSlash(opts.baseUrl)}/api/subscriptions/${encodeURIComponent(name)}?input=${encodeURIComponent(JSON.stringify(input))}`;\n const fetchFn = boundFetch(opts.fetch);\n const res = await fetchFn(url, {\n method: \"GET\",\n headers: {\n accept: \"text/event-stream\",\n ...(opts.headers ?? {}),\n },\n ...(opts.signal !== undefined ? { signal: opts.signal } : {}),\n });\n if (!res.ok || res.body === null) {\n throw new SubscriptionError(`SSE subscribe failed: HTTP ${res.status} ${res.statusText}`, {\n code: \"sse_http_error\",\n });\n }\n const events = parseSseW3C(streamToAsyncIterable(res.body));\n for await (const ev of events) {\n if (ev.event === \"end\") return;\n if (ev.event === \"error\") {\n throw new SubscriptionError(`SSE server emitted error: ${ev.data ?? \"(no body)\"}`, {\n code: \"sse_server_error\",\n });\n }\n if (ev.event === \"connected\") continue;\n if (ev.data === undefined) continue;\n const parsedValue = safeJsonParse<T>(ev.data);\n if (parsedValue === undefined) continue;\n yield {\n value: parsedValue,\n ...(ev.id !== undefined ? { lastEventId: ev.id } : {}),\n };\n }\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: openWs orchestrates WS lifecycle + envelope decode + cleanup — refactor candidate\nasync function* openWs<T>(\n name: string,\n input: unknown,\n opts: SubscribeOptions,\n): AsyncIterable<FrameOut<T>> {\n const baseUrl = stripTrailingSlash(opts.baseUrl);\n const wsUrl = baseUrl\n .replace(/^http:/, \"ws:\")\n .replace(/^https:/, \"wss:\")\n .concat(\"/api/ws\");\n\n const WS = opts.WebSocket ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;\n if (WS === undefined) {\n throw new SubscriptionError(\n \"Theokit.subscribe(transport='ws'): no global WebSocket available. Use Node >=22 or install 'ws' as a runtime dep + assign to globalThis.WebSocket, or pass opts.WebSocket.\",\n { code: \"ws_global_missing\" },\n );\n }\n const ws = new WS(wsUrl);\n\n // Set up async iterator-like state.\n const incoming: WireFrame[] = [];\n // biome-ignore lint/suspicious/noConfusingVoidType: idiomatic event-callback signature; refactoring to undefined would mask the no-value semantics\n let waiter: ((value: void) => void) | null = null;\n let closed = false;\n let closeError: Error | undefined;\n\n ws.addEventListener(\"message\", (ev: MessageEvent) => {\n const data = typeof ev.data === \"string\" ? ev.data : \"\";\n const frame = safeJsonParse<WireFrame>(data);\n if (frame !== undefined) {\n incoming.push(frame);\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n }\n });\n ws.addEventListener(\"close\", () => {\n closed = true;\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n });\n ws.addEventListener(\"error\", () => {\n closed = true;\n closeError = new Error(\"WebSocket error\");\n if (waiter !== null) {\n waiter();\n waiter = null;\n }\n });\n\n await new Promise<void>((resolve, reject) => {\n ws.addEventListener(\"open\", () => resolve(), { once: true });\n ws.addEventListener(\"error\", () => reject(new Error(\"WS connect failed\")), { once: true });\n });\n\n // Send subscribe request after handshake.\n ws.send(JSON.stringify({ kind: \"subscribe\", name, input }));\n\n if (opts.signal !== undefined) {\n opts.signal.addEventListener(\"abort\", () => ws.close(), { once: true });\n }\n\n try {\n while (true) {\n if (incoming.length === 0) {\n if (closed) {\n if (closeError !== undefined) throw closeError;\n return;\n }\n await new Promise<void>((resolve) => {\n waiter = resolve;\n });\n continue;\n }\n const frame = incoming.shift() as WireFrame;\n if (frame.type === \"end\") return;\n if (frame.type === \"error\") {\n // The server's own code wins. `ws_server_error` is the fallback for a frame that carries\n // none — it used to be the code for EVERY server-side failure, so a caller could not tell an\n // invalid input from a disconnect without reading English out of the message.\n throw new SubscriptionError(\n `WS server emitted error: ${frame.error?.message ?? \"(unknown)\"}`,\n { code: frame.error?.code ?? \"ws_server_error\" },\n );\n }\n const value = frame.data as T;\n yield {\n value,\n ...(frame.id !== undefined ? { lastEventId: frame.id } : {}),\n };\n }\n } finally {\n try {\n ws.close();\n } catch {\n /* ignore */\n }\n }\n}\n\nasync function selectTransport(\n pref: SubscriptionTransport,\n _name: string,\n opts: SubscribeOptions,\n): Promise<\"ws\" | \"sse\"> {\n if (pref === \"ws\") return \"ws\";\n if (pref === \"sse\") return \"sse\";\n // auto — prefer WS if available (injected or global), else SSE.\n const WS = opts.WebSocket ?? (globalThis as { WebSocket?: unknown }).WebSocket;\n if (typeof WS === \"function\") {\n return \"ws\";\n }\n return \"sse\";\n}\n\nfunction mergeLastEventId(input: unknown, lastEventId: string | undefined): unknown {\n if (lastEventId === undefined) return input;\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n // Cannot merge into primitive — return as-is.\n return input;\n }\n return { ...(input as object), lastEventId };\n}\n\nfunction stripTrailingSlash(s: string): string {\n return s.endsWith(\"/\") ? s.slice(0, -1) : s;\n}\n\nfunction safeJsonParse<T>(s: string): T | undefined {\n try {\n return JSON.parse(s) as T;\n } catch {\n return undefined;\n }\n}\n\nasync function* streamToAsyncIterable(\n stream: ReadableStream<Uint8Array>,\n): AsyncIterable<Uint8Array> {\n const reader = stream.getReader();\n let finishedNaturally = false;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n finishedNaturally = true;\n return;\n }\n if (value !== undefined) yield value;\n }\n } finally {\n // B-131: `releaseLock()` alone detaches the reader WITHOUT canceling the stream (WHATWG\n // Streams spec) — the underlying `fetch` response body, and its socket, stays open until\n // something else cancels it or reads it to completion. A consumer that breaks out of the\n // subscription mid-stream (the ordinary shape: `for await ... break`) used to leave that\n // connection dangling. `cancel()` is a no-op once the stream is already closed, so it is safe\n // to call unconditionally on the early-exit path; skip it on natural completion, where the\n // stream is already done and canceling only risks surfacing a spurious rejection.\n if (!finishedNaturally) {\n try {\n await reader.cancel();\n } catch {\n /* best-effort cleanup — the caller's own error (if any) already takes precedence */\n }\n }\n reader.releaseLock();\n }\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error(\"aborted\"));\n return;\n }\n const t = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(new Error(\"aborted\"));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n"]}
@@ -41,8 +41,8 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
41
41
  | `cloud_incompatible_function_resolver` | domain | ConfigurationError | `packages/sdk/src/internal/cloud-agent/cloud-tool-parity.ts:43` +2 |
42
42
  | `cloud_incompatible_mcp_stdio_local` | domain | ConfigurationError | `packages/sdk/src/internal/cloud-agent/cloud-tool-parity.ts:74` |
43
43
  | `cloud_plugin_path_rejected` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugins-manager.ts:159` +1 |
44
- | `cloud_run_http_error` | domain | NetworkError | `packages/sdk/src/internal/cloud-agent/real-cloud-run.ts:155` |
45
- | `cloud_run_unknown_status` | domain | NetworkError | `packages/sdk/src/internal/cloud-agent/real-cloud-run.ts:284` +1 |
44
+ | `cloud_run_http_error` | domain | NetworkError | `packages/sdk/src/internal/cloud-agent/real-cloud-run.ts:156` |
45
+ | `cloud_run_unknown_status` | domain | NetworkError | `packages/sdk/src/internal/cloud-agent/real-cloud-run.ts:285` +1 |
46
46
  | `cloud_runtime_pre_release` | domain | ConfigurationError | `packages/sdk/src/agent.ts:417` +2 |
47
47
  | `cloud_stdio_cwd_rejected` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/validation/validate-agent-options.ts:121` |
48
48
  | `compression_failed` | domain | — | `packages/sdk/src/errors.ts:700` |
@@ -62,9 +62,9 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
62
62
  | `duplicate_tool_name` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/validation/validate-agent-options.ts:201` |
63
63
  | `effective_tools_expected_options` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/validation/effective-tools.ts:102` +1 |
64
64
  | `embedding_dimension_mismatch` | domain | ConfigurationError | `packages/sdk/src/internal/memory/lance-index.ts:146` +1 |
65
- | `embedding_invalid_response` | domain | NetworkError | `packages/sdk/src/internal/memory/adapters/openai-compatible.ts:399` |
66
- | `embedding_missing_api_key` | domain | AuthenticationError | `packages/sdk/src/internal/memory/adapters/openai-compatible.ts:141` |
67
- | `embedding_unknown_model` | domain | ConfigurationError | `packages/sdk/src/internal/memory/adapters/openai-compatible.ts:153` |
65
+ | `embedding_invalid_response` | domain | NetworkError | `packages/sdk/src/internal/memory/adapters/openai-compatible.ts:400` |
66
+ | `embedding_missing_api_key` | domain | AuthenticationError | `packages/sdk/src/internal/memory/adapters/openai-compatible.ts:142` |
67
+ | `embedding_unknown_model` | domain | ConfigurationError | `packages/sdk/src/internal/memory/adapters/openai-compatible.ts:154` |
68
68
  | `eval_already_running` | domain | — | `packages/sdk/src/internal/eval/single-flight.ts:19` |
69
69
  | `eval_threshold_failed` | domain | — | `packages/sdk/src/internal/eval/assert.ts:33` |
70
70
  | `fallback_empty_chain` | domain | NetworkError | `packages/sdk/src/internal/llm/fallback-client.ts:44` |
@@ -79,11 +79,11 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
79
79
  | `handoff_target_required` | domain | ConfigurationError | `packages/sdk-handoff/src/handoff.ts:111` |
80
80
  | `hitl_timeout` | domain | HitlTimeoutError | `packages/sdk/src/internal/runtime/tools/hitl-middleware.ts:42` +1 |
81
81
  | `hook_denied` | domain | ConfigurationError | `packages/sdk/src/internal/local-agent/local-agent.ts:454` |
82
- | `hooks_invalid_command` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/hooks/hooks-source.ts:406` |
82
+ | `hooks_invalid_command` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/hooks/hooks-source.ts:415` |
83
83
  | `hooks_json_invalid` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/hooks/hooks-source.ts:252` +2 |
84
84
  | `hooks_read_error` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/hooks/hooks-source.ts:243` |
85
- | `hooks_unsupported_field` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/hooks/hooks-source.ts:384` |
86
- | `hooks_unsupported_type` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/hooks/hooks-source.ts:400` |
85
+ | `hooks_unsupported_field` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/hooks/hooks-source.ts:393` |
86
+ | `hooks_unsupported_type` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/hooks/hooks-source.ts:409` |
87
87
  | `interactive_unavailable` | domain | InteractiveUnavailableError | `packages/sdk/src/interactive/types.ts:28` +1 |
88
88
  | `INTERNAL_SERVER_ERROR` | domain | — | `packages/sdk/src/server/errors-envelope.ts:100` |
89
89
  | `invalid_argument` | domain | TheokitAgentError | `packages/sdk/src/compaction.ts:79` |
@@ -141,7 +141,7 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
141
141
  | `missing_model` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/validation/validate-agent-options.ts:35` |
142
142
  | `model_unavailable` | domain | buildErrorMetadata | `packages/sdk/src/internal/error-mappers/ollama.ts:75` +1 |
143
143
  | `network` | domain | MemoryAdapterError, buildErrorMetadata | `packages/memory-honcho/src/adapter.ts:258` +5 |
144
- | `network_error` | domain | NetworkError | `packages/sdk/src/internal/http.ts:98` |
144
+ | `network_error` | domain | NetworkError | `packages/sdk/src/internal/http.ts:99` |
145
145
  | `no_api_key` | domain | ConfigurationError | `packages/sdk-tools/src/web-search-brave.ts:50` |
146
146
  | `no_memory_adapter` | domain | ConfigurationError | `packages/sdk/src/internal/local-agent/local-agent-memory-direct.ts:141` +2 |
147
147
  | `no_such_session` | domain | NoSuchSessionError | `packages/sdk/src/interactive/types.ts:41` +1 |
@@ -154,7 +154,7 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
154
154
  | `oauth_state_mismatch` | domain | ConfigurationError | `packages/sdk/src/internal/mcp/oauth.ts:127` |
155
155
  | `oauth_timeout` | domain | ConfigurationError | `packages/sdk/src/internal/mcp/oauth.ts:216` +1 |
156
156
  | `oauth_token_exchange_failed` | domain | ConfigurationError | `packages/sdk/src/internal/mcp/oauth.ts:148` |
157
- | `ollama_image_unsupported` | domain | ConfigurationError | `packages/sdk/src/internal/llm/ollama-native.ts:323` |
157
+ | `ollama_image_unsupported` | domain | ConfigurationError | `packages/sdk/src/internal/llm/ollama-native.ts:324` |
158
158
  | `ollama_model_loading` | domain | NetworkError | `packages/sdk/src/internal/error-mappers/ollama.ts:101` |
159
159
  | `ollama_model_not_pulled` | domain | ConfigurationError | `packages/sdk/src/internal/error-mappers/ollama.ts:84` |
160
160
  | `ollama_unreachable` | domain | ConfigurationError | `packages/sdk/src/internal/error-mappers/ollama.ts:55` +1 |
@@ -193,11 +193,11 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
193
193
  | `sqlite_driver_unavailable` | domain | ConfigurationError | `packages/sdk/src/internal/persistence/sqlite-open.ts:195` |
194
194
  | `sqlite_vec_unavailable` | domain | ConfigurationError | `packages/sdk/src/internal/memory/sqlite-vec-loader.ts:23` +1 |
195
195
  | `squad_process_unsupported` | domain | ConfigurationError | `packages/sdk/src/squad.ts:117` |
196
- | `sse_http_error` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:146` |
197
- | `sse_server_error` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:154` |
196
+ | `sse_http_error` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:147` |
197
+ | `sse_server_error` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:155` |
198
198
  | `ssrf_blocked` | domain | — | `packages/sdk-tools/src/internal/network-guard.ts:23` |
199
199
  | `stream_idle_timeout` | domain | NetworkError | `packages/sdk/src/internal/llm/sse.ts:95` |
200
- | `stream_truncated` | domain | NetworkError | `packages/sdk/src/internal/llm/anthropic.ts:184` +1 |
200
+ | `stream_truncated` | domain | NetworkError | `packages/sdk/src/internal/llm/anthropic.ts:185` +1 |
201
201
  | `subagent_foreign_runtime_field` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/skills/subagents-loader.ts:245` |
202
202
  | `subagent_mcp_unsupported_local` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/skills/subagents-loader.ts:272` |
203
203
  | `subagent_missing_description` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/validation/validate-agent-options.ts:142` |
@@ -207,8 +207,8 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
207
207
  | `subagent_sandbox_not_boolean` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/skills/subagents-loader.ts:312` |
208
208
  | `subagent_unknown_field` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/skills/subagents-loader.ts:249` |
209
209
  | `subagent_unknown_setting_source` | domain | ConfigurationError | `packages/sdk/src/subagents-loader.ts:96` |
210
- | `subscribe_baseUrl_missing` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:77` |
211
- | `subscribe_name_invalid` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:72` |
210
+ | `subscribe_baseUrl_missing` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:78` |
211
+ | `subscribe_name_invalid` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:73` |
212
212
  | `subscription_descriptor_invalid` | domain | SubscriptionError | `packages/sdk/src/subscription/internal/server-integration.ts:172` |
213
213
  | `subscription_disconnected` | domain | — | `packages/sdk/src/subscription/types.ts:147` |
214
214
  | `subscription_duplicate` | domain | SubscriptionError | `packages/sdk/src/subscription/internal/subscription-runtime.ts:101` |
@@ -250,7 +250,7 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
250
250
  | `workflow_snapshot_not_found` | domain | — | `packages/sdk/src/workflow-errors.ts:159` |
251
251
  | `workflow_state_invalid` | domain | — | `packages/sdk/src/workflow-errors.ts:82` |
252
252
  | `workflow_tool_failed` | domain | WorkflowToolError | `packages/sdk/src/workflow-as-tool.ts:40` +2 |
253
- | `ws_global_missing` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:183` |
253
+ | `ws_global_missing` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:184` |
254
254
  | `ws_peer_missing` | domain | SubscriptionError | `packages/sdk/src/subscription/internal/ws-adapter-node.ts:48` |
255
255
  | `ws_transport_mismatch` | domain | SubscriptionError | `packages/sdk/src/subscription/internal/server-integration.ts:351` |
256
256
  | `zod_not_installed` | domain | ConfigurationError | `packages/sdk/src/internal/structured-output-helpers.ts:33` +1 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/sdk",
3
- "version": "5.9.0",
3
+ "version": "5.9.2",
4
4
  "description": "TypeScript SDK for the Theo agent harness — same surface, local or cloud.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/usetheokit/theokit-sdk#readme",
@@ -443,7 +443,7 @@
443
443
  "@theokit/sdk-budget": "0.3.5"
444
444
  },
445
445
  "scripts": {
446
- "build": "tsup && cp src/internal/providers/provider-catalog.json dist/provider-catalog.json && node ../../tools/repair-dts-imports.mjs .",
446
+ "build": "tsup && node ../../tools/repair-dts-imports.mjs .",
447
447
  "test": "vitest run --no-file-parallelism",
448
448
  "test:watch": "vitest",
449
449
  "eval": "vitest run --no-file-parallelism tests/eval/suites",
@@ -1,6 +0,0 @@
1
- export { appendCompactBoundaryRecord, persistTurn, readSessionMessages } from './chunk-2WXHA33T.js';
2
- import './chunk-JOFVLOFY.js';
3
- import './chunk-3JHIFQ4I.js';
4
- import './chunk-CZJ6Q7CW.js';
5
- //# sourceMappingURL=agent-session-store-AFML3AXC.js.map
6
- //# sourceMappingURL=agent-session-store-AFML3AXC.js.map
@@ -1,23 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkYIFFF23U_cjs = require('./chunk-YIFFF23U.cjs');
4
- require('./chunk-GZV6AVRL.cjs');
5
- require('./chunk-JLRLCBJ4.cjs');
6
- require('./chunk-6LHQPOMI.cjs');
7
-
8
-
9
-
10
- Object.defineProperty(exports, "appendCompactBoundaryRecord", {
11
- enumerable: true,
12
- get: function () { return chunkYIFFF23U_cjs.appendCompactBoundaryRecord; }
13
- });
14
- Object.defineProperty(exports, "persistTurn", {
15
- enumerable: true,
16
- get: function () { return chunkYIFFF23U_cjs.persistTurn; }
17
- });
18
- Object.defineProperty(exports, "readSessionMessages", {
19
- enumerable: true,
20
- get: function () { return chunkYIFFF23U_cjs.readSessionMessages; }
21
- });
22
- //# sourceMappingURL=agent-session-store-MTSIY3MH.cjs.map
23
- //# sourceMappingURL=agent-session-store-MTSIY3MH.cjs.map