@theokit/sdk 4.52.1 → 4.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/{agent-U2R2R5JP.cjs → agent-JX5SBYDE.cjs} +13 -12
  3. package/dist/{agent-U2R2R5JP.cjs.map → agent-JX5SBYDE.cjs.map} +1 -1
  4. package/dist/{agent-RDHK6MVT.js → agent-ZAGG6ZBS.js} +12 -11
  5. package/dist/{agent-RDHK6MVT.js.map → agent-ZAGG6ZBS.js.map} +1 -1
  6. package/dist/auth/index.cjs +26 -25
  7. package/dist/auth/index.cjs.map +1 -1
  8. package/dist/auth/index.js +3 -2
  9. package/dist/auth/index.js.map +1 -1
  10. package/dist/chunk-23VZBRDQ.js +147 -0
  11. package/dist/chunk-23VZBRDQ.js.map +1 -0
  12. package/dist/{chunk-CY7MIMI4.cjs → chunk-2QMK627M.cjs} +3 -3
  13. package/dist/{chunk-CY7MIMI4.cjs.map → chunk-2QMK627M.cjs.map} +1 -1
  14. package/dist/{chunk-6GS7JI64.cjs → chunk-2VFZQEDW.cjs} +56 -56
  15. package/dist/{chunk-6GS7JI64.cjs.map → chunk-2VFZQEDW.cjs.map} +1 -1
  16. package/dist/{chunk-M5EK7N6R.js → chunk-2Y5NO2SY.js} +4 -4
  17. package/dist/{chunk-M5EK7N6R.js.map → chunk-2Y5NO2SY.js.map} +1 -1
  18. package/dist/{chunk-V2EJLKGA.js → chunk-2YWWPCGX.js} +4 -3
  19. package/dist/chunk-2YWWPCGX.js.map +1 -0
  20. package/dist/chunk-33L2NVTJ.cjs +177 -0
  21. package/dist/chunk-33L2NVTJ.cjs.map +1 -0
  22. package/dist/{chunk-GNPI5IWZ.js → chunk-3SHW7XKK.js} +3 -3
  23. package/dist/{chunk-GNPI5IWZ.js.map → chunk-3SHW7XKK.js.map} +1 -1
  24. package/dist/{chunk-J4RY5DTI.js → chunk-634YVZLU.js} +3 -3
  25. package/dist/{chunk-J4RY5DTI.js.map → chunk-634YVZLU.js.map} +1 -1
  26. package/dist/{chunk-T6ZCG5AP.cjs → chunk-BC5EUG7R.cjs} +7 -6
  27. package/dist/chunk-BC5EUG7R.cjs.map +1 -0
  28. package/dist/{chunk-WLESQ3ZQ.cjs → chunk-DM6Y5B2G.cjs} +21 -21
  29. package/dist/{chunk-WLESQ3ZQ.cjs.map → chunk-DM6Y5B2G.cjs.map} +1 -1
  30. package/dist/{chunk-NACDF3PK.js → chunk-HTK54K2J.js} +3 -3
  31. package/dist/{chunk-SDJYLCJK.cjs.map → chunk-HTK54K2J.js.map} +1 -1
  32. package/dist/{chunk-42PLABFU.js → chunk-I5OTK2RP.js} +3 -3
  33. package/dist/{chunk-42PLABFU.js.map → chunk-I5OTK2RP.js.map} +1 -1
  34. package/dist/chunk-NUEL6RCZ.cjs +155 -0
  35. package/dist/chunk-NUEL6RCZ.cjs.map +1 -0
  36. package/dist/{chunk-KELIQH7K.js → chunk-NZOR3N4E.js} +11 -11
  37. package/dist/{chunk-KELIQH7K.js.map → chunk-NZOR3N4E.js.map} +1 -1
  38. package/dist/{chunk-ZNEE4WWQ.cjs → chunk-QN5N3ZVT.cjs} +5 -5
  39. package/dist/{chunk-ZNEE4WWQ.cjs.map → chunk-QN5N3ZVT.cjs.map} +1 -1
  40. package/dist/{chunk-OI6RHLGC.cjs → chunk-T5ZWI3MC.cjs} +5 -5
  41. package/dist/{chunk-OI6RHLGC.cjs.map → chunk-T5ZWI3MC.cjs.map} +1 -1
  42. package/dist/{chunk-SDJYLCJK.cjs → chunk-TR4V2LHV.cjs} +3 -3
  43. package/dist/chunk-TR4V2LHV.cjs.map +1 -0
  44. package/dist/chunk-XRI6DXPZ.js +171 -0
  45. package/dist/chunk-XRI6DXPZ.js.map +1 -0
  46. package/dist/{compact-session-FBVWO6B3.cjs → compact-session-6GKIS4SD.cjs} +15 -14
  47. package/dist/{compact-session-FBVWO6B3.cjs.map → compact-session-6GKIS4SD.cjs.map} +1 -1
  48. package/dist/{compact-session-XLXC2CZN.js → compact-session-EJ36VH5I.js} +7 -6
  49. package/dist/{compact-session-XLXC2CZN.js.map → compact-session-EJ36VH5I.js.map} +1 -1
  50. package/dist/cron.cjs +12 -11
  51. package/dist/cron.js +11 -10
  52. package/dist/eval.cjs +15 -14
  53. package/dist/eval.cjs.map +1 -1
  54. package/dist/eval.js +11 -10
  55. package/dist/eval.js.map +1 -1
  56. package/dist/fs-session-store-LIKYT24K.js +10 -0
  57. package/dist/{fs-session-store-2TF3ZWMT.js.map → fs-session-store-LIKYT24K.js.map} +1 -1
  58. package/dist/{fs-session-store-TL4RJTXZ.cjs → fs-session-store-VXXDIBGM.cjs} +5 -5
  59. package/dist/{fs-session-store-TL4RJTXZ.cjs.map → fs-session-store-VXXDIBGM.cjs.map} +1 -1
  60. package/dist/index.cjs +42 -41
  61. package/dist/index.cjs.map +1 -1
  62. package/dist/index.js +13 -12
  63. package/dist/index.js.map +1 -1
  64. package/dist/{inject-session-UBAQ7I3G.cjs → inject-session-67SF65FC.cjs} +4 -4
  65. package/dist/{inject-session-UBAQ7I3G.cjs.map → inject-session-67SF65FC.cjs.map} +1 -1
  66. package/dist/{inject-session-UEH5MAKU.js → inject-session-HO7FYVCX.js} +3 -3
  67. package/dist/{inject-session-UEH5MAKU.js.map → inject-session-HO7FYVCX.js.map} +1 -1
  68. package/dist/internal/mcp/oauth.d.ts +1 -0
  69. package/dist/internal/mcp/token-storage.d.ts +1 -0
  70. package/dist/internal/persistence/index.cjs +6 -6
  71. package/dist/internal/persistence/index.js +1 -1
  72. package/dist/internal/persistence/transcript-ops.d.cts +6 -7
  73. package/dist/internal/persistence/transcript-ops.d.ts +6 -7
  74. package/dist/mcp-auth.cjs +299 -0
  75. package/dist/mcp-auth.cjs.map +1 -0
  76. package/dist/mcp-auth.d.cts +17 -0
  77. package/dist/mcp-auth.d.ts +17 -0
  78. package/dist/mcp-auth.js +292 -0
  79. package/dist/mcp-auth.js.map +1 -0
  80. package/dist/models.cjs +11 -10
  81. package/dist/models.cjs.map +1 -1
  82. package/dist/models.js +3 -2
  83. package/dist/models.js.map +1 -1
  84. package/dist/persistence.cjs +16 -7
  85. package/dist/persistence.cjs.map +1 -1
  86. package/dist/persistence.js +11 -2
  87. package/dist/persistence.js.map +1 -1
  88. package/package.json +11 -1
  89. package/dist/chunk-BKRTYDVN.js +0 -312
  90. package/dist/chunk-BKRTYDVN.js.map +0 -1
  91. package/dist/chunk-NACDF3PK.js.map +0 -1
  92. package/dist/chunk-T6ZCG5AP.cjs.map +0 -1
  93. package/dist/chunk-V2EJLKGA.js.map +0 -1
  94. package/dist/chunk-XK54DTRF.cjs +0 -325
  95. package/dist/chunk-XK54DTRF.cjs.map +0 -1
  96. package/dist/fs-session-store-2TF3ZWMT.js +0 -10
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/persistence/fs-session-store.ts"],"names":[],"mappings":";;;;;;AA0DA,IAAM,YAAA,uBAAmB,GAAA,EAAyD;AAElF,eAAe,cAAc,IAAA,EAA2C;AACtE,EAAA,MAAM,QAAA,GAAW,YAAA,CAAa,GAAA,CAAI,IAAI,CAAA;AACtC,EAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,IAAA,QAAA,CAAS,IAAA,EAAA;AACT,IAAA,OAAO,YAAY,IAAI,CAAA;AAAA,EACzB;AACA,EAAA,MAAM,KAAA,GAAQ,MAAM,oBAAA,CAAqB,IAAI,CAAA;AAC7C,EAAA,YAAA,CAAa,IAAI,IAAA,EAAM,EAAE,KAAA,EAAO,IAAA,EAAM,GAAG,CAAA;AACzC,EAAA,OAAO,YAAY,IAAI,CAAA;AACzB;AAGA,SAAS,YAAY,IAAA,EAAkC;AACrD,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,WAAA,EAAa,IAAA;AAAA;AAAA;AAAA;AAAA,IAIb,OAAO,MAAY;AACjB,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,Y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essionStore} seam. It reads and append-writes the native Claude-shaped\n * `.jsonl` transcript at `<baseDir>/projects/<encoded-cwd>/<agentId>.jsonl` — the\n * exact on-disk format SE40 introduced (the file the Claude Code CLI can\n * `--continue`). Omitting `local.sessionStore` resolves to this store, so the\n * default persistence path is byte-identical to SE40 behavior.\n *\n * `readRecords` is `readTranscript(transcriptPath(...))` (a missing session →\n * `[]`, not an error — a fresh agent has no history). `appendRecords` is a TRUE\n * append: it reads the prior records, concatenates the new-turn delta, and\n * rewrites the whole line set atomically under the SE40 cross-process file lock\n * (`writeTranscript` never shrinks — the native format is an append-only\n * `parentUuid` DAG). The parent dir is created BEFORE acquiring the lock because\n * the lock's companion `<path>.lock` file needs an existing parent dir (the SE40\n * `mkdir(dirname)`-before-lock fix).\n *\n * @internal\n */\n\nimport { mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport { withFileLock } from \"./file-lock.js\";\nimport { appendJsonl } from \"./jsonl.js\";\nimport { readTranscript, type SessionRecord, transcriptPath } from \"./session-transcript.js\";\nimport { acquireSessionWriter, type SessionWriterLease } from \"./session-writer.js\";\n\n/** Options identifying the on-disk transcript location for the FS default store. */\nexport interface FsSessionStoreOptions {\n /** Transcript base dir (`~/.theokit` default, `~/.claude` for CLI interop) — already `~`-expanded. */\n baseDir: string;\n /** The workspace cwd whose encoded form is the transcript project dir. */\n cwd: string;\n}\n\n/**\n * The default `SessionStore` — reads/append-writes the native `.jsonl` transcript.\n *\n * @internal\n */\n/**\n * Reference-counted leases, shared per path.\n *\n * `acquireSessionWriter` is STRICT on purpose: two concurrent acquisitions of the same path, and\n * exactly one wins — \"a lease that let both through would be decorative\" (the M81 test says exactly\n * that, and it is right). That is the primitive's contract, and it does not change.\n *\n * But within ONE process it is normal to have more than one store over the same session: the golden\n * compaction tests and the concurrent-send tests do exactly that, and they record real runtime\n * behavior. Applying the raw primitive there would turn a legitimate pattern into a\n * `SessionBusyError`.\n *\n * The reconciliation belongs here, in the primitive's consumer: the process takes ONE lease per path\n * and counts how many stores use it. The last to release actually frees it. Cross-process stays\n * strict — which is the problem M81 states (\"`exec resume --last` can write into the TUI's live\n * session\").\n */\nconst sharedLeases = new Map<string, { lease: SessionWriterLease; refs: number }>();\n\nasync function acquireShared(path: string): Promise<SessionWriterLease> {\n const existing = sharedLeases.get(path);\n if (existing !== undefined) {\n existing.refs++;\n return createProxy(path);\n }\n const lease = await acquireSessionWriter(path);\n sharedLeases.set(path, { lease, refs: 1 });\n return createProxy(path);\n}\n\n/** A handle that decrements the count; the last to release frees the real lease. */\nfunction createProxy(path: string): SessionWriterLease {\n let released = false;\n return {\n sessionPath: path,\n // The proxy forwards the renewal to the ONE real lease this path shares. Renewing through any\n // holder is correct and is the point: the record must say \"someone in this process is still\n // writing\", and the refcount already guarantees they are all the same owner.\n renew: (): void => {\n if (released) return;\n sharedLeases.get(path)?.lease.renew();\n },\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n const entry = sharedLeases.get(path);\n if (entry === undefined) return;\n entry.refs--;\n if (entry.refs > 0) return;\n sharedLeases.delete(path);\n await entry.lease.release();\n },\n };\n}\n\nexport class FsSessionStore implements SessionStore {\n readonly #baseDir: string;\n readonly #cwd: string;\n /** One lease per `agentId` — a store serves more than one session over the process lifetime. */\n readonly #leases = new Map<string, SessionWriterLease>();\n\n constructor(options: FsSessionStoreOptions) {\n this.#baseDir = options.baseDir;\n this.#cwd = options.cwd;\n }\n\n async readRecords(agentId: string): Promise<SessionRecord[]> {\n return readTranscript(transcriptPath(this.#baseDir, this.#cwd, agentId));\n }\n\n async appendRecords(agentId: string, records: readonly SessionRecord[]): Promise<void> {\n // Empty delta → nothing to persist (avoids an unnecessary lock + rewrite).\n if (records.length === 0) return;\n const path = transcriptPath(this.#baseDir, this.#cwd, agentId);\n // mkdir BEFORE the lock: withFileLock's companion `<path>.lock` needs the parent dir.\n await mkdir(dirname(path), { recursive: true });\n\n await withFileLock(path, async () => {\n // M93 — appends the DELTA instead of rewriting the whole file.\n //\n // Before: `readTranscript` + `writeTranscript` of everything, per turn. O(n) of I/O **and** of\n // parsing on every turn, O(n^2) per session — the consumer note in\n // `agents/lib/session/backtrack.ts` records 1.4 MB / 3000 lines over 200 turns.\n //\n // Correct because the format **is already append-only**: the `parentUuid` DAG does not depend\n // on line order, and every record carries its own parent. `appendJsonl` **already existed in\n // the package** and had a single caller (`eval/runner.ts`) — the primitive was there, it was\n // the store that ignored it (rung 4).\n //\n // `withFileLock` stays — but the earlier claim that \"it is what serializes two concurrent\n // `appendRecords`\" was too strong, and M93's adversarial review measured it: removing it fails\n // no test. The reason is the paragraph above — the `parentUuid` DAG does not depend on line\n // order, so two interleaved batches reconstruct identically. The work the lock was doing\n // (protecting a read-modify-write) disappeared along with the rewrite.\n //\n // What it still covers is the TOCTOU window in `needsLineBreakBefore` (read the last byte,\n // then write): without it, two processes can both conclude \"a \\n is missing\" and produce a\n // blank line — which the reader discards, i.e. benign. It stays as a **declared, not\n // mechanized** defense (the discipline in `error-handling.md` § 4: enumerate the residue\n // rather than let a missing test pass for coverage).\n //\n // `writeTranscript` still exists for **compaction**, the one operation that legitimately\n // rewrites the file.\n for (const record of records) appendJsonl(path, record);\n });\n }\n\n /**\n * Takes the session's writer lease. Throws `SessionBusyError` when another process holds it.\n *\n * **Explicit, and NOT inside `appendRecords`** — M95's adversarial review measured why that\n * matters: the `SessionStore` contract states that \"an `appendRecords` rejection is logged to\n * stderr, NOT thrown to the caller (best-effort write)\". Acquiring there made the\n * `SessionBusyError` get **swallowed**, and the result was worse than the original problem:\n * instead of two writers interleaving lines, the loser **lost the turn silently** — nothing on\n * disk, a stderr warning invisible under the TUI, and no way for the caller to react.\n *\n * At init the error reaches someone who can act: `exec` forks to a new id, which is exactly what\n * the error message itself prescribes. It is the difference between failing where a decision is\n * possible and failing where only loss is.\n */\n async acquire(agentId: string): Promise<void> {\n if (this.#leases.has(agentId)) return;\n const path = transcriptPath(this.#baseDir, this.#cwd, agentId);\n await mkdir(dirname(path), { recursive: true });\n this.#leases.set(agentId, await acquireShared(path));\n }\n\n /**\n * Releases ONE agent's lease.\n *\n * It exists because `dispose()` releases **every** lease the store holds, and a store injected by\n * the consumer may serve several agents: an init that fails for agent B must not free agent A's\n * lease, which is still live and writing.\n */\n async release(agentId: string): Promise<void> {\n const lease = this.#leases.get(agentId);\n if (lease === undefined) return;\n this.#leases.delete(agentId);\n await lease.release();\n }\n\n /**\n * Releases every lease this store holds.\n *\n * Without it the `.writer.lock` outlives the process and the next open would have to wait out the\n * heartbeat window — recoverable, but 30 s of waiting after a CLEAN shutdown would be an avoidable\n * defect. Idempotent: calling it twice is not an error.\n */\n async dispose(): Promise<void> {\n const leases = [...this.#leases.values()];\n this.#leases.clear();\n for (const lease of leases) await lease.release();\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/persistence/fs-session-store.ts"],"names":[],"mappings":";;;;;;AA0DA,IAAM,YAAA,uBAAmB,GAAA,EAAyD;AAElF,eAAe,cAAc,IAAA,EAA2C;AACtE,EAAA,MAAM,QAAA,GAAW,YAAA,CAAa,GAAA,CAAI,IAAI,CAAA;AACtC,EAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,IAAA,QAAA,CAAS,IAAA,EAAA;AACT,IAAA,OAAO,YAAY,IAAI,CAAA;AAAA,EACzB;AACA,EAAA,MAAM,KAAA,GAAQ,MAAM,oBAAA,CAAqB,IAAI,CAAA;AAC7C,EAAA,YAAA,CAAa,IAAI,IAAA,EAAM,EAAE,KAAA,EAAO,IAAA,EAAM,GAAG,CAAA;AACzC,EAAA,OAAO,YAAY,IAAI,CAAA;AACzB;AAGA,SAAS,YAAY,IAAA,EAAkC;AACrD,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,WAAA,EAAa,IAAA;AAAA;AAAA;AAAA;AAAA,IAIb,OAAO,MAAY;AACjB,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,YAAA,CAAa,GAAA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AAY,IAAA,EAAM,MAAM,CAAA;AAAA,IACxD,CAAC,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBA,MAAM,QAAQ,OAAA,EAAgC;AAC5C,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,OAAO,CAAA,EAAG;AAC/B,IAAA,MAAM,OAAO,cAAA,CAAe,IAAA,CAAK,QAAA,EAAU,IAAA,CAAK,MAAM,OAAO,CAAA;AAC7D,IAAA,MAAM,MAAM,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC9C,IAAA,IAAA,CAAK,QAAQ,GAAA,CAAI,OAAA,EAAS,MAAM,aAAA,CAAc,IAAI,CAAC,CAAA;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,QAAQ,OAAA,EAAgC;AAC5C,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,OAAO,CAAA;AACtC,IAAA,IAAI,UAAU,MAAA,EAAW;AACzB,IAAA,IAAA,CAAK,OAAA,CAAQ,OAAO,OAAO,CAAA;AAC3B,IAAA,MAAM,MAAM,OAAA,EAAQ;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,OAAA,GAAyB;AAC7B,IAAA,MAAM,SAAS,CAAC,GAAG,IAAA,CAAK,OAAA,CAAQ,QAAQ,CAAA;AACxC,IAAA,IAAA,CAAK,QAAQ,KAAA,EAAM;AACnB,IAAA,KAAA,MAAW,KAAA,IAAS,MAAA,EAAQ,MAAM,KAAA,CAAM,OAAA,EAAQ;AAAA,EAClD;AACF","file":"chunk-634YVZLU.js","sourcesContent":["/**\n * SE41 — `FsSessionStore`, the DEFAULT reference implementation of the pluggable\n * {@link SessionStore} seam. It reads and append-writes the native Claude-shaped\n * `.jsonl` transcript at `<baseDir>/projects/<encoded-cwd>/<agentId>.jsonl` — the\n * exact on-disk format SE40 introduced (the file the Claude Code CLI can\n * `--continue`). Omitting `local.sessionStore` resolves to this store, so the\n * default persistence path is byte-identical to SE40 behavior.\n *\n * `readRecords` is `readTranscript(transcriptPath(...))` (a missing session →\n * `[]`, not an error — a fresh agent has no history). `appendRecords` is a TRUE\n * append: it reads the prior records, concatenates the new-turn delta, and\n * rewrites the whole line set atomically under the SE40 cross-process file lock\n * (`writeTranscript` never shrinks — the native format is an append-only\n * `parentUuid` DAG). The parent dir is created BEFORE acquiring the lock because\n * the lock's companion `<path>.lock` file needs an existing parent dir (the SE40\n * `mkdir(dirname)`-before-lock fix).\n *\n * @internal\n */\n\nimport { mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport { withFileLock } from \"./file-lock.js\";\nimport { appendJsonl } from \"./jsonl.js\";\nimport { readTranscript, type SessionRecord, transcriptPath } from \"./session-transcript.js\";\nimport { acquireSessionWriter, type SessionWriterLease } from \"./session-writer.js\";\n\n/** Options identifying the on-disk transcript location for the FS default store. */\nexport interface FsSessionStoreOptions {\n /** Transcript base dir (`~/.theokit` default, `~/.claude` for CLI interop) — already `~`-expanded. */\n baseDir: string;\n /** The workspace cwd whose encoded form is the transcript project dir. */\n cwd: string;\n}\n\n/**\n * The default `SessionStore` — reads/append-writes the native `.jsonl` transcript.\n *\n * @internal\n */\n/**\n * Reference-counted leases, shared per path.\n *\n * `acquireSessionWriter` is STRICT on purpose: two concurrent acquisitions of the same path, and\n * exactly one wins — \"a lease that let both through would be decorative\" (the M81 test says exactly\n * that, and it is right). That is the primitive's contract, and it does not change.\n *\n * But within ONE process it is normal to have more than one store over the same session: the golden\n * compaction tests and the concurrent-send tests do exactly that, and they record real runtime\n * behavior. Applying the raw primitive there would turn a legitimate pattern into a\n * `SessionBusyError`.\n *\n * The reconciliation belongs here, in the primitive's consumer: the process takes ONE lease per path\n * and counts how many stores use it. The last to release actually frees it. Cross-process stays\n * strict — which is the problem M81 states (\"`exec resume --last` can write into the TUI's live\n * session\").\n */\nconst sharedLeases = new Map<string, { lease: SessionWriterLease; refs: number }>();\n\nasync function acquireShared(path: string): Promise<SessionWriterLease> {\n const existing = sharedLeases.get(path);\n if (existing !== undefined) {\n existing.refs++;\n return createProxy(path);\n }\n const lease = await acquireSessionWriter(path);\n sharedLeases.set(path, { lease, refs: 1 });\n return createProxy(path);\n}\n\n/** A handle that decrements the count; the last to release frees the real lease. */\nfunction createProxy(path: string): SessionWriterLease {\n let released = false;\n return {\n sessionPath: path,\n // The proxy forwards the renewal to the ONE real lease this path shares. Renewing through any\n // holder is correct and is the point: the record must say \"someone in this process is still\n // writing\", and the refcount already guarantees they are all the same owner.\n renew: (): void => {\n if (released) return;\n sharedLeases.get(path)?.lease.renew();\n },\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n const entry = sharedLeases.get(path);\n if (entry === undefined) return;\n entry.refs--;\n if (entry.refs > 0) return;\n sharedLeases.delete(path);\n await entry.lease.release();\n },\n };\n}\n\nexport class FsSessionStore implements SessionStore {\n readonly #baseDir: string;\n readonly #cwd: string;\n /** One lease per `agentId` — a store serves more than one session over the process lifetime. */\n readonly #leases = new Map<string, SessionWriterLease>();\n\n constructor(options: FsSessionStoreOptions) {\n this.#baseDir = options.baseDir;\n this.#cwd = options.cwd;\n }\n\n async readRecords(agentId: string): Promise<SessionRecord[]> {\n return readTranscript(transcriptPath(this.#baseDir, this.#cwd, agentId));\n }\n\n async appendRecords(agentId: string, records: readonly SessionRecord[]): Promise<void> {\n // Empty delta → nothing to persist (avoids an unnecessary lock + rewrite).\n if (records.length === 0) return;\n const path = transcriptPath(this.#baseDir, this.#cwd, agentId);\n // mkdir BEFORE the lock: withFileLock's companion `<path>.lock` needs the parent dir.\n await mkdir(dirname(path), { recursive: true });\n\n await withFileLock(path, async () => {\n // M93 — appends the DELTA instead of rewriting the whole file.\n //\n // Before: `readTranscript` + `writeTranscript` of everything, per turn. O(n) of I/O **and** of\n // parsing on every turn, O(n^2) per session — the consumer note in\n // `agents/lib/session/backtrack.ts` records 1.4 MB / 3000 lines over 200 turns.\n //\n // Correct because the format **is already append-only**: the `parentUuid` DAG does not depend\n // on line order, and every record carries its own parent. `appendJsonl` **already existed in\n // the package** and had a single caller (`eval/runner.ts`) — the primitive was there, it was\n // the store that ignored it (rung 4).\n //\n // `withFileLock` stays — but the earlier claim that \"it is what serializes two concurrent\n // `appendRecords`\" was too strong, and M93's adversarial review measured it: removing it fails\n // no test. The reason is the paragraph above — the `parentUuid` DAG does not depend on line\n // order, so two interleaved batches reconstruct identically. The work the lock was doing\n // (protecting a read-modify-write) disappeared along with the rewrite.\n //\n // What it still covers is the TOCTOU window in `needsLineBreakBefore` (read the last byte,\n // then write): without it, two processes can both conclude \"a \\n is missing\" and produce a\n // blank line — which the reader discards, i.e. benign. It stays as a **declared, not\n // mechanized** defense (the discipline in `error-handling.md` § 4: enumerate the residue\n // rather than let a missing test pass for coverage).\n //\n // `writeTranscript` still exists for **compaction**, the one operation that legitimately\n // rewrites the file.\n for (const record of records) appendJsonl(path, record);\n });\n }\n\n /**\n * Takes the session's writer lease. Throws `SessionBusyError` when another process holds it.\n *\n * **Explicit, and NOT inside `appendRecords`** — M95's adversarial review measured why that\n * matters: the `SessionStore` contract states that \"an `appendRecords` rejection is logged to\n * stderr, NOT thrown to the caller (best-effort write)\". Acquiring there made the\n * `SessionBusyError` get **swallowed**, and the result was worse than the original problem:\n * instead of two writers interleaving lines, the loser **lost the turn silently** — nothing on\n * disk, a stderr warning invisible under the TUI, and no way for the caller to react.\n *\n * At init the error reaches someone who can act: `exec` forks to a new id, which is exactly what\n * the error message itself prescribes. It is the difference between failing where a decision is\n * possible and failing where only loss is.\n */\n async acquire(agentId: string): Promise<void> {\n if (this.#leases.has(agentId)) return;\n const path = transcriptPath(this.#baseDir, this.#cwd, agentId);\n await mkdir(dirname(path), { recursive: true });\n this.#leases.set(agentId, await acquireShared(path));\n }\n\n /**\n * Releases ONE agent's lease.\n *\n * It exists because `dispose()` releases **every** lease the store holds, and a store injected by\n * the consumer may serve several agents: an init that fails for agent B must not free agent A's\n * lease, which is still live and writing.\n */\n async release(agentId: string): Promise<void> {\n const lease = this.#leases.get(agentId);\n if (lease === undefined) return;\n this.#leases.delete(agentId);\n await lease.release();\n }\n\n /**\n * Releases every lease this store holds.\n *\n * Without it the `.writer.lock` outlives the process and the next open would have to wait out the\n * heartbeat window — recoverable, but 30 s of waiting after a CLEAN shutdown would be an avoidable\n * defect. Idempotent: calling it twice is not an error.\n */\n async dispose(): Promise<void> {\n const leases = [...this.#leases.values()];\n this.#leases.clear();\n for (const lease of leases) await lease.release();\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkXK54DTRF_cjs = require('./chunk-XK54DTRF.cjs');
3
+ var chunk33L2NVTJ_cjs = require('./chunk-33L2NVTJ.cjs');
4
+ var chunkNUEL6RCZ_cjs = require('./chunk-NUEL6RCZ.cjs');
4
5
  var chunkSXSPMRSV_cjs = require('./chunk-SXSPMRSV.cjs');
5
6
  var fs = require('fs');
6
7
  var path = require('path');
@@ -80,7 +81,7 @@ var catalogModelSchema = zod.z.object({
80
81
  }).loose();
81
82
 
82
83
  // src/internal/providers/catalog-loader.ts
83
- var __dirname_resolved = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-T6ZCG5AP.cjs', document.baseURI).href))));
84
+ var __dirname_resolved = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-BC5EUG7R.cjs', document.baseURI).href))));
84
85
  var modelInfoIndex = globalSingleton(
85
86
  "theokit-sdk.providers.model-info-index",
86
87
  () => /* @__PURE__ */ new Map()
@@ -396,7 +397,7 @@ var OPENAI_OAUTH_CONFIG = {
396
397
  function codexFetch() {
397
398
  return (async (input, init) => {
398
399
  const env = process.env;
399
- const resolved = await chunkXK54DTRF_cjs.resolveCredential({
400
+ const resolved = await chunk33L2NVTJ_cjs.resolveCredential({
400
401
  provider: "openai",
401
402
  store: DEFAULT_STORE,
402
403
  oauth: OPENAI_OAUTH_CONFIG,
@@ -407,7 +408,7 @@ function codexFetch() {
407
408
  'openai-chatgpt: no ChatGPT credential found \u2014 run the OpenAI device login (e.g. "/login openai") first.'
408
409
  );
409
410
  }
410
- const accountId = chunkXK54DTRF_cjs.readStoredOAuth(DEFAULT_STORE, env)?.account_id;
411
+ const accountId = chunkNUEL6RCZ_cjs.readStoredOAuth(DEFAULT_STORE, env)?.account_id;
411
412
  const headers = new Headers(init?.headers);
412
413
  headers.set("authorization", `Bearer ${resolved.apiKey}`);
413
414
  if (accountId !== void 0) headers.set("ChatGPT-Account-Id", accountId);
@@ -565,5 +566,5 @@ exports.resolveBedrockBaseUrl = resolveBedrockBaseUrl;
565
566
  exports.resolveVertexBaseUrl = resolveVertexBaseUrl;
566
567
  exports.stripBedrockPrefix = stripBedrockPrefix;
567
568
  exports.stripVertexPrefix = stripVertexPrefix;
568
- //# sourceMappingURL=chunk-T6ZCG5AP.cjs.map
569
- //# sourceMappingURL=chunk-T6ZCG5AP.cjs.map
569
+ //# sourceMappingURL=chunk-BC5EUG7R.cjs.map
570
+ //# sourceMappingURL=chunk-BC5EUG7R.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/global-singleton.ts","../src/internal/providers/registry.ts","../src/internal/providers/catalog-schema.ts","../src/internal/providers/catalog-loader.ts","../src/internal/providers/builtin/anthropic.ts","../src/internal/providers/builtin/bedrock.ts","../src/internal/providers/builtin/openai-compatible.ts","../src/internal/providers/builtin/cerebras.ts","../src/internal/providers/builtin/cohere.ts","../src/internal/providers/builtin/deepinfra.ts","../src/internal/providers/builtin/gemini.ts","../src/internal/providers/builtin/google.ts","../src/internal/providers/builtin/groq.ts","../src/internal/providers/builtin/llamacpp.ts","../src/internal/providers/builtin/lmstudio.ts","../src/internal/providers/builtin/mistral.ts","../src/internal/providers/builtin/ollama.ts","../src/internal/providers/builtin/openai.ts","../src/internal/providers/builtin/openai-chatgpt.ts","../src/internal/providers/builtin/openrouter.ts","../src/internal/providers/builtin/perplexity.ts","../src/internal/providers/builtin/together.ts","../src/internal/providers/builtin/vertex.ts","../src/internal/providers/builtin/xai.ts","../src/internal/providers/builtin/index.ts"],"names":["diag","z","dirname","fileURLToPath","join","readFileSync","homedir","resolveCredential","readStoredOAuth"],"mappings":";;;;;;;;;;;;;AAYO,SAAS,eAAA,CAAmB,KAAa,MAAA,EAAoB;AAClE,EAAA,MAAM,CAAA,GAAI,UAAA;AACV,EAAA,MAAM,GAAA,GAAM,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA;AAC1B,EAAA,IAAI,EAAE,GAAG,CAAA,KAAM,QAAW,CAAA,CAAE,GAAG,IAAI,MAAA,EAAO;AAC1C,EAAA,OAAO,EAAE,GAAG,CAAA;AACd;;;ACIA,IAAM,QAAA,GAAW,eAAA;AAAA,EACf,gCAAA;AAAA,EACA,0BAAU,GAAA;AACZ,CAAA;AACA,IAAM,UAAU,eAAA,CAAgB,+BAAA,EAAiC,sBAAM,IAAI,KAAqB,CAAA;AAEzF,SAAS,iBAAiB,OAAA,EAAgC;AAC/D,EAAA,IAAI,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,IAAI,CAAA,EAAG;AAC9B,IAAAA,sBAAA,CAAK,CAAA,wBAAA,EAA2B,QAAQ,IAAI,CAAA;AAAA,CAAgC,CAAA;AAAA,EAC9E;AACA,EAAA,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AAClC,EAAA,KAAA,MA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EAAA,gBAAA,CAAiB,MAAM,CAAA;AAEvB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,OAAO,CAAA;AACxB,EAAA,gBAAA,CAAiB,IAAI,CAAA;AACrB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,SAAS,CAAA;AAC1B,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AACzB,EAAA,gBAAA,CAAiB,GAAG,CAAA;AACpB,EAAA,gBAAA,CAAiB,UAAU,CAAA;AAC3B,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AAEzB,EAAA,wBAAA,EAAyB;AAC3B","file":"chunk-BC5EUG7R.cjs","sourcesContent":["/**\n * One singleton per realm, keyed by `Symbol.for`.\n *\n * It exists because a package can be loaded more than once in the same process (two copies in\n * `node_modules`, ESM and CJS side by side, a monorepo with distinct versions) — and then a module-level\n * `const x = new Map()` produces TWO caches that cannot see each other. `Symbol.for` uses the global\n * symbol registry, which belongs to the realm and not the module, so every copy converges on one instance.\n *\n * It was copied verbatim into `providers/discovery.ts` and `providers/catalog-loader.ts`. That is\n * duplicated KNOWLEDGE, not a coincidence of shape: the two copies have to agree on the\n * mechanism, and one fixed without the other produces exactly the bug the function exists to avoid.\n */\nexport function globalSingleton<T>(key: string, create: () => T): T {\n const g = globalThis as unknown as Record<symbol, T>;\n const sym = Symbol.for(key);\n if (g[sym] === undefined) g[sym] = create();\n return g[sym];\n}\n","/**\n * Provider registry (T3.2, ADR D107).\n *\n * `registerProvider` is idempotent and surface-warning: re-registering\n * a `name` logs to stderr (D107 last-writer-wins with WARN). Alias\n * collisions also warn (EC-5).\n *\n * @internal\n */\n\nimport { diag } from \"../diagnostics.js\";\nimport { globalSingleton } from \"../global-singleton.js\";\nimport type { ProviderProfile } from \"./types.js\";\n\n/**\n * M44 B1 fix — the registry state lives on `globalThis` keyed by `Symbol.for`, so EVERY bundle copy of this\n * module (tsup bundles each entry separately with `splitting: false` — `dist/index.js` and `dist/models.js`\n * each embed their own copy) shares the SAME maps. Without this, `@theokit/sdk/models`'s\n * `refreshModelCatalog` saw an eternally-empty registry and its patches were invisible to the core bundle's\n * capability/pricing lookups (state duplication made load-bearing by M44).\n */\nconst REGISTRY = globalSingleton(\n \"theokit-sdk.providers.registry\",\n () => new Map<string, ProviderProfile>(),\n);\nconst ALIASES = globalSingleton(\"theokit-sdk.providers.aliases\", () => new Map<string, string>());\n\nexport function registerProvider(profile: ProviderProfile): void {\n if (REGISTRY.has(profile.name)) {\n diag(`[theokit-sdk] Provider \"${profile.name}\" overridden by user plugin.\\n`);\n }\n REGISTRY.set(profile.name, profile);\n for (const alias of profile.aliases ?? []) {\n // EC-5: surface alias collision so operators notice mis-routing.\n const previous = ALIASES.get(alias);\n if (previous !== undefined && previous !== profile.name) {\n diag(`[theokit-sdk] Alias \"${alias}\" collision: was \"${previous}\", now \"${profile.name}\".\\n`);\n }\n ALIASES.set(alias, profile.name);\n }\n}\n\nexport function getProviderProfile(name: string): ProviderProfile | undefined {\n const canonical = ALIASES.get(name) ?? name;\n return REGISTRY.get(canonical);\n}\n\nexport function listProviders(): ProviderProfile[] {\n return Array.from(REGISTRY.values());\n}\n\n/** Test-only reset. @internal */\nexport function _resetProvidersForTests(): void {\n REGISTRY.clear();\n ALIASES.clear();\n}\n","import { z } from \"zod\";\n\n/**\n * M44 — the per-model catalog sub-schema. Field names mirror models.dev VERBATIM (snake_case) so\n * `scripts/refresh-catalog.mjs` regenerates the vendored data mechanically from `api.json` with zero\n * renaming (ADR D1; OpenCode keeps the raw shape on disk and maps at load — `core/src/models-dev.ts`).\n * TOLERANT by design: every field optional, unknown keys ignored — models.dev adds fields over time and\n * additive drift must never break the loader (Blueprint §6.4).\n *\n * theokit extensions beyond models.dev: `structured_output` / `cache_control` (both already exist on the\n * SDK's `ModelCapabilities`; models.dev has no such flags).\n *\n * @internal\n */\n\nexport const MODALITIES = [\"text\", \"audio\", \"image\", \"video\", \"pdf\"] as const;\nexport type Modality = (typeof MODALITIES)[number];\n\nconst costSchema = z\n .object({\n /** USD per 1M tokens (models.dev convention). */\n input: z.number().nonnegative(),\n output: z.number().nonnegative(),\n cache_read: z.number().nonnegative().optional(),\n cache_write: z.number().nonnegative().optional(),\n })\n .loose();\n\nconst limitSchema = z\n .object({\n context: z.number().positive(),\n input: z.number().positive().optional(),\n output: z.number().positive().optional(),\n })\n .loose();\n\nconst modalitiesSchema = z\n .object({\n input: z.array(z.enum(MODALITIES)).optional(),\n output: z.array(z.enum(MODALITIES)).optional(),\n })\n .loose();\n\nexport const catalogModelSchema = z\n .object({\n name: z.string().optional(),\n release_date: z.string().optional(),\n attachment: z.boolean().optional(),\n reasoning: z.boolean().optional(),\n temperature: z.boolean().optional(),\n tool_call: z.boolean().optional(),\n /** theokit extension — maps to ModelCapabilities.supportsStructuredOutput. */\n structured_output: z.boolean().optional(),\n /** theokit extension — maps to ModelCapabilities.supportsCacheControl. */\n cache_control: z.boolean().optional(),\n cost: costSchema.optional(),\n limit: limitSchema.optional(),\n modalities: modalitiesSchema.optional(),\n status: z.enum([\"alpha\", \"beta\", \"deprecated\"]).optional(),\n })\n .loose();\n\nexport type CatalogModel = z.infer<typeof catalogModelSchema>;\nexport type CatalogModelCost = z.infer<typeof costSchema>;\n","/**\n * Dynamic provider catalog loader (T10.1, ADR D447).\n *\n * Loads provider metadata from `provider-catalog.json` at runtime.\n * Malformed entries are skipped with WARN (EC-1) — never crash.\n *\n * @internal\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { diag } from \"../diagnostics.js\";\nimport { globalSingleton } from \"../global-singleton.js\";\nimport { type CatalogModel, catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile, registerProvider } from \"./registry.js\";\nimport type { ApiMode, AuthType, ProviderProfile } from \"./types.js\";\n\nconst __dirname_resolved = dirname(fileURLToPath(import.meta.url));\n\nexport interface ProviderCapabilities {\n supportsToolUse: boolean;\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsStreaming: boolean;\n supportsCacheControl: boolean;\n maxContextTokens?: number;\n maxOutputTokens?: number;\n}\n\nexport interface CatalogEntry {\n id: string;\n displayName: string;\n apiMode: ApiMode;\n authType: AuthType;\n baseUrl: string;\n envVars: string[];\n fallbackModels: string[];\n capabilities: ProviderCapabilities;\n aliases?: string[];\n modelsUrl?: string;\n hostname?: string;\n extraHeaders?: Record<string, string>;\n /**\n * M44 — OPTIONAL per-model data (models.dev shape, snake_case — see `catalog-schema.ts`), keyed by the\n * BARE model id. Additive: entries without it behave byte-identically to before. The loader indexes this\n * into the model-info index (`getCatalogModelInfo`) rather than onto `ProviderProfile` (ADR D2 — the\n * builtins-first registration skip means profile-attached data would never reach builtin providers).\n */\n models?: Record<string, CatalogModel>;\n}\n\n/**\n * M44 — the model-info index: `provider/model` → per-model catalog data (the EXACT-map key convention).\n * Populated by the vendored catalog load AND patched by the optional models-dev source (cache entries win\n * per model). The single lookup surface for capability / cost / limit enrichment.\n */\n// M44 B1 fix — index state on globalThis (Symbol.for) so every bundle copy shares the SAME maps (see the\n// identical pattern + rationale in registry.ts).\nconst modelInfoIndex = globalSingleton(\n \"theokit-sdk.providers.model-info-index\",\n () => new Map<string, CatalogModel>(),\n);\n/** M44 M5 fix — keys patched by the live models-dev source (honest pricing provenance). */\nconst patchedModelKeys = globalSingleton(\n \"theokit-sdk.providers.model-info-patched\",\n () => new Set<string>(),\n);\nconst indexState = globalSingleton(\"theokit-sdk.providers.model-info-loaded\", () => ({\n loaded: false,\n}));\n\n/** Look up per-model catalog data by `provider/model` key. @internal */\nexport function getCatalogModelInfo(key: string): CatalogModel | undefined {\n ensureModelIndexLoaded();\n return modelInfoIndex.get(key);\n}\n\n/** Was this key patched by the LIVE models-dev source (vs the vendored catalog)? @internal */\nexport function isPatchedModelKey(key: string): boolean {\n return patchedModelKeys.has(key);\n}\n\n/**\n * Patch the index with fresher per-model data (the models-dev source). M44 H2 fix — a per-FIELD shallow\n * MERGE, not a wholesale replace: models.dev can never supply the theokit extension fields\n * (`cache_control`, `structured_output` overlays), so a replace would wipe them and silently flip\n * capability answers. Incoming fields win; existing fields survive when the patch omits them.\n * @internal\n */\nexport function patchModelInfo(key: string, model: CatalogModel): void {\n ensureModelIndexLoaded();\n const existing = modelInfoIndex.get(key);\n modelInfoIndex.set(key, existing === undefined ? model : { ...existing, ...model });\n patchedModelKeys.add(key);\n}\n\n/** All indexed `provider/model` keys (for maintenance/tests). @internal */\nexport function listModelInfoKeys(): string[] {\n ensureModelIndexLoaded();\n return [...modelInfoIndex.keys()];\n}\n\nfunction ensureModelIndexLoaded(): void {\n if (indexState.loaded) return;\n indexState.loaded = true;\n // M44 L9 fix — never throw from a capability/pricing lookup: a missing/corrupt vendored catalog degrades\n // to conservative defaults with a WARN (the deleted EXACT map could never throw; keep that property).\n try {\n const catalog = loadProviderCatalog();\n for (const entry of Object.values(catalog)) {\n indexEntryModels(entry);\n }\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: provider catalog unavailable (${(err as Error).message}) — per-model data disabled\\n`,\n );\n }\n}\n\n/**\n * Index an entry's `models` block. Runs for EVERY catalog entry — including those whose PROVIDER\n * registration is skipped builtins-first — so builtin providers still get their per-model data (ADR D2).\n * A malformed model sub-entry drops THAT MODEL with WARN and keeps the provider (EC-1 philosophy extended).\n */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nfunction indexEntryModels(entry: CatalogEntry): void {\n if (entry.models === undefined || typeof entry.models !== \"object\") return;\n for (const [modelId, raw] of Object.entries(entry.models)) {\n const parsed = catalogModelSchema.safeParse(raw);\n if (!parsed.success) {\n diag(\n `[theokit-sdk] WARN: Skipping malformed catalog model \"${entry.id}/${modelId}\": ` +\n `${parsed.error.issues[0]?.message ?? \"invalid\"}\\n`,\n );\n continue;\n }\n // Index under the entry id AND every alias — capability lookups are VENDOR-keyed (e.g.\n // `google/gemini-2.5-pro` while the entry id is `google-gemini` with alias `google`), so alias keys are\n // what make the vendor-keyed convention resolve without a second mapping table.\n modelInfoIndex.set(`${entry.id}/${modelId}`, parsed.data);\n for (const alias of entry.aliases ?? []) {\n const key = `${alias}/${modelId}`;\n if (!modelInfoIndex.has(key)) modelInfoIndex.set(key, parsed.data);\n }\n }\n}\n\n/** Test-only reset for the model-info index. @internal */\nexport function _resetModelInfoIndexForTests(): void {\n modelInfoIndex.clear();\n patchedModelKeys.clear();\n indexState.loaded = false;\n}\n\ninterface LoadOptions {\n _testInjectMalformed?: boolean;\n}\n\nfunction validateEntry(raw: Record<string, unknown>): CatalogEntry | null {\n if (\n typeof raw.id !== \"string\" ||\n typeof raw.displayName !== \"string\" ||\n typeof raw.apiMode !== \"string\" ||\n typeof raw.authType !== \"string\" ||\n typeof raw.baseUrl !== \"string\" ||\n !Array.isArray(raw.envVars) ||\n !Array.isArray(raw.fallbackModels) ||\n raw.capabilities == null ||\n typeof raw.capabilities !== \"object\"\n ) {\n return null;\n }\n return raw as unknown as CatalogEntry;\n}\n\nexport function loadProviderCatalog(opts?: LoadOptions): Record<string, CatalogEntry> {\n const catalogPath = join(__dirname_resolved, \"provider-catalog.json\");\n const rawText = readFileSync(catalogPath, \"utf-8\");\n let entries: Record<string, unknown>[] = JSON.parse(rawText);\n\n if (opts?._testInjectMalformed) {\n entries = [\n ...entries,\n { id: \"malformed-provider\", displayName: \"Bad\" } as Record<string, unknown>,\n ];\n }\n\n const result: Record<string, CatalogEntry> = {};\n for (const raw of entries) {\n const validated = validateEntry(raw as Record<string, unknown>);\n if (validated === null) {\n diag(\n `[theokit-sdk] WARN: Skipping malformed catalog entry: ${JSON.stringify(raw).slice(0, 100)}\\n`,\n );\n continue;\n }\n result[validated.id] = validated;\n }\n return result;\n}\n\nlet _capabilitiesCache: Record<string, ProviderCapabilities> | null = null;\n\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nexport function getCatalogCapabilities(providerId: string): ProviderCapabilities | undefined {\n if (_capabilitiesCache === null) {\n const catalog = loadProviderCatalog();\n _capabilitiesCache = {};\n for (const entry of Object.values(catalog)) {\n _capabilitiesCache[entry.id] = entry.capabilities;\n // M45 review L4 — alias keys too (e.g. entry `google-gemini` alias `google`), consistent with the\n // model-info index's alias-keyed convention.\n for (const alias of entry.aliases ?? []) {\n if (_capabilitiesCache[alias] === undefined) _capabilitiesCache[alias] = entry.capabilities;\n }\n }\n }\n return _capabilitiesCache[providerId];\n}\n\nexport function registerCatalogProviders(opts?: LoadOptions): void {\n const catalog = loadProviderCatalog(opts);\n for (const entry of Object.values(catalog)) {\n // Skip catalog entries that would overwrite first-party builtins.\n // Builtins have richer env-var handling and are registered first.\n // Also skip if any alias collides with an existing provider name.\n if (getProviderProfile(entry.id) !== undefined) continue;\n if (entry.aliases?.some((a) => getProviderProfile(a) !== undefined)) continue;\n\n const profile: ProviderProfile = {\n name: entry.id,\n apiMode: entry.apiMode,\n authType: entry.authType,\n baseUrl: entry.baseUrl,\n envVars: entry.envVars,\n fallbackModels: entry.fallbackModels,\n displayName: entry.displayName,\n aliases: entry.aliases,\n modelsUrl: entry.modelsUrl,\n hostname: entry.hostname,\n extraHeaders: entry.extraHeaders,\n };\n registerProvider(profile);\n }\n}\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const ANTHROPIC: ProviderProfile = {\n name: \"anthropic\",\n apiMode: \"anthropic_messages\",\n envVars: [\"ANTHROPIC_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.anthropic.com\",\n modelsUrl: \"https://api.anthropic.com/v1/models\",\n hostname: \"api.anthropic.com\",\n fallbackModels: [\"claude-opus-4-7\", \"claude-sonnet-4-6\", \"claude-haiku-4-5-20251001\"],\n // M45 — the Anthropic beta-features header (interleaved thinking + fine-grained tool streaming). An\n // Anthropic API constant, adapted verbatim from OpenCode's anthropic plugin (MIT © 2025 opencode). The\n // SANCTIONED behavior delta of M45 (ADR D4) — consumed by the anthropic transport's extraHeaders wiring.\n extraHeaders: {\n \"anthropic-beta\": \"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14\",\n },\n};\n","/**\n * AWS Bedrock profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Bearer-only auth via `AWS_BEARER_TOKEN_BEDROCK` env (GA Sep 2025).\n * Optional `@aws/bedrock-token-generator` peer dep auto-refreshes short-term\n * tokens (D287). Transport via native `fetch`; no `@aws-sdk/*` dependency.\n *\n * Model IDs follow the `bedrock/{aws-id}` convention so the router can\n * infer the provider via prefix routing (D186). The client strips the\n * `bedrock/` prefix before building the URL.\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const BEDROCK: ProviderProfile = {\n name: \"bedrock\",\n apiMode: \"bedrock_anthropic\",\n envVars: [\"AWS_BEARER_TOKEN_BEDROCK\"],\n authType: \"aws_bearer\",\n baseUrl: \"https://bedrock-runtime.us-east-1.amazonaws.com\",\n modelsUrl: undefined,\n hostname: \"bedrock-runtime.amazonaws.com\",\n fallbackModels: [\n \"bedrock/us.anthropic.claude-sonnet-4-5-v1:0\",\n \"bedrock/us.anthropic.claude-opus-4-7-v1:0\",\n \"bedrock/global.anthropic.claude-haiku-4-5-v1:0\",\n ],\n};\n\n/** Strip `\"bedrock/\"` prefix so the raw AWS model id is used in the URL. */\nexport function stripBedrockPrefix(modelId: string): string {\n return modelId.replace(/^bedrock\\//, \"\");\n}\n\n/**\n * Infer AWS region from a Bedrock model id prefix (D290).\n *\n * `global.*` routes via `us-east-1` (AWS default entrypoint for global\n * inference profiles).\n */\nexport function inferRegionFromModelId(modelId: string): string | undefined {\n const id = stripBedrockPrefix(modelId);\n if (id.startsWith(\"global.\")) return \"us-east-1\";\n if (id.startsWith(\"us.\")) return process.env.AWS_REGION ?? \"us-east-1\";\n if (id.startsWith(\"eu.\")) return process.env.AWS_REGION ?? \"eu-west-1\";\n if (id.startsWith(\"apac.\")) return process.env.AWS_REGION ?? \"ap-southeast-1\";\n if (id.startsWith(\"jp.\")) return \"ap-northeast-1\";\n return undefined;\n}\n\n/** Resolve baseUrl from model id; falls back to `AWS_REGION` env or `us-east-1`. */\nexport function resolveBedrockBaseUrl(modelId: string): string {\n const region = inferRegionFromModelId(modelId) ?? process.env.AWS_REGION ?? \"us-east-1\";\n return `https://bedrock-runtime.${region}.amazonaws.com`;\n}\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * M45 — the data-only base for OpenAI-compatible chat_completions providers. OpenCode's\n * `openai-compatible-profile` pattern (MIT © 2025 opencode — `packages/llm/src/providers/`) flattened to\n * theokit's data model: leaves declare name/baseUrl/envVars (+ overrides) in ~10 lines; the router's\n * URL-join rule (version-segment detection + `chatCompletionsPath` escape) derives the endpoint.\n *\n * @internal\n */\nexport function openAiCompatibleProfile(\n p: { name: string; baseUrl: string; envVars: readonly string[] } & Partial<ProviderProfile>,\n): ProviderProfile {\n return {\n apiMode: \"chat_completions\",\n authType: \"api_key\",\n fallbackModels: [],\n ...p,\n };\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cerebras. Integration header adapted from OpenCode's `cerebras.ts` (MIT — value changed to\n * `theokit`, never `opencode`: the header attributes TRAFFIC). Models per models.dev (2026-07 snapshot).\n */\nexport const CEREBRAS = openAiCompatibleProfile({\n name: \"cerebras\",\n baseUrl: \"https://api.cerebras.ai/v1\",\n envVars: [\"CEREBRAS_API_KEY\"],\n fallbackModels: [\"gpt-oss-120b\", \"zai-glm-4.7\"],\n extraHeaders: { \"X-Cerebras-3rd-Party-Integration\": \"theokit\" },\n hostname: \"api.cerebras.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cohere via its OpenAI-compatibility surface (`api.cohere.ai/compatibility/v1` — the native v2 API\n * is NOT chat_completions; the discovery flagged the old catalog baseUrl as doubly wrong). Models per\n * models.dev `cohere` (2026-07 snapshot). SOURCE NOTE (review L2): the compatibility endpoint + `CO_API_KEY`\n * come from Cohere's own docs/python-SDK convention (not vendored in this repo's references) — verify with a\n * live smoke when a key is available.\n */\nexport const COHERE = openAiCompatibleProfile({\n name: \"cohere\",\n baseUrl: \"https://api.cohere.ai/compatibility/v1\",\n envVars: [\"COHERE_API_KEY\", \"CO_API_KEY\"],\n fallbackModels: [\"command-a-03-2025\"],\n hostname: \"api.cohere.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — DeepInfra. OpenAI-compat surface under /v1/openai (models.dev `deepinfra`, OpenCode profile map). */\nexport const DEEPINFRA = openAiCompatibleProfile({\n name: \"deepinfra\",\n baseUrl: \"https://api.deepinfra.com/v1/openai\",\n envVars: [\"DEEPINFRA_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen3-32B\"],\n hostname: \"api.deepinfra.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Gemini via OpenRouter passthrough. Direct Gemini API uses a different\n * dialect (`generateContent`); SDK currently routes through OpenRouter's\n * OpenAI-compatible endpoint so the chat_completions transport works.\n *\n * A future plugin `@theokit-provider-gemini-direct` can override this with\n * `apiMode: \"gemini_generate_content\"` once that transport ships.\n */\nexport const GEMINI: ProviderProfile = {\n name: \"gemini\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENROUTER_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n hostname: \"openrouter.ai\",\n fallbackModels: [\"google/gemini-2.0-flash-001\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Google Gemini via the DIRECT OpenAI-compat endpoint (a Google API key, not OpenRouter). Distinct\n * from the `gemini` builtin (an OpenRouter passthrough) by ADR D3 — two routes, two names. Endpoint + env\n * vars per Google's OpenAI-compatibility docs (mirrored by models.dev `google` + the M44 catalog entry).\n */\nexport const GOOGLE = openAiCompatibleProfile({\n name: \"google\",\n baseUrl: \"https://generativelanguage.googleapis.com/v1beta/openai\",\n envVars: [\"GOOGLE_API_KEY\", \"GEMINI_API_KEY\", \"GOOGLE_GENERATIVE_AI_API_KEY\"],\n fallbackModels: [\"gemini-2.5-pro\", \"gemini-2.5-flash\"],\n hostname: \"generativelanguage.googleapis.com\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Groq. Values per models.dev `groq` (2026-07 snapshot); OpenAI-compat surface under /openai/v1. */\nexport const GROQ = openAiCompatibleProfile({\n name: \"groq\",\n baseUrl: \"https://api.groq.com/openai/v1\",\n envVars: [\"GROQ_API_KEY\"],\n fallbackModels: [\"llama-3.3-70b-versatile\", \"llama-3.1-8b-instant\"],\n hostname: \"api.groq.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * llama.cpp server provider profile (T7.2, ADR D189).\n *\n * llama.cpp ships a HTTP server binary (`./server` since b1500+) that\n * implements the OpenAI-compatible `/v1/chat/completions` endpoint on\n * `http://localhost:8080` by default. Inherits `authType: \"none\"` from\n * D182 — no API key required for local use.\n *\n * llama.cpp idiosyncrasies:\n * - Server loads a single GGUF model at startup via `--model` CLI\n * flag. The `model` field in the chat-completions request is\n * cosmetic — any string works; the response comes from the loaded\n * model regardless. This is documented in\n * `.claude/knowledge-base/reviews/edge-case/ollama-integration-edge-cases-2026-05-21.md`\n * as EC-O.\n * - Tool calling support depends entirely on the underlying model.\n *\n * Override the default URL with `LLAMACPP_HOST`.\n *\n * @internal\n */\nexport const LLAMACPP: ProviderProfile = {\n name: \"llamacpp\",\n aliases: [\"llama-cpp\", \"llama.cpp\"],\n apiMode: \"chat_completions\",\n envVars: [\"LLAMACPP_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:8080\",\n modelsUrl: \"http://localhost:8080/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * LM Studio provider profile (T7.1, ADR D188).\n *\n * LM Studio exposes an OpenAI-compatible `/v1/chat/completions` endpoint\n * on `http://localhost:1234` by default (configurable via the LM Studio\n * UI under \"Local Server\"). Inherits the `authType: \"none\"` primitive\n * from D182 — no API key required for local use.\n *\n * LM Studio idiosyncrasies:\n * - Loads ONE model at a time via the desktop UI. The `model` field in\n * the chat-completions request is informational only — LM Studio\n * serves whatever model is currently loaded.\n * - `/v1/models` returns a single entry pointing to the loaded model.\n * - Tool calling depends on the underlying model.\n *\n * Override the default URL with `LMSTUDIO_HOST` (mirrors `OLLAMA_HOST`).\n *\n * @internal\n */\nexport const LMSTUDIO: ProviderProfile = {\n name: \"lmstudio\",\n aliases: [\"lm-studio\", \"lm_studio\"],\n apiMode: \"chat_completions\",\n envVars: [\"LMSTUDIO_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:1234\",\n modelsUrl: \"http://localhost:1234/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Mistral (La Plateforme). Values per models.dev `mistral` (2026-07 snapshot). */\nexport const MISTRAL = openAiCompatibleProfile({\n name: \"mistral\",\n baseUrl: \"https://api.mistral.ai/v1\",\n envVars: [\"MISTRAL_API_KEY\"],\n fallbackModels: [\"mistral-large-latest\", \"codestral-latest\"],\n hostname: \"api.mistral.ai\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Ollama — local-first LLM runtime (ADR D182).\n *\n * Ships as a builtin so `Agent.create({ model: \"ollama/llama3.2\" })` works\n * with zero configuration when `ollama serve` is running on the default\n * port. `authType: \"none\"` signals the router to skip env-key resolution\n * and use a placeholder credential (Ollama ignores Authorization headers\n * on local installs).\n *\n * Overrides:\n * - `OLLAMA_HOST` — replaces the default `http://localhost:11434` baseUrl\n * (advanced users running Ollama on a remote machine).\n * - `OLLAMA_API_KEY` — replaces the placeholder when Ollama is behind a\n * reverse-proxy with auth or when using Ollama Cloud (paid tier).\n */\nexport const OLLAMA: ProviderProfile = {\n name: \"ollama\",\n apiMode: \"chat_completions\",\n envVars: [\"OLLAMA_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:11434\",\n modelsUrl: \"http://localhost:11434/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"llama3.2\", \"qwen2.5\", \"mistral\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENAI: ProviderProfile = {\n name: \"openai\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.openai.com\",\n modelsUrl: \"https://api.openai.com/v1/models\",\n hostname: \"api.openai.com\",\n fallbackModels: [\"gpt-4o\", \"gpt-4o-mini\"],\n};\n","import { homedir } from \"node:os\";\n\nimport type { CredentialStoreConfig, OAuthProviderConfig } from \"../../auth/auth-types.js\";\nimport { readStoredOAuth } from \"../../auth/credential-store.js\";\nimport { resolveCredential } from \"../../auth/resolve-credential.js\";\nimport type { ProviderProfile } from \"../types.js\";\n\n/**\n * M43 — the ChatGPT \"Codex\" backend as a first-class builtin `ProviderProfile`. Migrated from the\n * agent-builder M40 workaround; the SDK now owns the provider, so a consumer only selects\n * `openai-chatgpt/<model>` and logs in — ZERO provider logic in the consumer.\n *\n * Grounded 100% in OpenCode's provider-auth model (see the codex-provider-in-sdk blueprint):\n * - static profile + a `transform.fetch` that resolves the LIVE credential per HTTP request (fresh Bearer +\n * dynamic `ChatGPT-Account-Id`), so a mid-turn expiry refreshes transparently with NO agent rebuild;\n * - the protocol values (endpoint, models, oauth config, `originator` header) are SDK-owned constants,\n * adapted from OpenCode's `openai.ts` (MIT © 2025 opencode — see NOTICE).\n *\n * @internal\n */\n\n/**\n * The SDK-owned ambient credential store the transform reads. Defaults to `~/.theokit/auth.json`. A consumer\n * points it at its existing store dir via the DEDICATED `THEOKIT_AUTH_HOME` env var (NOT `THEOKIT_HOME` — that\n * is the SDK's whole home directory for personality/credential-pool/profiles; overloading it would redirect\n * the entire runtime). The OpenCode \"ambient credential Service\" analog.\n */\nconst DEFAULT_STORE: CredentialStoreConfig = {\n home: homedir(),\n dirName: \".theokit\",\n fileName: \"auth.json\",\n homeEnvVar: \"THEOKIT_AUTH_HOME\",\n};\n\n/**\n * The OpenAI OAuth config the transform resolves + refreshes against. `provider: \"openai\"` is the STORE\n * provider (what `/login` persists), deliberately distinct from this profile's routing name `openai-chatgpt`\n * — the two-namespace split (integration id vs routed provider) mirrors OpenCode. Endpoints/clientId/scopes\n * adapted from OpenCode `openai.ts`.\n */\nconst OPENAI_OAUTH_CONFIG: OAuthProviderConfig = {\n provider: \"openai\",\n authorizeEndpoint: \"https://auth.openai.com/oauth/authorize\",\n tokenEndpoint: \"https://auth.openai.com/oauth/token\",\n clientId: \"app_EMoamEEZ73f0CkXaXp7hrann\",\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n redirectUri: \"https://auth.openai.com/deviceauth/callback\",\n};\n\n/**\n * Build the per-request fetch: resolve a FRESH (refreshed) Bearer + the LIVE account-id from the ambient\n * store, and inject them as headers. Re-resolves on EVERY call → mid-turn refresh with no rebuild. A\n * `Headers` object is used so `authorization` is set case-insensitively (never doubled). If no credential is\n * logged in, throw a clear error rather than putting the router's `__oauth_lazy_token__` placeholder on the\n * wire (fail-closed — the OpenCode `MissingCredentialError` semantics).\n */\nfunction codexFetch(): typeof fetch {\n return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n const env = process.env as Record<string, string | undefined>;\n const resolved = await resolveCredential({\n provider: \"openai\",\n store: DEFAULT_STORE,\n oauth: OPENAI_OAUTH_CONFIG,\n env,\n });\n if (resolved === undefined) {\n throw new Error(\n 'openai-chatgpt: no ChatGPT credential found — run the OpenAI device login (e.g. \"/login openai\") first.',\n );\n }\n const accountId = readStoredOAuth(DEFAULT_STORE, env)?.account_id;\n const headers = new Headers(init?.headers);\n headers.set(\"authorization\", `Bearer ${resolved.apiKey}`);\n if (accountId !== undefined) headers.set(\"ChatGPT-Account-Id\", accountId);\n return fetch(input, { ...init, headers });\n }) as typeof fetch;\n}\n\nexport const OPENAI_CHATGPT: ProviderProfile = {\n name: \"openai-chatgpt\",\n apiMode: \"responses_api\",\n authType: \"oauth_device_code\",\n baseUrl: \"https://chatgpt.com/backend-api/codex\",\n envVars: [],\n fallbackModels: [\n \"openai-chatgpt/gpt-5.4\",\n \"openai-chatgpt/gpt-5.4-mini\",\n \"openai-chatgpt/gpt-5.5\",\n ],\n // #165 — this shipped as `codex_cli_rs`, which is the OFFICIAL Codex CLI's own value\n // (`codex-rs/login/src/auth/default_client.rs`, `DEFAULT_ORIGINATOR`). Claiming to be a different\n // vendor's client is a false statement of identity, and it diverged from the very prior art this\n // file is adapted from: OpenCode sends `originator: \"opencode\"` — its own name — against this same\n // endpoint, which also shows the route is not restricted to the official client.\n extraHeaders: { originator: \"theokit\" },\n transform: {\n // Only `fetch` (async) can await the credential refresh; `headers` is sync and cannot.\n fetch: () => codexFetch(),\n },\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENROUTER: ProviderProfile = {\n name: \"openrouter\",\n apiMode: \"chat_completions\",\n aliases: [\"or\"],\n // Ordered fallback (EC-10): OPENROUTER_API_KEY preferred, OPENAI_API_KEY as compat.\n envVars: [\"OPENROUTER_API_KEY\", \"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n modelsUrl: \"https://openrouter.ai/api/v1/models\",\n hostname: \"openrouter.ai\",\n // M45 — models refreshed (claude-3-haiku retired upstream).\n fallbackModels: [\"openai/gpt-4o-mini\", \"anthropic/claude-haiku-4-5\"],\n // M45 — OpenRouter app-attribution headers (mechanism from OpenCode's openrouter plugin, MIT; VALUES are\n // theokit's own — copying another app's referer would misattribute traffic).\n extraHeaders: { \"HTTP-Referer\": \"https://usetheo.dev\", \"X-Title\": \"theokit\" },\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Perplexity. Its endpoint is UNVERSIONED (`/chat/completions`) — the explicit `chatCompletionsPath`\n * escape expresses it (the sonar-online model family was retired; models per models.dev `perplexity`).\n */\nexport const PERPLEXITY = openAiCompatibleProfile({\n name: \"perplexity\",\n baseUrl: \"https://api.perplexity.ai\",\n chatCompletionsPath: \"/chat/completions\",\n envVars: [\"PERPLEXITY_API_KEY\"],\n fallbackModels: [\"sonar-pro\", \"sonar\"],\n hostname: \"api.perplexity.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Together AI (models.dev id `togetherai` — kept as an alias). Values per the 2026-07 snapshot. */\nexport const TOGETHER = openAiCompatibleProfile({\n name: \"together\",\n aliases: [\"togetherai\"],\n baseUrl: \"https://api.together.xyz/v1\",\n envVars: [\"TOGETHER_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen2.5-7B-Instruct-Turbo\"],\n hostname: \"api.together.xyz\",\n});\n","/**\n * GCP Vertex AI profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Required peer dep: `google-auth-library` (D288). Resolves access tokens\n * via ADC (env → gcloud → metadata server → WIF).\n *\n * Model IDs follow the convention `vertex/{dialect}/{model}`:\n * - `vertex/google/gemini-2.0-flash-001` → OpenAI-compat endpoint (D291)\n * - `vertex/anthropic/claude-sonnet-4-5@20250929` → :rawPredict (D292)\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const VERTEX: ProviderProfile = {\n name: \"vertex\",\n apiMode: \"anthropic_messages\", // sub-dispatched in selectTransport by profile.name\n envVars: [\"GOOGLE_APPLICATION_CREDENTIALS\"],\n authType: \"gcp_oauth\",\n baseUrl: \"https://us-central1-aiplatform.googleapis.com\",\n modelsUrl: undefined,\n hostname: \"aiplatform.googleapis.com\",\n fallbackModels: [\n \"vertex/anthropic/claude-sonnet-4-5@20250929\",\n \"vertex/google/gemini-2.0-flash-001\",\n ],\n};\n\n/**\n * D293 absorbed: when location === \"global\", use `aiplatform.googleapis.com`\n * (no `global-` prefix) — known bug `streamRawPredict` 404 at\n * `global-aiplatform.googleapis.com` (a peer#10287).\n */\nexport function resolveVertexBaseUrl(opts: {\n projectId: string;\n location: string;\n modelDialect: \"anthropic\" | \"gemini\";\n}): string {\n const host =\n opts.location === \"global\"\n ? \"aiplatform.googleapis.com\"\n : `${opts.location}-aiplatform.googleapis.com`;\n if (opts.modelDialect === \"gemini\") {\n // OpenAI-compat endpoint (D291) — the client appends `/chat/completions`.\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/endpoints/openapi`;\n }\n // Anthropic — base URL up to `/publishers/anthropic` (model id appended by client).\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/publishers/anthropic`;\n}\n\n/** Detect dialect from a `vertex/{dialect}/{model}` id. Default: gemini. */\nexport function inferModelDialect(modelId: string): \"anthropic\" | \"gemini\" {\n if (modelId.includes(\"/anthropic/\")) return \"anthropic\";\n if (modelId.includes(\"/google/\")) return \"gemini\";\n return \"gemini\";\n}\n\n/** Strip the `vertex/{dialect}/` prefix so the raw model id is used in the URL. */\nexport function stripVertexPrefix(modelId: string): string {\n return modelId.replace(/^vertex\\/(anthropic|google)\\//, \"\");\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — xAI (Grok). Values per models.dev `xai` (2026-07 snapshot; grok-2 retired). */\nexport const XAI = openAiCompatibleProfile({\n name: \"xai\",\n aliases: [\"grok\"],\n baseUrl: \"https://api.x.ai/v1\",\n envVars: [\"XAI_API_KEY\"],\n fallbackModels: [\"grok-4.5\", \"grok-4.3\"],\n hostname: \"api.x.ai\",\n});\n","/**\n * Eager registration of builtin providers (T3.3). Side-effect import:\n * importing this module registers the 4 builtins with the registry.\n *\n * Lazy user-plugin discovery is handled by `discovery.ts` (T3.4).\n *\n * @internal\n */\n\nimport { registerCatalogProviders } from \"../catalog-loader.js\";\nimport { registerProvider } from \"../registry.js\";\nimport { ANTHROPIC } from \"./anthropic.js\";\nimport { BEDROCK } from \"./bedrock.js\";\nimport { CEREBRAS } from \"./cerebras.js\";\nimport { COHERE } from \"./cohere.js\";\nimport { DEEPINFRA } from \"./deepinfra.js\";\nimport { GEMINI } from \"./gemini.js\";\nimport { GOOGLE } from \"./google.js\";\nimport { GROQ } from \"./groq.js\";\nimport { LLAMACPP } from \"./llamacpp.js\";\nimport { LMSTUDIO } from \"./lmstudio.js\";\nimport { MISTRAL } from \"./mistral.js\";\nimport { OLLAMA } from \"./ollama.js\";\nimport { OPENAI } from \"./openai.js\";\nimport { OPENAI_CHATGPT } from \"./openai-chatgpt.js\";\nimport { OPENROUTER } from \"./openrouter.js\";\nimport { PERPLEXITY } from \"./perplexity.js\";\nimport { TOGETHER } from \"./together.js\";\nimport { VERTEX } from \"./vertex.js\";\nimport { XAI } from \"./xai.js\";\n\n// M45 review M2 — the guard lives on globalThis like the registry itself (M44 B1): a process importing both\n// bundle copies (`@theokit/sdk` + `@theokit/sdk/models`) must not re-register 19 builtins with bogus\n// \"overridden by user plugin\" WARNs.\nconst _registeredState = ((): { done: boolean } => {\n const g = globalThis as unknown as Record<symbol, { done: boolean }>;\n const sym = Symbol.for(\"theokit-sdk.providers.builtins-registered\");\n if (g[sym] === undefined) g[sym] = { done: false };\n return g[sym];\n})();\n\nexport function registerBuiltins(): void {\n if (_registeredState.done) return;\n _registeredState.done = true;\n // First-party builtins (take priority — registered first)\n registerProvider(ANTHROPIC);\n registerProvider(OPENAI);\n registerProvider(OPENAI_CHATGPT);\n registerProvider(OPENROUTER);\n registerProvider(GEMINI);\n registerProvider(OLLAMA);\n registerProvider(LMSTUDIO);\n registerProvider(LLAMACPP);\n registerProvider(BEDROCK);\n registerProvider(VERTEX);\n // M45 — the data-provider fleet (one file each on the openai-compatible base).\n registerProvider(GOOGLE);\n registerProvider(MISTRAL);\n registerProvider(GROQ);\n registerProvider(COHERE);\n registerProvider(DEEPINFRA);\n registerProvider(TOGETHER);\n registerProvider(XAI);\n registerProvider(PERPLEXITY);\n registerProvider(CEREBRAS);\n // Dynamic catalog — 40+ providers from JSON (T10.1, ADR D447)\n registerCatalogProviders();\n}\n\n/** Test-only reset. @internal */\nexport function _resetBuiltinsRegistered(): void {\n _registeredState.done = false;\n}\n\nexport {\n ANTHROPIC,\n BEDROCK,\n GEMINI,\n LLAMACPP,\n LMSTUDIO,\n OLLAMA,\n OPENAI,\n OPENAI_CHATGPT,\n OPENROUTER,\n VERTEX,\n};\n"]}
@@ -1,13 +1,13 @@
1
1
  'use strict';
2
2
 
3
- var chunk4JBHSLQO_cjs = require('./chunk-4JBHSLQO.cjs');
4
3
  var chunkRAACTJ7C_cjs = require('./chunk-RAACTJ7C.cjs');
4
+ var chunk4JBHSLQO_cjs = require('./chunk-4JBHSLQO.cjs');
5
5
  var chunkE3OCRJU6_cjs = require('./chunk-E3OCRJU6.cjs');
6
6
  var chunk6JSIEDKL_cjs = require('./chunk-6JSIEDKL.cjs');
7
7
  var chunkFRITRLZQ_cjs = require('./chunk-FRITRLZQ.cjs');
8
8
  var chunkECPL5RV6_cjs = require('./chunk-ECPL5RV6.cjs');
9
9
  var chunkAMYY3JHQ_cjs = require('./chunk-AMYY3JHQ.cjs');
10
- var chunkT6ZCG5AP_cjs = require('./chunk-T6ZCG5AP.cjs');
10
+ var chunkBC5EUG7R_cjs = require('./chunk-BC5EUG7R.cjs');
11
11
  var chunk2YGIBOUH_cjs = require('./chunk-2YGIBOUH.cjs');
12
12
  var chunkSXSPMRSV_cjs = require('./chunk-SXSPMRSV.cjs');
13
13
  var fs = require('fs');
@@ -18,7 +18,7 @@ var url = require('url');
18
18
  var module$1 = require('module');
19
19
 
20
20
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
21
- var discoveryState = chunkT6ZCG5AP_cjs.globalSingleton("theokit-sdk.providers.discovered", () => ({
21
+ var discoveryState = chunkBC5EUG7R_cjs.globalSingleton("theokit-sdk.providers.discovered", () => ({
22
22
  done: false
23
23
  }));
24
24
  function pluginsRoot() {
@@ -97,7 +97,7 @@ async function loadOne(dir, entryName) {
97
97
  if (plugin !== null && typeof plugin === "object" && plugin.kind === "model-provider") {
98
98
  const profile = plugin.profile;
99
99
  if (profile !== void 0 && typeof profile === "object") {
100
- chunkT6ZCG5AP_cjs.registerProvider(profile);
100
+ chunkBC5EUG7R_cjs.registerProvider(profile);
101
101
  }
102
102
  }
103
103
  return;
@@ -740,7 +740,7 @@ async function resolveBedrockToken(region) {
740
740
  return cachedToken.value;
741
741
  }
742
742
  try {
743
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-WLESQ3ZQ.cjs', document.baseURI).href)));
743
+ const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-DM6Y5B2G.cjs', document.baseURI).href)));
744
744
  const gen = r("@aws/bedrock-token-generator");
745
745
  if (typeof gen.getToken !== "function") return void 0;
746
746
  const providers = r("@aws-sdk/credential-providers");
@@ -774,10 +774,10 @@ var BedrockAnthropicClient = class {
774
774
  );
775
775
  }
776
776
  async *stream(request, signal) {
777
- const region = chunkT6ZCG5AP_cjs.inferRegionFromModelId(request.model) ?? process.env.AWS_REGION ?? "us-east-1";
777
+ const region = chunkBC5EUG7R_cjs.inferRegionFromModelId(request.model) ?? process.env.AWS_REGION ?? "us-east-1";
778
778
  const token = await this.resolveTokenOrThrow(region);
779
- const bareModel = chunkT6ZCG5AP_cjs.stripBedrockPrefix(request.model);
780
- const baseUrl = this.options.baseUrl ?? chunkT6ZCG5AP_cjs.resolveBedrockBaseUrl(request.model);
779
+ const bareModel = chunkBC5EUG7R_cjs.stripBedrockPrefix(request.model);
780
+ const baseUrl = this.options.baseUrl ?? chunkBC5EUG7R_cjs.resolveBedrockBaseUrl(request.model);
781
781
  const endpoint = `/model/${encodeURIComponent(bareModel)}/invoke`;
782
782
  const url = `${baseUrl}${endpoint}`;
783
783
  const response = await postAnthropicRequest({
@@ -2404,7 +2404,7 @@ async function resolveVertexAccessToken() {
2404
2404
  async function getAuthClientOrThrow() {
2405
2405
  let mod;
2406
2406
  try {
2407
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-WLESQ3ZQ.cjs', document.baseURI).href)));
2407
+ const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-DM6Y5B2G.cjs', document.baseURI).href)));
2408
2408
  mod = r("google-auth-library");
2409
2409
  } catch (err) {
2410
2410
  const isModuleMissing = err instanceof Error && (err.message.includes("Cannot find module") || err.code === "MODULE_NOT_FOUND");
@@ -2465,8 +2465,8 @@ var VertexAnthropicClient = class {
2465
2465
  const projectId = this.resolveProjectOrThrow();
2466
2466
  const location = this.options.location ?? resolveVertexLocation();
2467
2467
  const accessToken = await this.resolveTokenOrThrow();
2468
- const baseUrl = chunkT6ZCG5AP_cjs.resolveVertexBaseUrl({ projectId, location, modelDialect: "anthropic" });
2469
- const bareModel = chunkT6ZCG5AP_cjs.stripVertexPrefix(request.model);
2468
+ const baseUrl = chunkBC5EUG7R_cjs.resolveVertexBaseUrl({ projectId, location, modelDialect: "anthropic" });
2469
+ const bareModel = chunkBC5EUG7R_cjs.stripVertexPrefix(request.model);
2470
2470
  const endpoint = `/models/${encodeURIComponent(bareModel)}:rawPredict`;
2471
2471
  const url = `${baseUrl}${endpoint}`;
2472
2472
  const response = await postAnthropicRequest({
@@ -2515,7 +2515,7 @@ var VertexGeminiClient = class {
2515
2515
  { code: "auth_failed" }
2516
2516
  );
2517
2517
  }
2518
- const baseUrl = chunkT6ZCG5AP_cjs.resolveVertexBaseUrl({ projectId, location, modelDialect: "gemini" });
2518
+ const baseUrl = chunkBC5EUG7R_cjs.resolveVertexBaseUrl({ projectId, location, modelDialect: "gemini" });
2519
2519
  const url = `${baseUrl}/chat/completions`;
2520
2520
  const innerFetch = this.options.fetch ?? fetch;
2521
2521
  const rewriteFetch = (input, init) => {
@@ -2541,7 +2541,7 @@ var VertexRouterClient = class {
2541
2541
  options;
2542
2542
  name = "vertex";
2543
2543
  async *stream(request, signal) {
2544
- const dialect = chunkT6ZCG5AP_cjs.inferModelDialect(request.model);
2544
+ const dialect = chunkBC5EUG7R_cjs.inferModelDialect(request.model);
2545
2545
  if (dialect === "anthropic") {
2546
2546
  const inner2 = new VertexAnthropicClient(this.options);
2547
2547
  return yield* inner2.stream(request, signal);
@@ -2553,7 +2553,7 @@ var VertexRouterClient = class {
2553
2553
 
2554
2554
  // src/internal/llm/router.ts
2555
2555
  function resolveProviderChain(options) {
2556
- chunkT6ZCG5AP_cjs.registerBuiltins();
2556
+ chunkBC5EUG7R_cjs.registerBuiltins();
2557
2557
  return buildChain(options);
2558
2558
  }
2559
2559
  function buildChain(options) {
@@ -2578,7 +2578,7 @@ function buildChain(options) {
2578
2578
  return clients;
2579
2579
  }
2580
2580
  function buildClient(name, routerOptions) {
2581
- const baseProfile = chunkT6ZCG5AP_cjs.getProviderProfile(name);
2581
+ const baseProfile = chunkBC5EUG7R_cjs.getProviderProfile(name);
2582
2582
  if (baseProfile === void 0) return void 0;
2583
2583
  const profile = routerOptions.extractToolCallsFromContent === true && baseProfile.extractToolCallsFromContent !== true ? { ...baseProfile, extractToolCallsFromContent: true } : baseProfile;
2584
2584
  const resilience = routerOptions.onRateLimit !== void 0 ? { onRateLimit: routerOptions.onRateLimit } : {};
@@ -2675,7 +2675,7 @@ function warnUnknownProvidersInApiKeys(apiKeys) {
2675
2675
  if (apiKeys === void 0) return;
2676
2676
  for (const name of Object.keys(apiKeys)) {
2677
2677
  if (warnedProviders.has(name)) continue;
2678
- const profile = chunkT6ZCG5AP_cjs.getProviderProfile(name);
2678
+ const profile = chunkBC5EUG7R_cjs.getProviderProfile(name);
2679
2679
  if (profile === void 0) {
2680
2680
  warnedProviders.add(name);
2681
2681
  chunkSXSPMRSV_cjs.diag(
@@ -2771,7 +2771,7 @@ function selectTransport(profile, apiKey) {
2771
2771
  function inferProviderFromApiKey(apiKey) {
2772
2772
  const provider = chunkFRITRLZQ_cjs.providerFromApiKeyPrefix(apiKey);
2773
2773
  if (provider === void 0) return void 0;
2774
- return chunkT6ZCG5AP_cjs.getProviderProfile(provider) === void 0 ? void 0 : provider;
2774
+ return chunkBC5EUG7R_cjs.getProviderProfile(provider) === void 0 ? void 0 : provider;
2775
2775
  }
2776
2776
  function detectPrimaryProvider() {
2777
2777
  if (process.env.ANTHROPIC_API_KEY !== void 0 && process.env.ANTHROPIC_API_KEY.length > 0) {
@@ -2955,9 +2955,9 @@ function resolveSummarizerRoute(opts) {
2955
2955
  }
2956
2956
  function buildDefaultSummarizer(opts) {
2957
2957
  return async (messages) => {
2958
- chunkT6ZCG5AP_cjs.registerBuiltins();
2958
+ chunkBC5EUG7R_cjs.registerBuiltins();
2959
2959
  const modelPrefix = opts.agentModel.includes("/") ? opts.agentModel.slice(0, opts.agentModel.indexOf("/")) : void 0;
2960
- const prefixProfile = modelPrefix !== void 0 ? chunkT6ZCG5AP_cjs.getProviderProfile(modelPrefix) : void 0;
2960
+ const prefixProfile = modelPrefix !== void 0 ? chunkBC5EUG7R_cjs.getProviderProfile(modelPrefix) : void 0;
2961
2961
  const prefixUsable = prefixProfile !== void 0 && (prefixProfile.authType !== "api_key" || prefixProfile.envVars.some((v) => (process.env[v] ?? "").length > 0));
2962
2962
  const route = resolveSummarizerRoute({
2963
2963
  keyProvider: inferProviderFromApiKey(opts.apiKey),
@@ -3059,5 +3059,5 @@ exports.shouldAutoCompact = shouldAutoCompact;
3059
3059
  exports.shouldUseFixtureMode = shouldUseFixtureMode;
3060
3060
  exports.shouldUseRealLocalRuntime = shouldUseRealLocalRuntime;
3061
3061
  exports.tryFirstEvent = tryFirstEvent;
3062
- //# sourceMappingURL=chunk-WLESQ3ZQ.cjs.map
3063
- //# sourceMappingURL=chunk-WLESQ3ZQ.cjs.map
3062
+ //# sourceMappingURL=chunk-DM6Y5B2G.cjs.map
3063
+ //# sourceMappingURL=chunk-DM6Y5B2G.cjs.map