@theokit/sdk 5.9.2 → 5.11.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 (133) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/dist/{agent-WQ4LLTSY.cjs → agent-5DOR5T3E.cjs} +12 -10
  3. package/dist/{agent-WQ4LLTSY.cjs.map → agent-5DOR5T3E.cjs.map} +1 -1
  4. package/dist/{agent-enXXu447.d.ts → agent-CmKwSyyD.d.ts} +27 -0
  5. package/dist/{agent-GZVZXKME.js → agent-GWKRARAL.js} +11 -9
  6. package/dist/{agent-GZVZXKME.js.map → agent-GWKRARAL.js.map} +1 -1
  7. package/dist/{agent-Dh2YHSLj.d.cts → agent-XMkGzff_.d.cts} +27 -0
  8. package/dist/{chunk-PEIV7LOU.js → chunk-4PHSVR2R.js} +68 -37
  9. package/dist/chunk-4PHSVR2R.js.map +1 -0
  10. package/dist/{chunk-KXKT3HSD.cjs → chunk-5H2GJXGC.cjs} +4 -4
  11. package/dist/{chunk-KXKT3HSD.cjs.map → chunk-5H2GJXGC.cjs.map} +1 -1
  12. package/dist/{chunk-JU76WCW7.cjs → chunk-5OHB5HJF.cjs} +123 -92
  13. package/dist/chunk-5OHB5HJF.cjs.map +1 -0
  14. package/dist/{chunk-EVH3OUMY.js → chunk-74OA5DIM.js} +189 -43
  15. package/dist/chunk-74OA5DIM.js.map +1 -0
  16. package/dist/chunk-7KIN3L2S.js +103 -0
  17. package/dist/chunk-7KIN3L2S.js.map +1 -0
  18. package/dist/{chunk-EXI7EHDN.js → chunk-7Y23B7XX.js} +3 -3
  19. package/dist/{chunk-EXI7EHDN.js.map → chunk-7Y23B7XX.js.map} +1 -1
  20. package/dist/chunk-ASK2OQM5.cjs +84 -0
  21. package/dist/chunk-ASK2OQM5.cjs.map +1 -0
  22. package/dist/{chunk-QY3CIMUV.cjs → chunk-BZKF7TXX.cjs} +192 -44
  23. package/dist/chunk-BZKF7TXX.cjs.map +1 -0
  24. package/dist/{chunk-ZDF2IJKC.js → chunk-DPY2M74T.js} +3 -3
  25. package/dist/{chunk-ZDF2IJKC.js.map → chunk-DPY2M74T.js.map} +1 -1
  26. package/dist/{chunk-X7Z2FEI7.cjs → chunk-FYEHYQ7T.cjs} +8 -8
  27. package/dist/{chunk-X7Z2FEI7.cjs.map → chunk-FYEHYQ7T.cjs.map} +1 -1
  28. package/dist/{chunk-OZLQ6ZFM.js → chunk-IZDDSLL2.js} +4 -3
  29. package/dist/chunk-IZDDSLL2.js.map +1 -0
  30. package/dist/{chunk-DLUCTZ56.cjs → chunk-L3C6CCBG.cjs} +15 -15
  31. package/dist/{chunk-DLUCTZ56.cjs.map → chunk-L3C6CCBG.cjs.map} +1 -1
  32. package/dist/chunk-LZJXEPEQ.js +58 -0
  33. package/dist/chunk-LZJXEPEQ.js.map +1 -0
  34. package/dist/{chunk-FR6COQXZ.cjs → chunk-N7ZIPW2N.cjs} +3 -3
  35. package/dist/{chunk-FR6COQXZ.cjs.map → chunk-N7ZIPW2N.cjs.map} +1 -1
  36. package/dist/{chunk-RX3CFWQ2.cjs → chunk-NQVWSSX2.cjs} +6 -5
  37. package/dist/chunk-NQVWSSX2.cjs.map +1 -0
  38. package/dist/chunk-NWS2CS3Y.cjs +61 -0
  39. package/dist/chunk-NWS2CS3Y.cjs.map +1 -0
  40. package/dist/chunk-R5YPDAKD.cjs +108 -0
  41. package/dist/chunk-R5YPDAKD.cjs.map +1 -0
  42. package/dist/chunk-RGQICWFU.js +82 -0
  43. package/dist/chunk-RGQICWFU.js.map +1 -0
  44. package/dist/{chunk-N7KYUNFO.js → chunk-W2ZVTEOD.js} +3 -3
  45. package/dist/{chunk-N7KYUNFO.js.map → chunk-W2ZVTEOD.js.map} +1 -1
  46. package/dist/{chunk-47Z6LP3I.js → chunk-X3LOJJMO.js} +88 -28
  47. package/dist/chunk-X3LOJJMO.js.map +1 -0
  48. package/dist/{chunk-M2CCHC66.js → chunk-Z5BAFHPU.js} +3 -3
  49. package/dist/{chunk-M2CCHC66.js.map → chunk-Z5BAFHPU.js.map} +1 -1
  50. package/dist/{chunk-VZ2JZ2EH.cjs → chunk-ZD66GFH5.cjs} +89 -27
  51. package/dist/chunk-ZD66GFH5.cjs.map +1 -0
  52. package/dist/{compact-session-4QHBBGEY.cjs → compact-session-2AETONOS.cjs} +12 -12
  53. package/dist/{compact-session-4QHBBGEY.cjs.map → compact-session-2AETONOS.cjs.map} +1 -1
  54. package/dist/{compact-session-PVAWTKKL.js → compact-session-F2UDGZCN.js} +3 -3
  55. package/dist/{compact-session-PVAWTKKL.js.map → compact-session-F2UDGZCN.js.map} +1 -1
  56. package/dist/{cron-DTuaPMVI.d.ts → cron-BPccQCO8.d.ts} +1 -1
  57. package/dist/{cron-QTgcwcZt.d.cts → cron-Blj6wMYg.d.cts} +1 -1
  58. package/dist/cron.cjs +11 -9
  59. package/dist/cron.d.cts +2 -2
  60. package/dist/cron.d.ts +2 -2
  61. package/dist/cron.js +10 -8
  62. package/dist/eval.cjs +14 -12
  63. package/dist/eval.cjs.map +1 -1
  64. package/dist/eval.js +10 -8
  65. package/dist/eval.js.map +1 -1
  66. package/dist/fs-session-store-3VI4CPTX.js +11 -0
  67. package/dist/{fs-session-store-LCZBM3LT.js.map → fs-session-store-3VI4CPTX.js.map} +1 -1
  68. package/dist/fs-session-store-IQ6PEHYF.cjs +20 -0
  69. package/dist/{fs-session-store-SVEMRE4K.cjs.map → fs-session-store-IQ6PEHYF.cjs.map} +1 -1
  70. package/dist/{index-manager-6B2UF5S3.js → index-manager-JVYIVTZG.js} +5 -4
  71. package/dist/{index-manager-6B2UF5S3.js.map → index-manager-JVYIVTZG.js.map} +1 -1
  72. package/dist/{index-manager-M3FHJCHQ.cjs → index-manager-YGXRFJMZ.cjs} +6 -5
  73. package/dist/{index-manager-M3FHJCHQ.cjs.map → index-manager-YGXRFJMZ.cjs.map} +1 -1
  74. package/dist/index.cjs +62 -145
  75. package/dist/index.cjs.map +1 -1
  76. package/dist/index.d.cts +12 -3
  77. package/dist/index.d.ts +12 -3
  78. package/dist/index.js +27 -115
  79. package/dist/index.js.map +1 -1
  80. package/dist/{inject-session-O24XGRR6.js → inject-session-E5UDFVLI.js} +3 -3
  81. package/dist/{inject-session-O24XGRR6.js.map → inject-session-E5UDFVLI.js.map} +1 -1
  82. package/dist/{inject-session-OMLFL2V3.cjs → inject-session-W4UKACYJ.cjs} +4 -4
  83. package/dist/{inject-session-OMLFL2V3.cjs.map → inject-session-W4UKACYJ.cjs.map} +1 -1
  84. package/dist/internal/budget/normalize-usage.d.ts +81 -0
  85. package/dist/internal/llm/anthropic-shared.d.ts +6 -0
  86. package/dist/internal/llm/openai.d.ts +3 -5
  87. package/dist/internal/llm/openrouter-system.d.ts +1 -0
  88. package/dist/internal/llm/types.d.ts +10 -5
  89. package/dist/internal/memory/dreaming/phases.d.ts +2 -0
  90. package/dist/internal/memory/dreaming/run.d.ts +5 -0
  91. package/dist/internal/memory/sdk-memory-peer-loader.d.ts +2 -0
  92. package/dist/internal/memory/storage/fact-ceiling.d.cts +19 -0
  93. package/dist/internal/memory/storage/fact-ceiling.d.ts +19 -0
  94. package/dist/internal/memory/storage/index.cjs +40 -31
  95. package/dist/internal/memory/storage/index.d.cts +1 -0
  96. package/dist/internal/memory/storage/index.d.ts +1 -0
  97. package/dist/internal/memory/storage/index.js +3 -2
  98. package/dist/internal/memory/storage/markdown-store.d.cts +3 -1
  99. package/dist/internal/memory/storage/markdown-store.d.ts +3 -1
  100. package/dist/internal/memory/types.d.ts +6 -0
  101. package/dist/internal/persistence/index.cjs +7 -6
  102. package/dist/internal/persistence/index.cjs.map +1 -1
  103. package/dist/internal/persistence/index.js +2 -1
  104. package/dist/internal/persistence/index.js.map +1 -1
  105. package/dist/internal/runtime/registry/agent-registry-store.d.ts +2 -0
  106. package/dist/models.cjs +5 -50
  107. package/dist/models.cjs.map +1 -1
  108. package/dist/models.js +3 -51
  109. package/dist/models.js.map +1 -1
  110. package/dist/persistence.cjs +7 -6
  111. package/dist/persistence.cjs.map +1 -1
  112. package/dist/persistence.js +2 -1
  113. package/dist/persistence.js.map +1 -1
  114. package/dist/subagents-loader.d.cts +1 -1
  115. package/dist/subagents-loader.d.ts +1 -1
  116. package/dist/types/agent.d.ts +27 -0
  117. package/docs/error-codes.md +29 -26
  118. package/docs/harness-capability-map.md +6 -1
  119. package/package.json +1 -1
  120. package/dist/chunk-47Z6LP3I.js.map +0 -1
  121. package/dist/chunk-BKMDRBJ7.js +0 -180
  122. package/dist/chunk-BKMDRBJ7.js.map +0 -1
  123. package/dist/chunk-EVH3OUMY.js.map +0 -1
  124. package/dist/chunk-JU76WCW7.cjs.map +0 -1
  125. package/dist/chunk-OF2CLCTH.cjs +0 -186
  126. package/dist/chunk-OF2CLCTH.cjs.map +0 -1
  127. package/dist/chunk-OZLQ6ZFM.js.map +0 -1
  128. package/dist/chunk-PEIV7LOU.js.map +0 -1
  129. package/dist/chunk-QY3CIMUV.cjs.map +0 -1
  130. package/dist/chunk-RX3CFWQ2.cjs.map +0 -1
  131. package/dist/chunk-VZ2JZ2EH.cjs.map +0 -1
  132. package/dist/fs-session-store-LCZBM3LT.js +0 -10
  133. package/dist/fs-session-store-SVEMRE4K.cjs +0 -19
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/internal/persistence/exclusive-create.ts","../../../src/internal/persistence/sqlite-cas.ts"],"names":["open"],"mappings":";;;;;;;;;;;;;;AAwDA,eAAsB,eAAA,CACpB,IAAA,EACA,IAAA,EACA,OAAA,EACkB;AAClB,EAAA,MAAM,IAAA,GAAO,SAAS,IAAA,IAAQ,GAAA;AAC9B,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,MAAMA,aAAA,CAAK,IAAA,EAAM,MAAM,IAAI,CAAA;AAC1C,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,CAAO,UAAU,IAAI,CAAA;AAC3B,MAAA,OAAO,IAAA;AAAA,IACT,CAAA,SAAE;AACA,MAAA,MAAM,OAAO,KAAA,EAAM;AAAA,IACrB;AAAA,EACF,SAAS,GAAA,EAAK;AACZ,IAAA,IAAK,GAAA,CAA8B,SAAS,QAAA,EAAU;AACpD,MAAA,OAAO,KAAA;AAAA,IACT;AACA,IAAA,MAAM,GAAA;AAAA,EACR;AACF;;;ACdO,SAAS,SAAA,CACd,EAAA,EACA,GAAA,EACA,MAAA,EACA,kBAA0B,CAAA,EACjB;AACT,EAAA,MAAM,IAAA,GAAO,EAAA,CAAG,OAAA,CAAQ,GAAG,CAAA;AAC3B,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,GAAA,CAAI,GAAI,MAAoB,CAAA;AAChD,EAAA,OAAO,OAAO,OAAA,KAAY,eAAA;AAC5B","file":"index.cjs","sourcesContent":["/**\n * O_EXCL exclusive file creation (ADR D82).\n *\n * `createExclusive(path, data, { mode })` creates a file in a single\n * syscall (`open(path, \"wx\", mode)`). Returns `true` if created, `false`\n * if it already existed (EEXIST swallowed — caller decides). All other\n * errors propagate.\n *\n * Default mode is 0o600 (owner-only) — EC-2 fix from edge-case review:\n * token files, lockfiles, and PID files MUST NOT default to world-\n * readable 0o644 under typical umask 022. Callers writing non-sensitive\n * files can pass `mode: 0o644` explicitly.\n *\n * NFS not honoring O_EXCL is documented (D61 — same stance as\n * `withFileLock`); the SDK target is ext4/APFS/NTFS.\n *\n * @internal\n */\n\nimport { open } from \"node:fs/promises\";\n\nexport interface CreateExclusiveOptions {\n /** Unix mode for the new file (default 0o600 — owner-only). */\n mode?: number;\n}\n\n/**\n * Create `path` holding `data`, but only if it does not exist yet. Returns `true` when this call\n * created it, `false` when it was already there.\n *\n * The check and the create are one `open(path, \"wx\")` syscall, so of N processes racing to create\n * the same path exactly one gets `true` — no window between testing and writing. The content is\n * written after the create, so the `false` branch tells you the file exists, not that another\n * writer has finished filling it.\n *\n * Only `EEXIST` becomes `false`. Every other error propagates: a missing parent directory is\n * `ENOENT`, an unwritable one `EACCES`. This never creates directories.\n *\n * The file is created with mode 0600 unless `options.mode` says otherwise, and the mode is\n * subject to the process umask. That default is deliberate — the callers are token files,\n * lockfiles and PID files, and 0644 under a typical umask would make them world-readable.\n *\n * **Choosing between this and the locks.** `createExclusive` claims a NAME once and is the right\n * tool for first-writer-wins: seeding a config, electing a single owner, writing a credential\n * exactly once. It cannot guard repeated updates, because a file that already exists always loses.\n * For read-modify-write on a path several writers touch, take a lock instead —\n * {@link withFileLock} across processes, `withCwdMutex` when the writers are all in this one. For\n * an in-place update guarded by a version column in SQLite, `casUpdate` is the equivalent\n * primitive.\n *\n * Atomicity is the filesystem's `O_EXCL`, which NFS does not reliably honor; the SDK targets\n * ext4, APFS and NTFS.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function createExclusive(\n path: string,\n data: string | Uint8Array,\n options?: CreateExclusiveOptions,\n): Promise<boolean> {\n const mode = options?.mode ?? 0o600;\n try {\n const handle = await open(path, \"wx\", mode);\n try {\n await handle.writeFile(data);\n return true;\n } finally {\n await handle.close();\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n return false;\n }\n throw err;\n }\n}\n","/**\n * SQLite optimistic compare-and-swap (ADR D83).\n *\n * `casUpdate(db, sql, params, expectedChanges)` executes a prepared\n * UPDATE and returns true if `result.changes === expectedChanges`.\n * Caller provides the full SQL (including `WHERE version = ?` predicate);\n * helper does NOT generate SQL — DRY at the level of \"wrap the\n * convention\", not \"build queries\".\n *\n * Use case canonical (Hermes `kanban_db.py:1922-1934`):\n *\n * const won = casUpdate(\n * db,\n * \"UPDATE registry SET status = ?, version = version + 1 WHERE id = ? AND version = ?\",\n * [\"running\", \"agent-foo\", 3],\n * );\n * if (!won) { ... re-read and retry ... }\n *\n * Helper does NOT retry — caller responsible for backoff (avoids hidden\n * loops). Helper does NOT cache prepared statements — `better-sqlite3`\n * caches internally; SDK use is one-shot per mutation, not hot loops.\n *\n * NOTE — no internal-visibility tag in this block. `tsconfig.base.json` sets `stripInternal: true`,\n * and TypeScript scans EVERY leading comment range of the declaration that follows, including the\n * import right below this one. The tag that used to sit here deleted that import from the emitted\n * `.d.ts`, leaving the types it binds unresolvable for any consumer running type-aware lint\n * (usetheodev/theokit-sdk#283 records the same trap on a declaration).\n */\n\nimport type Database from \"better-sqlite3\";\n\ntype DatabaseInstance = InstanceType<typeof Database>;\n\n/**\n * Run an UPDATE and report whether it changed exactly the number of rows you expected — the\n * optimistic-concurrency equivalent of taking a lock.\n *\n * `sql` is yours, in full, including the guard that makes it a compare-and-swap: the\n * `WHERE ... AND version = ?` predicate and the `SET version = version + 1` that closes it. This\n * function generates nothing. It prepares the statement, runs it with `params`, and compares\n * `changes` against `expectedChanges` (default 1).\n *\n * `false` means the guard did not match — someone else moved the row first, or the id does not\n * exist. Those two are indistinguishable here; if you need to tell them apart, re-read the row.\n * A `false` return means NOTHING was written, so the caller owns the re-read-and-retry, with\n * whatever backoff it wants. There is no retry loop hidden in here, by design.\n *\n * SQL errors propagate — bad syntax, a closed database, a constraint violation, a busy writer.\n * Only the row-count mismatch is reported as `false`.\n *\n * Runs as a single implicit transaction, so no explicit BEGIN is needed for one statement. Wrap\n * the call yourself when the swap has to commit together with other writes.\n *\n * **Choosing between this and the locks.** `casUpdate` never blocks and never waits: the loser\n * finds out immediately and decides what to do. Prefer it when the contended state is already a\n * row with a version column. When the contended state is a FILE, there is no version column to\n * swap on — use `withFileLock` across processes, or `withCwdMutex` within one. When the goal is\n * to create something exactly once rather than update it, `createExclusive` is the primitive.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function casUpdate(\n db: DatabaseInstance,\n sql: string,\n params: ReadonlyArray<unknown>,\n expectedChanges: number = 1,\n): boolean {\n const stmt = db.prepare(sql);\n const result = stmt.run(...(params as unknown[]));\n return result.changes === expectedChanges;\n}\n"]}
1
+ {"version":3,"sources":["../../../src/internal/persistence/exclusive-create.ts","../../../src/internal/persistence/sqlite-cas.ts"],"names":["open"],"mappings":";;;;;;;;;;;;;;;AAwDA,eAAsB,eAAA,CACpB,IAAA,EACA,IAAA,EACA,OAAA,EACkB;AAClB,EAAA,MAAM,IAAA,GAAO,SAAS,IAAA,IAAQ,GAAA;AAC9B,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,MAAMA,aAAA,CAAK,IAAA,EAAM,MAAM,IAAI,CAAA;AAC1C,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,CAAO,UAAU,IAAI,CAAA;AAC3B,MAAA,OAAO,IAAA;AAAA,IACT,CAAA,SAAE;AACA,MAAA,MAAM,OAAO,KAAA,EAAM;AAAA,IACrB;AAAA,EACF,SAAS,GAAA,EAAK;AACZ,IAAA,IAAK,GAAA,CAA8B,SAAS,QAAA,EAAU;AACpD,MAAA,OAAO,KAAA;AAAA,IACT;AACA,IAAA,MAAM,GAAA;AAAA,EACR;AACF;;;ACdO,SAAS,SAAA,CACd,EAAA,EACA,GAAA,EACA,MAAA,EACA,kBAA0B,CAAA,EACjB;AACT,EAAA,MAAM,IAAA,GAAO,EAAA,CAAG,OAAA,CAAQ,GAAG,CAAA;AAC3B,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,GAAA,CAAI,GAAI,MAAoB,CAAA;AAChD,EAAA,OAAO,OAAO,OAAA,KAAY,eAAA;AAC5B","file":"index.cjs","sourcesContent":["/**\n * O_EXCL exclusive file creation (ADR D82).\n *\n * `createExclusive(path, data, { mode })` creates a file in a single\n * syscall (`open(path, \"wx\", mode)`). Returns `true` if created, `false`\n * if it already existed (EEXIST swallowed — caller decides). All other\n * errors propagate.\n *\n * Default mode is 0o600 (owner-only) — EC-2 fix from edge-case review:\n * token files, lockfiles, and PID files MUST NOT default to world-\n * readable 0o644 under typical umask 022. Callers writing non-sensitive\n * files can pass `mode: 0o644` explicitly.\n *\n * NFS not honoring O_EXCL is documented (D61 — same stance as\n * `withFileLock`); the SDK target is ext4/APFS/NTFS.\n *\n * @internal\n */\n\nimport { open } from \"node:fs/promises\";\n\nexport interface CreateExclusiveOptions {\n /** Unix mode for the new file (default 0o600 — owner-only). */\n mode?: number;\n}\n\n/**\n * Create `path` holding `data`, but only if it does not exist yet. Returns `true` when this call\n * created it, `false` when it was already there.\n *\n * The check and the create are one `open(path, \"wx\")` syscall, so of N processes racing to create\n * the same path exactly one gets `true` — no window between testing and writing. The content is\n * written after the create, so the `false` branch tells you the file exists, not that another\n * writer has finished filling it.\n *\n * Only `EEXIST` becomes `false`. Every other error propagates: a missing parent directory is\n * `ENOENT`, an unwritable one `EACCES`. This never creates directories.\n *\n * The file is created with mode 0600 unless `options.mode` says otherwise, and the mode is\n * subject to the process umask. That default is deliberate — the callers are token files,\n * lockfiles and PID files, and 0644 under a typical umask would make them world-readable.\n *\n * **Choosing between this and the locks.** `createExclusive` claims a NAME once and is the right\n * tool for first-writer-wins: seeding a config, electing a single owner, writing a credential\n * exactly once. It cannot guard repeated updates, because a file that already exists always loses.\n * For read-modify-write on a path several writers touch, take a lock instead —\n * {@link withFileLock} across processes, `withCwdMutex` when the writers are all in this one. For\n * an in-place update guarded by a version column in SQLite, `casUpdate` is the equivalent\n * primitive.\n *\n * Atomicity is the filesystem's `O_EXCL`, which NFS does not reliably honor; the SDK targets\n * ext4, APFS and NTFS.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function createExclusive(\n path: string,\n data: string | Uint8Array,\n options?: CreateExclusiveOptions,\n): Promise<boolean> {\n const mode = options?.mode ?? 0o600;\n try {\n const handle = await open(path, \"wx\", mode);\n try {\n await handle.writeFile(data);\n return true;\n } finally {\n await handle.close();\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n return false;\n }\n throw err;\n }\n}\n","/**\n * SQLite optimistic compare-and-swap (ADR D83).\n *\n * `casUpdate(db, sql, params, expectedChanges)` executes a prepared\n * UPDATE and returns true if `result.changes === expectedChanges`.\n * Caller provides the full SQL (including `WHERE version = ?` predicate);\n * helper does NOT generate SQL — DRY at the level of \"wrap the\n * convention\", not \"build queries\".\n *\n * Use case canonical (Hermes `kanban_db.py:1922-1934`):\n *\n * const won = casUpdate(\n * db,\n * \"UPDATE registry SET status = ?, version = version + 1 WHERE id = ? AND version = ?\",\n * [\"running\", \"agent-foo\", 3],\n * );\n * if (!won) { ... re-read and retry ... }\n *\n * Helper does NOT retry — caller responsible for backoff (avoids hidden\n * loops). Helper does NOT cache prepared statements — `better-sqlite3`\n * caches internally; SDK use is one-shot per mutation, not hot loops.\n *\n * NOTE — no internal-visibility tag in this block. `tsconfig.base.json` sets `stripInternal: true`,\n * and TypeScript scans EVERY leading comment range of the declaration that follows, including the\n * import right below this one. The tag that used to sit here deleted that import from the emitted\n * `.d.ts`, leaving the types it binds unresolvable for any consumer running type-aware lint\n * (usetheodev/theokit-sdk#283 records the same trap on a declaration).\n */\n\nimport type Database from \"better-sqlite3\";\n\ntype DatabaseInstance = InstanceType<typeof Database>;\n\n/**\n * Run an UPDATE and report whether it changed exactly the number of rows you expected — the\n * optimistic-concurrency equivalent of taking a lock.\n *\n * `sql` is yours, in full, including the guard that makes it a compare-and-swap: the\n * `WHERE ... AND version = ?` predicate and the `SET version = version + 1` that closes it. This\n * function generates nothing. It prepares the statement, runs it with `params`, and compares\n * `changes` against `expectedChanges` (default 1).\n *\n * `false` means the guard did not match — someone else moved the row first, or the id does not\n * exist. Those two are indistinguishable here; if you need to tell them apart, re-read the row.\n * A `false` return means NOTHING was written, so the caller owns the re-read-and-retry, with\n * whatever backoff it wants. There is no retry loop hidden in here, by design.\n *\n * SQL errors propagate — bad syntax, a closed database, a constraint violation, a busy writer.\n * Only the row-count mismatch is reported as `false`.\n *\n * Runs as a single implicit transaction, so no explicit BEGIN is needed for one statement. Wrap\n * the call yourself when the swap has to commit together with other writes.\n *\n * **Choosing between this and the locks.** `casUpdate` never blocks and never waits: the loser\n * finds out immediately and decides what to do. Prefer it when the contended state is already a\n * row with a version column. When the contended state is a FILE, there is no version column to\n * swap on — use `withFileLock` across processes, or `withCwdMutex` within one. When the goal is\n * to create something exactly once rather than update it, `createExclusive` is the primitive.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function casUpdate(\n db: DatabaseInstance,\n sql: string,\n params: ReadonlyArray<unknown>,\n expectedChanges: number = 1,\n): boolean {\n const stmt = db.prepare(sql);\n const result = stmt.run(...(params as unknown[]));\n return result.changes === expectedChanges;\n}\n"]}
@@ -2,7 +2,8 @@ export { PersistenceSchema } from '../../chunk-HY66GLM6.js';
2
2
  export { migrateSchema, readVersionedJson, writeVersionedJson } from '../../chunk-SVQIW5RJ.js';
3
3
  export { containsCjk, sanitizeFts5Query } from '../../chunk-WE22OXQA.js';
4
4
  export { applyWalWithFallback, isCorruptionError, openSqliteResilient } from '../../chunk-XZHJYSPB.js';
5
- export { JsonlParseError, appendJsonl, loadJsonl, readJsonlIds, withFileLock } from '../../chunk-BKMDRBJ7.js';
5
+ export { JsonlParseError, appendJsonl, loadJsonl, readJsonlIds } from '../../chunk-7KIN3L2S.js';
6
+ export { withFileLock } from '../../chunk-RGQICWFU.js';
6
7
  export { withCwdMutex } from '../../chunk-Q5EWJPRY.js';
7
8
  export { atomicWriteJson, atomicWriteText, replaceFileAtomic } from '../../chunk-3JHIFQ4I.js';
8
9
  export { displayTheokitHome, getProfilesRoot, getTheokitHome } from '../../chunk-X7EUUHXU.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/internal/persistence/exclusive-create.ts","../../../src/internal/persistence/sqlite-cas.ts"],"names":[],"mappings":";;;;;;;;;;;;AAwDA,eAAsB,eAAA,CACpB,IAAA,EACA,IAAA,EACA,OAAA,EACkB;AAClB,EAAA,MAAM,IAAA,GAAO,SAAS,IAAA,IAAQ,GAAA;AAC9B,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,IAAA,EAAM,MAAM,IAAI,CAAA;AAC1C,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,CAAO,UAAU,IAAI,CAAA;AAC3B,MAAA,OAAO,IAAA;AAAA,IACT,CAAA,SAAE;AACA,MAAA,MAAM,OAAO,KAAA,EAAM;AAAA,IACrB;AAAA,EACF,SAAS,GAAA,EAAK;AACZ,IAAA,IAAK,GAAA,CAA8B,SAAS,QAAA,EAAU;AACpD,MAAA,OAAO,KAAA;AAAA,IACT;AACA,IAAA,MAAM,GAAA;AAAA,EACR;AACF;;;ACdO,SAAS,SAAA,CACd,EAAA,EACA,GAAA,EACA,MAAA,EACA,kBAA0B,CAAA,EACjB;AACT,EAAA,MAAM,IAAA,GAAO,EAAA,CAAG,OAAA,CAAQ,GAAG,CAAA;AAC3B,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,GAAA,CAAI,GAAI,MAAoB,CAAA;AAChD,EAAA,OAAO,OAAO,OAAA,KAAY,eAAA;AAC5B","file":"index.js","sourcesContent":["/**\n * O_EXCL exclusive file creation (ADR D82).\n *\n * `createExclusive(path, data, { mode })` creates a file in a single\n * syscall (`open(path, \"wx\", mode)`). Returns `true` if created, `false`\n * if it already existed (EEXIST swallowed — caller decides). All other\n * errors propagate.\n *\n * Default mode is 0o600 (owner-only) — EC-2 fix from edge-case review:\n * token files, lockfiles, and PID files MUST NOT default to world-\n * readable 0o644 under typical umask 022. Callers writing non-sensitive\n * files can pass `mode: 0o644` explicitly.\n *\n * NFS not honoring O_EXCL is documented (D61 — same stance as\n * `withFileLock`); the SDK target is ext4/APFS/NTFS.\n *\n * @internal\n */\n\nimport { open } from \"node:fs/promises\";\n\nexport interface CreateExclusiveOptions {\n /** Unix mode for the new file (default 0o600 — owner-only). */\n mode?: number;\n}\n\n/**\n * Create `path` holding `data`, but only if it does not exist yet. Returns `true` when this call\n * created it, `false` when it was already there.\n *\n * The check and the create are one `open(path, \"wx\")` syscall, so of N processes racing to create\n * the same path exactly one gets `true` — no window between testing and writing. The content is\n * written after the create, so the `false` branch tells you the file exists, not that another\n * writer has finished filling it.\n *\n * Only `EEXIST` becomes `false`. Every other error propagates: a missing parent directory is\n * `ENOENT`, an unwritable one `EACCES`. This never creates directories.\n *\n * The file is created with mode 0600 unless `options.mode` says otherwise, and the mode is\n * subject to the process umask. That default is deliberate — the callers are token files,\n * lockfiles and PID files, and 0644 under a typical umask would make them world-readable.\n *\n * **Choosing between this and the locks.** `createExclusive` claims a NAME once and is the right\n * tool for first-writer-wins: seeding a config, electing a single owner, writing a credential\n * exactly once. It cannot guard repeated updates, because a file that already exists always loses.\n * For read-modify-write on a path several writers touch, take a lock instead —\n * {@link withFileLock} across processes, `withCwdMutex` when the writers are all in this one. For\n * an in-place update guarded by a version column in SQLite, `casUpdate` is the equivalent\n * primitive.\n *\n * Atomicity is the filesystem's `O_EXCL`, which NFS does not reliably honor; the SDK targets\n * ext4, APFS and NTFS.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function createExclusive(\n path: string,\n data: string | Uint8Array,\n options?: CreateExclusiveOptions,\n): Promise<boolean> {\n const mode = options?.mode ?? 0o600;\n try {\n const handle = await open(path, \"wx\", mode);\n try {\n await handle.writeFile(data);\n return true;\n } finally {\n await handle.close();\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n return false;\n }\n throw err;\n }\n}\n","/**\n * SQLite optimistic compare-and-swap (ADR D83).\n *\n * `casUpdate(db, sql, params, expectedChanges)` executes a prepared\n * UPDATE and returns true if `result.changes === expectedChanges`.\n * Caller provides the full SQL (including `WHERE version = ?` predicate);\n * helper does NOT generate SQL — DRY at the level of \"wrap the\n * convention\", not \"build queries\".\n *\n * Use case canonical (Hermes `kanban_db.py:1922-1934`):\n *\n * const won = casUpdate(\n * db,\n * \"UPDATE registry SET status = ?, version = version + 1 WHERE id = ? AND version = ?\",\n * [\"running\", \"agent-foo\", 3],\n * );\n * if (!won) { ... re-read and retry ... }\n *\n * Helper does NOT retry — caller responsible for backoff (avoids hidden\n * loops). Helper does NOT cache prepared statements — `better-sqlite3`\n * caches internally; SDK use is one-shot per mutation, not hot loops.\n *\n * NOTE — no internal-visibility tag in this block. `tsconfig.base.json` sets `stripInternal: true`,\n * and TypeScript scans EVERY leading comment range of the declaration that follows, including the\n * import right below this one. The tag that used to sit here deleted that import from the emitted\n * `.d.ts`, leaving the types it binds unresolvable for any consumer running type-aware lint\n * (usetheodev/theokit-sdk#283 records the same trap on a declaration).\n */\n\nimport type Database from \"better-sqlite3\";\n\ntype DatabaseInstance = InstanceType<typeof Database>;\n\n/**\n * Run an UPDATE and report whether it changed exactly the number of rows you expected — the\n * optimistic-concurrency equivalent of taking a lock.\n *\n * `sql` is yours, in full, including the guard that makes it a compare-and-swap: the\n * `WHERE ... AND version = ?` predicate and the `SET version = version + 1` that closes it. This\n * function generates nothing. It prepares the statement, runs it with `params`, and compares\n * `changes` against `expectedChanges` (default 1).\n *\n * `false` means the guard did not match — someone else moved the row first, or the id does not\n * exist. Those two are indistinguishable here; if you need to tell them apart, re-read the row.\n * A `false` return means NOTHING was written, so the caller owns the re-read-and-retry, with\n * whatever backoff it wants. There is no retry loop hidden in here, by design.\n *\n * SQL errors propagate — bad syntax, a closed database, a constraint violation, a busy writer.\n * Only the row-count mismatch is reported as `false`.\n *\n * Runs as a single implicit transaction, so no explicit BEGIN is needed for one statement. Wrap\n * the call yourself when the swap has to commit together with other writes.\n *\n * **Choosing between this and the locks.** `casUpdate` never blocks and never waits: the loser\n * finds out immediately and decides what to do. Prefer it when the contended state is already a\n * row with a version column. When the contended state is a FILE, there is no version column to\n * swap on — use `withFileLock` across processes, or `withCwdMutex` within one. When the goal is\n * to create something exactly once rather than update it, `createExclusive` is the primitive.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function casUpdate(\n db: DatabaseInstance,\n sql: string,\n params: ReadonlyArray<unknown>,\n expectedChanges: number = 1,\n): boolean {\n const stmt = db.prepare(sql);\n const result = stmt.run(...(params as unknown[]));\n return result.changes === expectedChanges;\n}\n"]}
1
+ {"version":3,"sources":["../../../src/internal/persistence/exclusive-create.ts","../../../src/internal/persistence/sqlite-cas.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAwDA,eAAsB,eAAA,CACpB,IAAA,EACA,IAAA,EACA,OAAA,EACkB;AAClB,EAAA,MAAM,IAAA,GAAO,SAAS,IAAA,IAAQ,GAAA;AAC9B,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,IAAA,EAAM,MAAM,IAAI,CAAA;AAC1C,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,CAAO,UAAU,IAAI,CAAA;AAC3B,MAAA,OAAO,IAAA;AAAA,IACT,CAAA,SAAE;AACA,MAAA,MAAM,OAAO,KAAA,EAAM;AAAA,IACrB;AAAA,EACF,SAAS,GAAA,EAAK;AACZ,IAAA,IAAK,GAAA,CAA8B,SAAS,QAAA,EAAU;AACpD,MAAA,OAAO,KAAA;AAAA,IACT;AACA,IAAA,MAAM,GAAA;AAAA,EACR;AACF;;;ACdO,SAAS,SAAA,CACd,EAAA,EACA,GAAA,EACA,MAAA,EACA,kBAA0B,CAAA,EACjB;AACT,EAAA,MAAM,IAAA,GAAO,EAAA,CAAG,OAAA,CAAQ,GAAG,CAAA;AAC3B,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,GAAA,CAAI,GAAI,MAAoB,CAAA;AAChD,EAAA,OAAO,OAAO,OAAA,KAAY,eAAA;AAC5B","file":"index.js","sourcesContent":["/**\n * O_EXCL exclusive file creation (ADR D82).\n *\n * `createExclusive(path, data, { mode })` creates a file in a single\n * syscall (`open(path, \"wx\", mode)`). Returns `true` if created, `false`\n * if it already existed (EEXIST swallowed — caller decides). All other\n * errors propagate.\n *\n * Default mode is 0o600 (owner-only) — EC-2 fix from edge-case review:\n * token files, lockfiles, and PID files MUST NOT default to world-\n * readable 0o644 under typical umask 022. Callers writing non-sensitive\n * files can pass `mode: 0o644` explicitly.\n *\n * NFS not honoring O_EXCL is documented (D61 — same stance as\n * `withFileLock`); the SDK target is ext4/APFS/NTFS.\n *\n * @internal\n */\n\nimport { open } from \"node:fs/promises\";\n\nexport interface CreateExclusiveOptions {\n /** Unix mode for the new file (default 0o600 — owner-only). */\n mode?: number;\n}\n\n/**\n * Create `path` holding `data`, but only if it does not exist yet. Returns `true` when this call\n * created it, `false` when it was already there.\n *\n * The check and the create are one `open(path, \"wx\")` syscall, so of N processes racing to create\n * the same path exactly one gets `true` — no window between testing and writing. The content is\n * written after the create, so the `false` branch tells you the file exists, not that another\n * writer has finished filling it.\n *\n * Only `EEXIST` becomes `false`. Every other error propagates: a missing parent directory is\n * `ENOENT`, an unwritable one `EACCES`. This never creates directories.\n *\n * The file is created with mode 0600 unless `options.mode` says otherwise, and the mode is\n * subject to the process umask. That default is deliberate — the callers are token files,\n * lockfiles and PID files, and 0644 under a typical umask would make them world-readable.\n *\n * **Choosing between this and the locks.** `createExclusive` claims a NAME once and is the right\n * tool for first-writer-wins: seeding a config, electing a single owner, writing a credential\n * exactly once. It cannot guard repeated updates, because a file that already exists always loses.\n * For read-modify-write on a path several writers touch, take a lock instead —\n * {@link withFileLock} across processes, `withCwdMutex` when the writers are all in this one. For\n * an in-place update guarded by a version column in SQLite, `casUpdate` is the equivalent\n * primitive.\n *\n * Atomicity is the filesystem's `O_EXCL`, which NFS does not reliably honor; the SDK targets\n * ext4, APFS and NTFS.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function createExclusive(\n path: string,\n data: string | Uint8Array,\n options?: CreateExclusiveOptions,\n): Promise<boolean> {\n const mode = options?.mode ?? 0o600;\n try {\n const handle = await open(path, \"wx\", mode);\n try {\n await handle.writeFile(data);\n return true;\n } finally {\n await handle.close();\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n return false;\n }\n throw err;\n }\n}\n","/**\n * SQLite optimistic compare-and-swap (ADR D83).\n *\n * `casUpdate(db, sql, params, expectedChanges)` executes a prepared\n * UPDATE and returns true if `result.changes === expectedChanges`.\n * Caller provides the full SQL (including `WHERE version = ?` predicate);\n * helper does NOT generate SQL — DRY at the level of \"wrap the\n * convention\", not \"build queries\".\n *\n * Use case canonical (Hermes `kanban_db.py:1922-1934`):\n *\n * const won = casUpdate(\n * db,\n * \"UPDATE registry SET status = ?, version = version + 1 WHERE id = ? AND version = ?\",\n * [\"running\", \"agent-foo\", 3],\n * );\n * if (!won) { ... re-read and retry ... }\n *\n * Helper does NOT retry — caller responsible for backoff (avoids hidden\n * loops). Helper does NOT cache prepared statements — `better-sqlite3`\n * caches internally; SDK use is one-shot per mutation, not hot loops.\n *\n * NOTE — no internal-visibility tag in this block. `tsconfig.base.json` sets `stripInternal: true`,\n * and TypeScript scans EVERY leading comment range of the declaration that follows, including the\n * import right below this one. The tag that used to sit here deleted that import from the emitted\n * `.d.ts`, leaving the types it binds unresolvable for any consumer running type-aware lint\n * (usetheodev/theokit-sdk#283 records the same trap on a declaration).\n */\n\nimport type Database from \"better-sqlite3\";\n\ntype DatabaseInstance = InstanceType<typeof Database>;\n\n/**\n * Run an UPDATE and report whether it changed exactly the number of rows you expected — the\n * optimistic-concurrency equivalent of taking a lock.\n *\n * `sql` is yours, in full, including the guard that makes it a compare-and-swap: the\n * `WHERE ... AND version = ?` predicate and the `SET version = version + 1` that closes it. This\n * function generates nothing. It prepares the statement, runs it with `params`, and compares\n * `changes` against `expectedChanges` (default 1).\n *\n * `false` means the guard did not match — someone else moved the row first, or the id does not\n * exist. Those two are indistinguishable here; if you need to tell them apart, re-read the row.\n * A `false` return means NOTHING was written, so the caller owns the re-read-and-retry, with\n * whatever backoff it wants. There is no retry loop hidden in here, by design.\n *\n * SQL errors propagate — bad syntax, a closed database, a constraint violation, a busy writer.\n * Only the row-count mismatch is reported as `false`.\n *\n * Runs as a single implicit transaction, so no explicit BEGIN is needed for one statement. Wrap\n * the call yourself when the swap has to commit together with other writes.\n *\n * **Choosing between this and the locks.** `casUpdate` never blocks and never waits: the loser\n * finds out immediately and decides what to do. Prefer it when the contended state is already a\n * row with a version column. When the contended state is a FILE, there is no version column to\n * swap on — use `withFileLock` across processes, or `withCwdMutex` within one. When the goal is\n * to create something exactly once rather than update it, `createExclusive` is the primitive.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function casUpdate(\n db: DatabaseInstance,\n sql: string,\n params: ReadonlyArray<unknown>,\n expectedChanges: number = 1,\n): boolean {\n const stmt = db.prepare(sql);\n const result = stmt.run(...(params as unknown[]));\n return result.changes === expectedChanges;\n}\n"]}
@@ -46,6 +46,8 @@ export interface SerializedAgentOptions {
46
46
  };
47
47
  };
48
48
  activeRecall?: Record<string, unknown>;
49
+ maxFacts?: number;
50
+ directory?: string;
49
51
  };
50
52
  skills?: {
51
53
  enabled?: ReadonlyArray<string>;
package/dist/models.cjs CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var chunk72CPLZPC_cjs = require('./chunk-72CPLZPC.cjs');
4
+ var chunkNWS2CS3Y_cjs = require('./chunk-NWS2CS3Y.cjs');
4
5
  var chunk3EE6LVWT_cjs = require('./chunk-3EE6LVWT.cjs');
5
6
  var chunkHU666T3Q_cjs = require('./chunk-HU666T3Q.cjs');
6
7
  require('./chunk-NVXXWAU7.cjs');
@@ -15,55 +16,6 @@ var fs = require('fs');
15
16
  var os = require('os');
16
17
  var path = require('path');
17
18
 
18
- // src/internal/llm/model-capabilities.ts
19
- var CONSERVATIVE_DEFAULTS = {
20
- supportsVision: false,
21
- supportsStructuredOutput: false,
22
- supportsToolUse: false,
23
- supportsCacheControl: false,
24
- maxContextTokens: 4096,
25
- maxOutputTokens: 4096
26
- };
27
- var ROUTING_PREFIXES = ["openrouter/", "vertex/", "bedrock/"];
28
- function capsFromCatalog(m) {
29
- return {
30
- supportsVision: m.modalities?.input?.includes("image") ?? m.attachment ?? false,
31
- supportsStructuredOutput: m.structured_output ?? false,
32
- supportsToolUse: m.tool_call ?? false,
33
- supportsCacheControl: m.cache_control ?? false,
34
- maxContextTokens: m.limit?.context ?? CONSERVATIVE_DEFAULTS.maxContextTokens,
35
- maxOutputTokens: m.limit?.output ?? CONSERVATIVE_DEFAULTS.maxOutputTokens
36
- };
37
- }
38
- function resolveModelCapabilities(modelId) {
39
- const bare = stripVariantSuffix(stripRoutingPrefix(modelId));
40
- const fromIndex = chunkHU666T3Q_cjs.getCatalogModelInfo(bare);
41
- if (fromIndex !== void 0) return capsFromCatalog(fromIndex);
42
- const withVendor = inferVendorPrefix(bare);
43
- if (withVendor !== bare) {
44
- const vendored = chunkHU666T3Q_cjs.getCatalogModelInfo(withVendor);
45
- if (vendored !== void 0) return capsFromCatalog(vendored);
46
- }
47
- return CONSERVATIVE_DEFAULTS;
48
- }
49
- function stripRoutingPrefix(modelId) {
50
- for (const prefix of ROUTING_PREFIXES) {
51
- if (modelId.startsWith(prefix)) return modelId.slice(prefix.length);
52
- }
53
- return modelId;
54
- }
55
- function stripVariantSuffix(modelId) {
56
- const i = modelId.indexOf(":");
57
- return i >= 0 ? modelId.slice(0, i) : modelId;
58
- }
59
- function inferVendorPrefix(bare) {
60
- if (bare.startsWith("claude")) return `anthropic/${bare}`;
61
- if (bare.startsWith("gpt-") || bare.startsWith("o1") || bare.startsWith("o3"))
62
- return `openai/${bare}`;
63
- if (bare.startsWith("gemini")) return `google/${bare}`;
64
- return bare;
65
- }
66
-
67
19
  // src/internal/llm/model-option.ts
68
20
  var ACRONYMS = /* @__PURE__ */ new Set(["gpt", "ai", "hd", "ui", "api", "sdk", "llm", "xl"]);
69
21
  function prettyToken(token) {
@@ -283,6 +235,10 @@ function getModelInfo(modelId) {
283
235
  return chunkHU666T3Q_cjs.getCatalogModelInfo(modelId);
284
236
  }
285
237
 
238
+ Object.defineProperty(exports, "resolveModelCapabilities", {
239
+ enumerable: true,
240
+ get: function () { return chunkNWS2CS3Y_cjs.resolveModelCapabilities; }
241
+ });
286
242
  Object.defineProperty(exports, "parseModelId", {
287
243
  enumerable: true,
288
244
  get: function () { return chunk3EE6LVWT_cjs.parseModelId; }
@@ -290,7 +246,6 @@ Object.defineProperty(exports, "parseModelId", {
290
246
  exports.getModelInfo = getModelInfo;
291
247
  exports.humanizeModelName = humanizeModelName;
292
248
  exports.refreshModelCatalog = refreshModelCatalog;
293
- exports.resolveModelCapabilities = resolveModelCapabilities;
294
249
  exports.toModelOption = toModelOption;
295
250
  //# sourceMappingURL=models.cjs.map
296
251
  //# sourceMappingURL=models.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/llm/model-capabilities.ts","../src/internal/llm/model-option.ts","../src/internal/providers/catalog-source-models-dev.ts"],"names":["getCatalogModelInfo","parseModelId","join","homedir","createHash","path","mkdirSync","dirname","randomBytes","writeFileSync","renameSync","unlinkSync","loadProviderCatalog","getProviderProfile","catalogModelSchema","patchModelInfo","diag","readFileSync","statSync","Retry","registerBuiltins","boundFetch"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,IAAM,qBAAA,GAA2C;AAAA,EAC/C,cAAA,EAAgB,KAAA;AAAA,EAChB,wBAAA,EAA0B,KAAA;AAAA,EAC1B,eAAA,EAAiB,KAAA;AAAA,EACjB,oBAAA,EAAsB,KAAA;AAAA,EACtB,gBAAA,EAAkB,IAAA;AAAA,EAClB,eAAA,EAAiB;AACnB,CAAA;AAGA,IAAM,gBAAA,GAAmB,CAAC,aAAA,EAAe,SAAA,EAAW,UAAU,CAAA;AAM9D,SAAS,gBAAgB,CAAA,EAAoC;AAC3D,EAAA,OAAO;AAAA,IACL,cAAA,EAAgB,EAA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,IAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AAAA,EACnC;AAEA,EAAA,MAAM,IAAA,GAAO,MAAM,gBAAA,CAAiB,GAAA,EAAKC,6BAAW,IAAA,CAAK,IAAA,EAAM,KAAK,CAAC,CAAA;AAErE,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,EAAE,QAAQ,OAAA,EAAS,MAAA,EAAQ,kBAAA,CAAmB,GAAG,CAAA,EAAE;AAElF,EAAA,OAAO,eAAA,CAAgB,MAAM,IAAI,CAAA;AACnC;AAGO,SAAS,aAAa,OAAA,EAAyD;AACpF,EAAA,OAAOrB,sCAAoB,OAAO,CAAA;AACpC","file":"models.cjs","sourcesContent":["/**\n * T3.10c — Model capability registry (DR3 #17).\n *\n * Typed per-model flags that let the SDK gate features at the boundary\n * (before hitting the provider) instead of letting opaque 400s surface.\n *\n * Resolution algorithm:\n * 1. Strip routing prefixes (openrouter/, vertex/, bedrock/) AND the\n * OpenRouter `:variant` suffix (:free/:nitro/…) to find the bare vendor id.\n * 2. Exact match in the `EXACT` catalog → return entry.\n * 3. Vendor inference (e.g., `claude-*` → `anthropic/claude-*`) → return entry.\n * 4. No match → conservative defaults (all false, minimum tokens).\n *\n * Module is internal, but `ModelCapabilities` + `resolveModelCapabilities` are\n * re-exported publicly via the `@theokit/sdk/models` subpath (see their @public tags).\n */\n\n/**\n * Per-model capability shape. Consumers use this to gate features at\n * the SDK boundary (before request construction, not after 400).\n *\n * @public\n */\nexport interface ModelCapabilities {\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsToolUse: boolean;\n supportsCacheControl: boolean;\n maxContextTokens: number;\n maxOutputTokens: number;\n}\n\nconst CONSERVATIVE_DEFAULTS: ModelCapabilities = {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: false,\n supportsCacheControl: false,\n maxContextTokens: 4096,\n maxOutputTokens: 4096,\n};\n\n/** Routing prefixes to strip to find the underlying vendor model. */\nconst ROUTING_PREFIXES = [\"openrouter/\", \"vertex/\", \"bedrock/\"] as const;\n\nimport { getCatalogModelInfo } from \"../providers/catalog-loader.js\";\nimport type { CatalogModel } from \"../providers/catalog-schema.js\";\n\n/** Map a catalog model block (models.dev shape) to the SDK's ModelCapabilities (M44 — catalog-backed). */\nfunction capsFromCatalog(m: CatalogModel): ModelCapabilities {\n return {\n supportsVision: m.modalities?.input?.includes(\"image\") ?? m.attachment ?? false,\n supportsStructuredOutput: m.structured_output ?? false,\n supportsToolUse: m.tool_call ?? false,\n supportsCacheControl: (m as { cache_control?: boolean }).cache_control ?? false,\n maxContextTokens: m.limit?.context ?? CONSERVATIVE_DEFAULTS.maxContextTokens,\n maxOutputTokens: m.limit?.output ?? CONSERVATIVE_DEFAULTS.maxOutputTokens,\n };\n}\n\n/**\n * Resolve per-model capability flags (vision/structured-output/tool-use/cache +\n * `maxContextTokens`/`maxOutputTokens`) for a model id. Pure, sync, offline (a\n * static catalog — no network). Strips routing prefixes (`openrouter/`/`vertex/`/\n * `bedrock/`) and OpenRouter `:variant` suffixes before lookup; unknown models get\n * conservative defaults. Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function resolveModelCapabilities(modelId: string): ModelCapabilities {\n const bare = stripVariantSuffix(stripRoutingPrefix(modelId));\n // M44 — the catalog model-info index replaced the hand-curated EXACT map (single source of truth; the\n // vendored provider-catalog.json carries the migrated data — parity-tested against the old map snapshot).\n const fromIndex = getCatalogModelInfo(bare);\n if (fromIndex !== undefined) return capsFromCatalog(fromIndex);\n // Routing-prefixed models (vertex/claude-3-5-sonnet) strip to bare\n // model name without vendor. Try inferring the vendor from the name.\n const withVendor = inferVendorPrefix(bare);\n if (withVendor !== bare) {\n const vendored = getCatalogModelInfo(withVendor);\n if (vendored !== undefined) return capsFromCatalog(vendored);\n }\n return CONSERVATIVE_DEFAULTS;\n}\n\nfunction stripRoutingPrefix(modelId: string): string {\n for (const prefix of ROUTING_PREFIXES) {\n if (modelId.startsWith(prefix)) return modelId.slice(prefix.length);\n }\n return modelId;\n}\n\n/**\n * Strip an OpenRouter variant suffix (`:free`/`:nitro`/`:floor`/`:beta`/…) so the\n * catalog lookup hits the underlying model. Model slugs contain no `:` except the\n * variant separator, so cutting at the first `:` is safe.\n */\nfunction stripVariantSuffix(modelId: string): string {\n const i = modelId.indexOf(\":\");\n return i >= 0 ? modelId.slice(0, i) : modelId;\n}\n\n/** Infer vendor prefix from bare model name for routing-prefixed lookups. */\nfunction inferVendorPrefix(bare: string): string {\n if (bare.startsWith(\"claude\")) return `anthropic/${bare}`;\n if (bare.startsWith(\"gpt-\") || bare.startsWith(\"o1\") || bare.startsWith(\"o3\"))\n return `openai/${bare}`;\n if (bare.startsWith(\"gemini\")) return `google/${bare}`;\n return bare;\n}\n","import { parseModelId } from \"./model-identifier.js\";\n\n/**\n * A UI-friendly model option — the shape a `<select>`/dropdown consumes.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport interface ModelOption {\n /** The original model id (what you pass back to the SDK). */\n value: string;\n /** Best-effort human label (see {@link humanizeModelName}). */\n label: string;\n /** Provider from the slug prefix, or `undefined` when none. */\n provider: string | undefined;\n}\n\n/** Tokens rendered upper-case rather than title-case. */\nconst ACRONYMS = new Set([\"gpt\", \"ai\", \"hd\", \"ui\", \"api\", \"sdk\", \"llm\", \"xl\"]);\n\nfunction prettyToken(token: string): string {\n if (ACRONYMS.has(token.toLowerCase())) return token.toUpperCase();\n return token.charAt(0).toUpperCase() + token.slice(1);\n}\n\n/**\n * Turn a model id into a best-effort human label: strip the routing/vendor\n * prefix to the core model segment, split on `-`/`_`/`.`/whitespace, title-case\n * each token (known acronyms upper-cased), and append an OpenRouter `:variant`\n * in parentheses. Deterministic, pure, dependency-free.\n *\n * Best-effort, NOT vendor-canonical: `\"anthropic/claude-3-5-sonnet\"` →\n * `\"Claude 3 5 Sonnet\"`. A UI wanting exact marketing names overrides per id.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function humanizeModelName(modelId: string): string {\n const { name } = parseModelId(modelId);\n if (name.length === 0) return \"\";\n const colon = name.indexOf(\":\");\n // Strip a trailing slash so a typo'd `gpt-4o/` keeps its name (not lost to an\n // empty last segment).\n //\n // Done by index rather than with `/\\/+$/`, and the difference is not stylistic: that pattern\n // consumes slashes to the end of the string at every start position and then backtracks\n // looking for an end-anchor that is not there (CodeQL js/polynomial-redos #6). This function\n // is `@public` and takes a caller-supplied model id. Measured on a run of slashes followed by\n // one other character: 25_000 took 496 ms, 100_000 took 31_305 ms — half a minute of pinned\n // CPU to render a label. Walking back from the end is linear and cannot backtrack.\n const base = trimTrailingSlashes(colon >= 0 ? name.slice(0, colon) : name);\n const variant = colon >= 0 ? name.slice(colon + 1) : \"\";\n const lastSlash = base.lastIndexOf(\"/\");\n const core = lastSlash >= 0 ? base.slice(lastSlash + 1) : base;\n const label = core\n .split(/[-_.\\s]+/)\n .filter((t) => t.length > 0)\n .map(prettyToken)\n .join(\" \");\n if (label.length === 0) return variant; // no base label (e.g. \":free\") → bare variant\n return variant.length > 0 ? `${label} (${variant})` : label;\n}\n\n/**\n * Build a {@link ModelOption} (`{ value, label, provider }`) for a model id —\n * a dropdown-ready entry composing {@link humanizeModelName} + `parseModelId`.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function toModelOption(modelId: string): ModelOption {\n return {\n value: modelId,\n label: humanizeModelName(modelId),\n provider: parseModelId(modelId).provider,\n };\n}\n\nconst SLASH_CODE = 47; // \"/\"\n\n/** Removes trailing `/` characters in one linear pass. See the call site for why not a regex. */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === SLASH_CODE) end--;\n return end === value.length ? value : value.slice(0, end);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { Retry } from \"../../retry.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { boundFetch } from \"../runtime-fetch.js\";\nimport { registerBuiltins } from \"./builtin/index.js\";\nimport { getCatalogModelInfo, loadProviderCatalog, patchModelInfo } from \"./catalog-loader.js\";\nimport { catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile } from \"./registry.js\";\n\n/**\n * M44 — the OPTIONAL models.dev catalog source. Explicit opt-in ONLY (`refreshModelCatalog()`): the SDK\n * NEVER fetches at startup or per-request — the vendored catalog + any existing disk cache are the offline\n * base, and every failure mode fails CLOSED back to them (ROADMAP constraint: no runtime hard network dep).\n *\n * The models.dev consumption mechanism:\n * disk cache with mtime TTL, atomic tempfile+rename write, corrupt-cache delete-and-fall-through, kill-switch\n * env. Library adaptations: NO background refresh loop (a consumer composes refresh with the SDK's cron);\n * TTL 1h (not 5min — no background refresher to keep it warm); no cross-process flock v1 (atomic rename +\n * idempotent upstream content — at most one wasted fetch).\n *\n * @internal (the public surface is `refreshModelCatalog` re-exported via `@theokit/sdk/models`)\n */\n\nconst DEFAULT_URL = \"https://models.dev/api.json\";\n\n/**\n * Ceiling on a fetched catalog, before it is parsed or written to the cache.\n *\n * The response body was read with `res.text()` and persisted with no bound, so a host serving a\n * multi-gigabyte document would have been materialised in memory and then written to disk. The\n * default URL is trusted, but `THEOKIT_MODELS_URL` lets an operator point this anywhere, and a\n * limit is the difference between \"we only fetch from a host we trust\" and \"we cannot be hurt by\n * one we do not\".\n *\n * 32 MiB is roughly 40x the real catalog (~800 KiB in 2026-08), so it bounds the failure without\n * being a number anyone has to tune when models.dev grows.\n */\nconst MAX_CATALOG_BYTES = 32 * 1024 * 1024;\nconst TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FETCH_TIMEOUT_MS = 10_000;\n\n/**\n * Arguments to `refreshModelCatalog`, the SDK's only network trigger for model metadata.\n *\n * `url` wins over the `THEOKIT_MODELS_URL` environment variable, which in turn wins over\n * `https://models.dev/api.json`. A non-default URL gets its own cache file, named by a hash of\n * the URL, so switching sources never reads another source's cache.\n *\n * `force` skips only the freshness check — it does not skip the kill switch. When\n * `THEOKIT_DISABLE_MODELS_FETCH` is set to anything other than an empty string, `\"0\"` or\n * `\"false\"`, the call returns `source: \"skipped\"` with no fetch and no cache read, whatever\n * `force` says.\n *\n * Without `force`, a cache file whose mtime is under an hour old is served directly and no\n * request is made.\n *\n * `deps` exists so tests can drive the fetch and the clock; production leaves it unset.\n */\nexport interface RefreshModelCatalogOptions {\n /** Override the source URL (`THEOKIT_MODELS_URL` env also honored). */\n url?: string;\n /** Bypass the TTL freshness gate. */\n force?: boolean;\n /** Injected for tests. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\n/**\n * What `refreshModelCatalog` did. It never throws on a failed refresh, so this is the only place\n * the outcome is reported.\n *\n * `source` is `\"network\"` only when a request succeeded, its body parsed as JSON, and the models\n * were patched in. Every failure path — kill switch aside — returns `\"cache\"`: an HTTP error\n * after retries, a timeout, an unparseable body, or a patch that threw. `\"cache\"` therefore means\n * \"serving what was already there\", which may be a fresh cache, a stale one, or nothing but the\n * vendored catalog. Read `models` to tell those apart. `\"skipped\"` means the kill switch was set.\n *\n * `models` counts the models patched into the index during this call, not the catalog's size. It\n * counts each model once even when the provider has aliases and the model is written under several\n * index keys, and it excludes models whose payload failed schema validation and models under\n * providers the SDK does not know. It is 0 whenever there was no cache to fall back on, and 0 for\n * `\"skipped\"`.\n *\n * A cache write that fails is logged and otherwise ignored: the result can still say `\"network\"`\n * with the data live in memory and nothing on disk.\n */\nexport interface RefreshModelCatalogResult {\n /** Where the data came from: a fresh network fetch, the still-fresh disk cache, or skipped entirely. */\n source: \"network\" | \"cache\" | \"skipped\";\n /** How many models were patched into the index. */\n models: number;\n}\n\n/** The cache file for a source URL (custom URLs get a hash-suffixed name). */\nexport function cachePathFor(url: string): string {\n // M44 L8 fix — honor the SDK home override so tests and multi-home setups never touch the real ~/.theokit.\n const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), \".theokit\");\n const dir = join(base, \"cache\", \"models-dev\");\n if (url === DEFAULT_URL) return join(dir, \"api.json\");\n const hash = createHash(\"sha256\").update(url).digest(\"hex\").slice(0, 12);\n return join(dir, `api-${hash}.json`);\n}\n\n/** Atomic write: temp file + rename (crash mid-write never leaves a partial cache). */\nfunction writeCacheAtomic(path: string, body: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${randomBytes(6).toString(\"hex\")}`;\n try {\n writeFileSync(tmp, body);\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best effort\n }\n throw err;\n }\n}\n\n/**\n * M44 H3 fix — models.dev provider ids ≠ theokit ids (google↔google-gemini, zai↔zhipu, togetherai↔together,\n * fireworks-ai↔fireworks, amazon-bedrock↔bedrock, google-vertex↔vertex). The RUNTIME mapping mirrors the\n * maintenance script's table; targets resolve against the CATALOG entries (id + aliases — the same namespace\n * the vendored index uses) first, then the registry.\n */\nconst MODELS_DEV_ID_MAP: Record<string, string> = {\n google: \"google-gemini\",\n zai: \"zhipu\",\n togetherai: \"together\",\n \"fireworks-ai\": \"fireworks\",\n \"amazon-bedrock\": \"bedrock\",\n \"google-vertex\": \"vertex\",\n};\n\nlet _catalogTargets: Map<string, { keys: string[] }> | undefined;\n/** external-id → the index keys (entry id + aliases) its models patch under. Lazy; catalog-first. */\nfunction catalogTargets(): Map<string, { keys: string[] }> {\n if (_catalogTargets !== undefined) return _catalogTargets;\n _catalogTargets = new Map();\n try {\n for (const entry of Object.values(loadProviderCatalog())) {\n const keys = [entry.id, ...(entry.aliases ?? [])];\n for (const k of keys) {\n if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });\n }\n }\n } catch {\n // catalog unavailable — registry fallback below still works\n }\n return _catalogTargets;\n}\n\nfunction resolvePatchKeys(externalId: string): string[] | undefined {\n const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;\n const fromCatalog = catalogTargets().get(mapped);\n if (fromCatalog !== undefined) return fromCatalog.keys;\n const profile = getProviderProfile(mapped);\n if (profile !== undefined) return [profile.name, ...(profile.aliases ?? [])];\n return undefined;\n}\n\n/** Parse + patch the index from an api.json payload. Unknown providers are skipped with WARN (once each). */\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: validates and merges an UNTRUSTED upstream payload (models.dev api.json) shape by shape, dropping a single bad model rather than the file. Each branch is a distinct malformed input; merging them loses which one was seen.\nfunction patchIndexFromApiJson(raw: unknown): number {\n if (typeof raw !== \"object\" || raw === null) return 0;\n let patched = 0;\n const skipped: string[] = [];\n for (const [providerId, provider] of Object.entries(raw as Record<string, unknown>)) {\n const models = (provider as { models?: Record<string, unknown> })?.models;\n if (models === undefined || typeof models !== \"object\") continue;\n // Enrich ONLY providers the SDK knows — models.dev's npm/api fields cannot be mapped to a theokit\n // apiMode/authType safely, so unknown providers are data we cannot route.\n const keys = resolvePatchKeys(providerId);\n if (keys === undefined) {\n skipped.push(providerId);\n continue;\n }\n for (const [modelId, rawModel] of Object.entries(models)) {\n const parsed = catalogModelSchema.safeParse(rawModel);\n if (!parsed.success) continue; // malformed model — drop silently (live data, additive drift expected)\n for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);\n patched++;\n }\n }\n if (skipped.length > 0) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh skipped ${skipped.length} unknown provider(s) (e.g. ${skipped.slice(0, 3).join(\", \")})\\n`,\n );\n }\n return patched;\n}\n\n/**\n * Load an existing disk cache into the index (called by refresh when fresh, or opportunistically by a\n * consumer at startup — NEVER fetches). Corrupt cache → delete + fall through to vendored data.\n */\nexport function loadCacheIntoIndex(url: string = DEFAULT_URL): number {\n const path = cachePathFor(url);\n let body: string;\n try {\n body = readFileSync(path, \"utf-8\");\n } catch {\n return 0; // no cache — vendored data only\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n // corrupt cache: delete and fall through to the vendored catalog.\n // M44 L9 fix — only a PARSE failure is cache corruption; a patch error must never delete a valid cache.\n try {\n unlinkSync(path);\n } catch {\n // best effort\n }\n diag(`[theokit-sdk] WARN: corrupt models-dev cache deleted (${path})\\n`);\n return 0;\n }\n try {\n return patchIndexFromApiJson(parsed);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache patch failed (${(err as Error).message})\\n`);\n return 0;\n }\n}\n\n/**\n * The kill switch, read from the environment.\n *\n * Truthy-only by design (M44 L11): a presence check would treat `THEOKIT_DISABLE_MODELS_FETCH=0`\n * and `=false` as \"disabled\", which is the opposite of what anyone writing them means.\n */\nfunction fetchDisabledByEnv(): boolean {\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n return kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\";\n}\n\n/**\n * The TTL gate: a cache file younger than {@link TTL_MS} serves without touching the network.\n *\n * Returns `undefined` when there is no usable cache — including when `statSync` throws, which is\n * how \"no cache file\" arrives. That is the ONE failure this step owns, and its fallback is simply\n * to let the caller proceed to the fetch.\n */\nfunction servedFromFreshCache(\n url: string,\n path: string,\n now: () => number,\n): RefreshModelCatalogResult | undefined {\n try {\n if (now() - statSync(path).mtimeMs >= TTL_MS) return undefined;\n } catch {\n return undefined; // no cache — proceed to fetch\n }\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n}\n\n/**\n * Fetch the catalog, bound its size, and prove it parses before anyone persists it.\n *\n * Returns `undefined` after logging when ANY of that fails — timeout, non-2xx, oversize, unparseable\n * body. The fallback this step owns is \"serve what we already have\", and the caller applies it.\n * Splitting the step from its fallback was the objection recorded in the suppression this replaces;\n * the fallback is not separated, it is named — `undefined` means \"this step could not produce a\n * body\", and there is exactly one thing to do about that.\n */\nasync function fetchCatalogBody(url: string, fetchImpl: typeof fetch): Promise<string | undefined> {\n try {\n const res = await Retry.run(\n async () => {\n const r = await fetchImpl(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n return r;\n },\n // 2 transient retries with backoff; every error here is worth one more try —\n // the whole call is already fail-closed at the caller.\n { retries: 2, isRetryable: () => true, initialDelayMs: 200 },\n );\n const declaredLength = Number(res.headers.get(\"content-length\") ?? Number.NaN);\n if (Number.isFinite(declaredLength) && declaredLength > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${declaredLength} bytes declared`);\n }\n const body = await res.text();\n // Checked again after reading: `content-length` is the server's claim, and a server that\n // omits it or lies about it is exactly the one worth bounding. Both checks are cheap and\n // neither alone is sufficient.\n if (body.length > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${body.length} bytes received`);\n }\n JSON.parse(body); // validate before persisting — never cache garbage\n return body;\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return undefined;\n }\n}\n\n/**\n * Persist the fetched body and patch it into the index.\n *\n * Two independent failures with two different consequences, which is why they are two try blocks\n * and not one: a cache write that fails costs the NEXT process a fetch and nothing more, so the run\n * continues; a patch that fails means this body never reached the index, so the index is whatever it\n * was and the result says `cache`.\n */\nfunction persistAndPatch(path: string, body: string): RefreshModelCatalogResult {\n try {\n writeCacheAtomic(path, body);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache write failed (${(err as Error).message})\\n`);\n }\n try {\n return { source: \"network\", models: patchIndexFromApiJson(JSON.parse(body)) };\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev patch failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return { source: \"cache\", models: 0 };\n }\n}\n\n/**\n * Explicitly refresh the model catalog from models.dev (the ONLY network trigger in the subsystem).\n * Fail-closed: any failure keeps serving the current index (cache or vendored). Kill-switch:\n * `THEOKIT_DISABLE_MODELS_FETCH`.\n *\n * The sequence carried a cognitive-complexity suppression whose reason said splitting it would\n * \"separate a step from the fallback it owns\". The four helpers above each KEEP their fallback: the\n * TTL gate owns \"no cache\", the fetch owns every network and validation failure, the persist owns\n * the write and the patch. What is left here is the order they run in, which is what this function\n * was always for.\n *\n * Still true, and NOT fixed by the split: three of the paths return `{ source: \"cache\" }`, so a\n * caller cannot tell a timeout from an unparseable body from a patch failure. Distinguishing them\n * means adding a field to the PUBLIC `RefreshModelCatalogResult`, which is a release decision rather\n * than a refactor. The `diag` line already names the cause for an operator.\n */\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works\n // standalone (without the consumer having built an Agent first).\n registerBuiltins();\n if (fetchDisabledByEnv()) return { source: \"skipped\", models: 0 };\n\n const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;\n const path = cachePathFor(url);\n const now = opts.deps?.now ?? (() => Date.now());\n\n if (opts.force !== true) {\n const cached = servedFromFreshCache(url, path, now);\n if (cached !== undefined) return cached;\n }\n\n const body = await fetchCatalogBody(url, boundFetch(opts.deps?.fetch));\n // fail-closed: serve whatever we already have (stale cache if present, else vendored)\n if (body === undefined) return { source: \"cache\", models: loadCacheIntoIndex(url) };\n\n return persistAndPatch(path, body);\n}\n\n/** The enriched per-model view (public via `@theokit/sdk/models`): index lookup by (possibly prefixed) id. */\nexport function getModelInfo(modelId: string): ReturnType<typeof getCatalogModelInfo> {\n return getCatalogModelInfo(modelId);\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/llm/model-option.ts","../src/internal/providers/catalog-source-models-dev.ts"],"names":["parseModelId","join","homedir","createHash","path","mkdirSync","dirname","randomBytes","writeFileSync","renameSync","unlinkSync","loadProviderCatalog","getProviderProfile","catalogModelSchema","patchModelInfo","diag","readFileSync","statSync","Retry","registerBuiltins","boundFetch","getCatalogModelInfo"],"mappings":";;;;;;;;;;;;;;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EAAK;AACZ,IAAAA,sBAAA;AAAA,MACE,CAAA,6CAAA,EAAiD,IAAc,OAAO,CAAA;AAAA;AAAA,KACxE;AACA,IAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,CAAA,EAAE;AAAA,EACtC;AACF;AAkBA,eAAsB,mBAAA,CACpB,IAAA,GAAmC,EAAC,EACA;AAGpC,EAAAI,kCAAA,EAAiB;AACjB,EAAA,IAAI,oBAAmB,EAAG,OAAO,EAAE,MAAA,EAAQ,SAAA,EAAW,QAAQ,CAAA,EAAE;AAEhE,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,IAAO,OAAA,CAAQ,IAAI,kBAAA,IAAsB,WAAA;AAC1D,EAAA,MAAM,IAAA,GAAO,aAAa,GAAG,CAAA;AAC7B,EAAA,MAAM,MAAM,IAAA,CAAK,IAAA,EAAM,GAAA,KAAQ,MAAM,KAAK,GAAA,EAAI,CAAA;AAE9C,EAAA,IAAI,IAAA,CAAK,UAAU,IAAA,EAAM;AACvB,IAAA,MAAM,MAAA,GAAS,oBAAA,CAAqB,GAAA,EAAK,IAAA,EAAM,GAAG,CAAA;AAClD,IAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AAAA,EACnC;AAEA,EAAA,MAAM,IAAA,GAAO,MAAM,gBAAA,CAAiB,GAAA,EAAKC,6BAAW,IAAA,CAAK,IAAA,EAAM,KAAK,CAAC,CAAA;AAErE,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,EAAE,QAAQ,OAAA,EAAS,MAAA,EAAQ,kBAAA,CAAmB,GAAG,CAAA,EAAE;AAElF,EAAA,OAAO,eAAA,CAAgB,MAAM,IAAI,CAAA;AACnC;AAGO,SAAS,aAAa,OAAA,EAAyD;AACpF,EAAA,OAAOC,sCAAoB,OAAO,CAAA;AACpC","file":"models.cjs","sourcesContent":["import { parseModelId } from \"./model-identifier.js\";\n\n/**\n * A UI-friendly model option — the shape a `<select>`/dropdown consumes.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport interface ModelOption {\n /** The original model id (what you pass back to the SDK). */\n value: string;\n /** Best-effort human label (see {@link humanizeModelName}). */\n label: string;\n /** Provider from the slug prefix, or `undefined` when none. */\n provider: string | undefined;\n}\n\n/** Tokens rendered upper-case rather than title-case. */\nconst ACRONYMS = new Set([\"gpt\", \"ai\", \"hd\", \"ui\", \"api\", \"sdk\", \"llm\", \"xl\"]);\n\nfunction prettyToken(token: string): string {\n if (ACRONYMS.has(token.toLowerCase())) return token.toUpperCase();\n return token.charAt(0).toUpperCase() + token.slice(1);\n}\n\n/**\n * Turn a model id into a best-effort human label: strip the routing/vendor\n * prefix to the core model segment, split on `-`/`_`/`.`/whitespace, title-case\n * each token (known acronyms upper-cased), and append an OpenRouter `:variant`\n * in parentheses. Deterministic, pure, dependency-free.\n *\n * Best-effort, NOT vendor-canonical: `\"anthropic/claude-3-5-sonnet\"` →\n * `\"Claude 3 5 Sonnet\"`. A UI wanting exact marketing names overrides per id.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function humanizeModelName(modelId: string): string {\n const { name } = parseModelId(modelId);\n if (name.length === 0) return \"\";\n const colon = name.indexOf(\":\");\n // Strip a trailing slash so a typo'd `gpt-4o/` keeps its name (not lost to an\n // empty last segment).\n //\n // Done by index rather than with `/\\/+$/`, and the difference is not stylistic: that pattern\n // consumes slashes to the end of the string at every start position and then backtracks\n // looking for an end-anchor that is not there (CodeQL js/polynomial-redos #6). This function\n // is `@public` and takes a caller-supplied model id. Measured on a run of slashes followed by\n // one other character: 25_000 took 496 ms, 100_000 took 31_305 ms — half a minute of pinned\n // CPU to render a label. Walking back from the end is linear and cannot backtrack.\n const base = trimTrailingSlashes(colon >= 0 ? name.slice(0, colon) : name);\n const variant = colon >= 0 ? name.slice(colon + 1) : \"\";\n const lastSlash = base.lastIndexOf(\"/\");\n const core = lastSlash >= 0 ? base.slice(lastSlash + 1) : base;\n const label = core\n .split(/[-_.\\s]+/)\n .filter((t) => t.length > 0)\n .map(prettyToken)\n .join(\" \");\n if (label.length === 0) return variant; // no base label (e.g. \":free\") → bare variant\n return variant.length > 0 ? `${label} (${variant})` : label;\n}\n\n/**\n * Build a {@link ModelOption} (`{ value, label, provider }`) for a model id —\n * a dropdown-ready entry composing {@link humanizeModelName} + `parseModelId`.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function toModelOption(modelId: string): ModelOption {\n return {\n value: modelId,\n label: humanizeModelName(modelId),\n provider: parseModelId(modelId).provider,\n };\n}\n\nconst SLASH_CODE = 47; // \"/\"\n\n/** Removes trailing `/` characters in one linear pass. See the call site for why not a regex. */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === SLASH_CODE) end--;\n return end === value.length ? value : value.slice(0, end);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { Retry } from \"../../retry.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { boundFetch } from \"../runtime-fetch.js\";\nimport { registerBuiltins } from \"./builtin/index.js\";\nimport { getCatalogModelInfo, loadProviderCatalog, patchModelInfo } from \"./catalog-loader.js\";\nimport { catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile } from \"./registry.js\";\n\n/**\n * M44 — the OPTIONAL models.dev catalog source. Explicit opt-in ONLY (`refreshModelCatalog()`): the SDK\n * NEVER fetches at startup or per-request — the vendored catalog + any existing disk cache are the offline\n * base, and every failure mode fails CLOSED back to them (ROADMAP constraint: no runtime hard network dep).\n *\n * The models.dev consumption mechanism:\n * disk cache with mtime TTL, atomic tempfile+rename write, corrupt-cache delete-and-fall-through, kill-switch\n * env. Library adaptations: NO background refresh loop (a consumer composes refresh with the SDK's cron);\n * TTL 1h (not 5min — no background refresher to keep it warm); no cross-process flock v1 (atomic rename +\n * idempotent upstream content — at most one wasted fetch).\n *\n * @internal (the public surface is `refreshModelCatalog` re-exported via `@theokit/sdk/models`)\n */\n\nconst DEFAULT_URL = \"https://models.dev/api.json\";\n\n/**\n * Ceiling on a fetched catalog, before it is parsed or written to the cache.\n *\n * The response body was read with `res.text()` and persisted with no bound, so a host serving a\n * multi-gigabyte document would have been materialised in memory and then written to disk. The\n * default URL is trusted, but `THEOKIT_MODELS_URL` lets an operator point this anywhere, and a\n * limit is the difference between \"we only fetch from a host we trust\" and \"we cannot be hurt by\n * one we do not\".\n *\n * 32 MiB is roughly 40x the real catalog (~800 KiB in 2026-08), so it bounds the failure without\n * being a number anyone has to tune when models.dev grows.\n */\nconst MAX_CATALOG_BYTES = 32 * 1024 * 1024;\nconst TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FETCH_TIMEOUT_MS = 10_000;\n\n/**\n * Arguments to `refreshModelCatalog`, the SDK's only network trigger for model metadata.\n *\n * `url` wins over the `THEOKIT_MODELS_URL` environment variable, which in turn wins over\n * `https://models.dev/api.json`. A non-default URL gets its own cache file, named by a hash of\n * the URL, so switching sources never reads another source's cache.\n *\n * `force` skips only the freshness check — it does not skip the kill switch. When\n * `THEOKIT_DISABLE_MODELS_FETCH` is set to anything other than an empty string, `\"0\"` or\n * `\"false\"`, the call returns `source: \"skipped\"` with no fetch and no cache read, whatever\n * `force` says.\n *\n * Without `force`, a cache file whose mtime is under an hour old is served directly and no\n * request is made.\n *\n * `deps` exists so tests can drive the fetch and the clock; production leaves it unset.\n */\nexport interface RefreshModelCatalogOptions {\n /** Override the source URL (`THEOKIT_MODELS_URL` env also honored). */\n url?: string;\n /** Bypass the TTL freshness gate. */\n force?: boolean;\n /** Injected for tests. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\n/**\n * What `refreshModelCatalog` did. It never throws on a failed refresh, so this is the only place\n * the outcome is reported.\n *\n * `source` is `\"network\"` only when a request succeeded, its body parsed as JSON, and the models\n * were patched in. Every failure path — kill switch aside — returns `\"cache\"`: an HTTP error\n * after retries, a timeout, an unparseable body, or a patch that threw. `\"cache\"` therefore means\n * \"serving what was already there\", which may be a fresh cache, a stale one, or nothing but the\n * vendored catalog. Read `models` to tell those apart. `\"skipped\"` means the kill switch was set.\n *\n * `models` counts the models patched into the index during this call, not the catalog's size. It\n * counts each model once even when the provider has aliases and the model is written under several\n * index keys, and it excludes models whose payload failed schema validation and models under\n * providers the SDK does not know. It is 0 whenever there was no cache to fall back on, and 0 for\n * `\"skipped\"`.\n *\n * A cache write that fails is logged and otherwise ignored: the result can still say `\"network\"`\n * with the data live in memory and nothing on disk.\n */\nexport interface RefreshModelCatalogResult {\n /** Where the data came from: a fresh network fetch, the still-fresh disk cache, or skipped entirely. */\n source: \"network\" | \"cache\" | \"skipped\";\n /** How many models were patched into the index. */\n models: number;\n}\n\n/** The cache file for a source URL (custom URLs get a hash-suffixed name). */\nexport function cachePathFor(url: string): string {\n // M44 L8 fix — honor the SDK home override so tests and multi-home setups never touch the real ~/.theokit.\n const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), \".theokit\");\n const dir = join(base, \"cache\", \"models-dev\");\n if (url === DEFAULT_URL) return join(dir, \"api.json\");\n const hash = createHash(\"sha256\").update(url).digest(\"hex\").slice(0, 12);\n return join(dir, `api-${hash}.json`);\n}\n\n/** Atomic write: temp file + rename (crash mid-write never leaves a partial cache). */\nfunction writeCacheAtomic(path: string, body: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${randomBytes(6).toString(\"hex\")}`;\n try {\n writeFileSync(tmp, body);\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best effort\n }\n throw err;\n }\n}\n\n/**\n * M44 H3 fix — models.dev provider ids ≠ theokit ids (google↔google-gemini, zai↔zhipu, togetherai↔together,\n * fireworks-ai↔fireworks, amazon-bedrock↔bedrock, google-vertex↔vertex). The RUNTIME mapping mirrors the\n * maintenance script's table; targets resolve against the CATALOG entries (id + aliases — the same namespace\n * the vendored index uses) first, then the registry.\n */\nconst MODELS_DEV_ID_MAP: Record<string, string> = {\n google: \"google-gemini\",\n zai: \"zhipu\",\n togetherai: \"together\",\n \"fireworks-ai\": \"fireworks\",\n \"amazon-bedrock\": \"bedrock\",\n \"google-vertex\": \"vertex\",\n};\n\nlet _catalogTargets: Map<string, { keys: string[] }> | undefined;\n/** external-id → the index keys (entry id + aliases) its models patch under. Lazy; catalog-first. */\nfunction catalogTargets(): Map<string, { keys: string[] }> {\n if (_catalogTargets !== undefined) return _catalogTargets;\n _catalogTargets = new Map();\n try {\n for (const entry of Object.values(loadProviderCatalog())) {\n const keys = [entry.id, ...(entry.aliases ?? [])];\n for (const k of keys) {\n if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });\n }\n }\n } catch {\n // catalog unavailable — registry fallback below still works\n }\n return _catalogTargets;\n}\n\nfunction resolvePatchKeys(externalId: string): string[] | undefined {\n const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;\n const fromCatalog = catalogTargets().get(mapped);\n if (fromCatalog !== undefined) return fromCatalog.keys;\n const profile = getProviderProfile(mapped);\n if (profile !== undefined) return [profile.name, ...(profile.aliases ?? [])];\n return undefined;\n}\n\n/** Parse + patch the index from an api.json payload. Unknown providers are skipped with WARN (once each). */\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: validates and merges an UNTRUSTED upstream payload (models.dev api.json) shape by shape, dropping a single bad model rather than the file. Each branch is a distinct malformed input; merging them loses which one was seen.\nfunction patchIndexFromApiJson(raw: unknown): number {\n if (typeof raw !== \"object\" || raw === null) return 0;\n let patched = 0;\n const skipped: string[] = [];\n for (const [providerId, provider] of Object.entries(raw as Record<string, unknown>)) {\n const models = (provider as { models?: Record<string, unknown> })?.models;\n if (models === undefined || typeof models !== \"object\") continue;\n // Enrich ONLY providers the SDK knows — models.dev's npm/api fields cannot be mapped to a theokit\n // apiMode/authType safely, so unknown providers are data we cannot route.\n const keys = resolvePatchKeys(providerId);\n if (keys === undefined) {\n skipped.push(providerId);\n continue;\n }\n for (const [modelId, rawModel] of Object.entries(models)) {\n const parsed = catalogModelSchema.safeParse(rawModel);\n if (!parsed.success) continue; // malformed model — drop silently (live data, additive drift expected)\n for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);\n patched++;\n }\n }\n if (skipped.length > 0) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh skipped ${skipped.length} unknown provider(s) (e.g. ${skipped.slice(0, 3).join(\", \")})\\n`,\n );\n }\n return patched;\n}\n\n/**\n * Load an existing disk cache into the index (called by refresh when fresh, or opportunistically by a\n * consumer at startup — NEVER fetches). Corrupt cache → delete + fall through to vendored data.\n */\nexport function loadCacheIntoIndex(url: string = DEFAULT_URL): number {\n const path = cachePathFor(url);\n let body: string;\n try {\n body = readFileSync(path, \"utf-8\");\n } catch {\n return 0; // no cache — vendored data only\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n // corrupt cache: delete and fall through to the vendored catalog.\n // M44 L9 fix — only a PARSE failure is cache corruption; a patch error must never delete a valid cache.\n try {\n unlinkSync(path);\n } catch {\n // best effort\n }\n diag(`[theokit-sdk] WARN: corrupt models-dev cache deleted (${path})\\n`);\n return 0;\n }\n try {\n return patchIndexFromApiJson(parsed);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache patch failed (${(err as Error).message})\\n`);\n return 0;\n }\n}\n\n/**\n * The kill switch, read from the environment.\n *\n * Truthy-only by design (M44 L11): a presence check would treat `THEOKIT_DISABLE_MODELS_FETCH=0`\n * and `=false` as \"disabled\", which is the opposite of what anyone writing them means.\n */\nfunction fetchDisabledByEnv(): boolean {\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n return kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\";\n}\n\n/**\n * The TTL gate: a cache file younger than {@link TTL_MS} serves without touching the network.\n *\n * Returns `undefined` when there is no usable cache — including when `statSync` throws, which is\n * how \"no cache file\" arrives. That is the ONE failure this step owns, and its fallback is simply\n * to let the caller proceed to the fetch.\n */\nfunction servedFromFreshCache(\n url: string,\n path: string,\n now: () => number,\n): RefreshModelCatalogResult | undefined {\n try {\n if (now() - statSync(path).mtimeMs >= TTL_MS) return undefined;\n } catch {\n return undefined; // no cache — proceed to fetch\n }\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n}\n\n/**\n * Fetch the catalog, bound its size, and prove it parses before anyone persists it.\n *\n * Returns `undefined` after logging when ANY of that fails — timeout, non-2xx, oversize, unparseable\n * body. The fallback this step owns is \"serve what we already have\", and the caller applies it.\n * Splitting the step from its fallback was the objection recorded in the suppression this replaces;\n * the fallback is not separated, it is named — `undefined` means \"this step could not produce a\n * body\", and there is exactly one thing to do about that.\n */\nasync function fetchCatalogBody(url: string, fetchImpl: typeof fetch): Promise<string | undefined> {\n try {\n const res = await Retry.run(\n async () => {\n const r = await fetchImpl(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n return r;\n },\n // 2 transient retries with backoff; every error here is worth one more try —\n // the whole call is already fail-closed at the caller.\n { retries: 2, isRetryable: () => true, initialDelayMs: 200 },\n );\n const declaredLength = Number(res.headers.get(\"content-length\") ?? Number.NaN);\n if (Number.isFinite(declaredLength) && declaredLength > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${declaredLength} bytes declared`);\n }\n const body = await res.text();\n // Checked again after reading: `content-length` is the server's claim, and a server that\n // omits it or lies about it is exactly the one worth bounding. Both checks are cheap and\n // neither alone is sufficient.\n if (body.length > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${body.length} bytes received`);\n }\n JSON.parse(body); // validate before persisting — never cache garbage\n return body;\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return undefined;\n }\n}\n\n/**\n * Persist the fetched body and patch it into the index.\n *\n * Two independent failures with two different consequences, which is why they are two try blocks\n * and not one: a cache write that fails costs the NEXT process a fetch and nothing more, so the run\n * continues; a patch that fails means this body never reached the index, so the index is whatever it\n * was and the result says `cache`.\n */\nfunction persistAndPatch(path: string, body: string): RefreshModelCatalogResult {\n try {\n writeCacheAtomic(path, body);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache write failed (${(err as Error).message})\\n`);\n }\n try {\n return { source: \"network\", models: patchIndexFromApiJson(JSON.parse(body)) };\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev patch failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return { source: \"cache\", models: 0 };\n }\n}\n\n/**\n * Explicitly refresh the model catalog from models.dev (the ONLY network trigger in the subsystem).\n * Fail-closed: any failure keeps serving the current index (cache or vendored). Kill-switch:\n * `THEOKIT_DISABLE_MODELS_FETCH`.\n *\n * The sequence carried a cognitive-complexity suppression whose reason said splitting it would\n * \"separate a step from the fallback it owns\". The four helpers above each KEEP their fallback: the\n * TTL gate owns \"no cache\", the fetch owns every network and validation failure, the persist owns\n * the write and the patch. What is left here is the order they run in, which is what this function\n * was always for.\n *\n * Still true, and NOT fixed by the split: three of the paths return `{ source: \"cache\" }`, so a\n * caller cannot tell a timeout from an unparseable body from a patch failure. Distinguishing them\n * means adding a field to the PUBLIC `RefreshModelCatalogResult`, which is a release decision rather\n * than a refactor. The `diag` line already names the cause for an operator.\n */\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works\n // standalone (without the consumer having built an Agent first).\n registerBuiltins();\n if (fetchDisabledByEnv()) return { source: \"skipped\", models: 0 };\n\n const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;\n const path = cachePathFor(url);\n const now = opts.deps?.now ?? (() => Date.now());\n\n if (opts.force !== true) {\n const cached = servedFromFreshCache(url, path, now);\n if (cached !== undefined) return cached;\n }\n\n const body = await fetchCatalogBody(url, boundFetch(opts.deps?.fetch));\n // fail-closed: serve whatever we already have (stale cache if present, else vendored)\n if (body === undefined) return { source: \"cache\", models: loadCacheIntoIndex(url) };\n\n return persistAndPatch(path, body);\n}\n\n/** The enriched per-model view (public via `@theokit/sdk/models`): index lookup by (possibly prefixed) id. */\nexport function getModelInfo(modelId: string): ReturnType<typeof getCatalogModelInfo> {\n return getCatalogModelInfo(modelId);\n}\n"]}
package/dist/models.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { Retry } from './chunk-7F7XE6CM.js';
2
+ export { resolveModelCapabilities } from './chunk-LZJXEPEQ.js';
2
3
  import { parseModelId } from './chunk-R7WIIPUR.js';
3
4
  export { parseModelId } from './chunk-R7WIIPUR.js';
4
- import { getCatalogModelInfo, registerBuiltins, catalogModelSchema, patchModelInfo, getProviderProfile, loadProviderCatalog } from './chunk-SVCPJRUB.js';
5
+ import { registerBuiltins, getCatalogModelInfo, catalogModelSchema, patchModelInfo, getProviderProfile, loadProviderCatalog } from './chunk-SVCPJRUB.js';
5
6
  import './chunk-AGACYRJ2.js';
6
7
  import './chunk-TX56N7FR.js';
7
8
  import './chunk-5Q4RTLMP.js';
@@ -14,55 +15,6 @@ import { statSync, readFileSync, unlinkSync, mkdirSync, writeFileSync, renameSyn
14
15
  import { homedir } from 'os';
15
16
  import { join, dirname } from 'path';
16
17
 
17
- // src/internal/llm/model-capabilities.ts
18
- var CONSERVATIVE_DEFAULTS = {
19
- supportsVision: false,
20
- supportsStructuredOutput: false,
21
- supportsToolUse: false,
22
- supportsCacheControl: false,
23
- maxContextTokens: 4096,
24
- maxOutputTokens: 4096
25
- };
26
- var ROUTING_PREFIXES = ["openrouter/", "vertex/", "bedrock/"];
27
- function capsFromCatalog(m) {
28
- return {
29
- supportsVision: m.modalities?.input?.includes("image") ?? m.attachment ?? false,
30
- supportsStructuredOutput: m.structured_output ?? false,
31
- supportsToolUse: m.tool_call ?? false,
32
- supportsCacheControl: m.cache_control ?? false,
33
- maxContextTokens: m.limit?.context ?? CONSERVATIVE_DEFAULTS.maxContextTokens,
34
- maxOutputTokens: m.limit?.output ?? CONSERVATIVE_DEFAULTS.maxOutputTokens
35
- };
36
- }
37
- function resolveModelCapabilities(modelId) {
38
- const bare = stripVariantSuffix(stripRoutingPrefix(modelId));
39
- const fromIndex = getCatalogModelInfo(bare);
40
- if (fromIndex !== void 0) return capsFromCatalog(fromIndex);
41
- const withVendor = inferVendorPrefix(bare);
42
- if (withVendor !== bare) {
43
- const vendored = getCatalogModelInfo(withVendor);
44
- if (vendored !== void 0) return capsFromCatalog(vendored);
45
- }
46
- return CONSERVATIVE_DEFAULTS;
47
- }
48
- function stripRoutingPrefix(modelId) {
49
- for (const prefix of ROUTING_PREFIXES) {
50
- if (modelId.startsWith(prefix)) return modelId.slice(prefix.length);
51
- }
52
- return modelId;
53
- }
54
- function stripVariantSuffix(modelId) {
55
- const i = modelId.indexOf(":");
56
- return i >= 0 ? modelId.slice(0, i) : modelId;
57
- }
58
- function inferVendorPrefix(bare) {
59
- if (bare.startsWith("claude")) return `anthropic/${bare}`;
60
- if (bare.startsWith("gpt-") || bare.startsWith("o1") || bare.startsWith("o3"))
61
- return `openai/${bare}`;
62
- if (bare.startsWith("gemini")) return `google/${bare}`;
63
- return bare;
64
- }
65
-
66
18
  // src/internal/llm/model-option.ts
67
19
  var ACRONYMS = /* @__PURE__ */ new Set(["gpt", "ai", "hd", "ui", "api", "sdk", "llm", "xl"]);
68
20
  function prettyToken(token) {
@@ -282,6 +234,6 @@ function getModelInfo(modelId) {
282
234
  return getCatalogModelInfo(modelId);
283
235
  }
284
236
 
285
- export { getModelInfo, humanizeModelName, refreshModelCatalog, resolveModelCapabilities, toModelOption };
237
+ export { getModelInfo, humanizeModelName, refreshModelCatalog, toModelOption };
286
238
  //# sourceMappingURL=models.js.map
287
239
  //# sourceMappingURL=models.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/llm/model-capabilities.ts","../src/internal/llm/model-option.ts","../src/internal/providers/catalog-source-models-dev.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAgCA,IAAM,qBAAA,GAA2C;AAAA,EAC/C,cAAA,EAAgB,KAAA;AAAA,EAChB,wBAAA,EAA0B,KAAA;AAAA,EAC1B,eAAA,EAAiB,KAAA;AAAA,EACjB,oBAAA,EAAsB,KAAA;AAAA,EACtB,gBAAA,EAAkB,IAAA;AAAA,EAClB,eAAA,EAAiB;AACnB,CAAA;AAGA,IAAM,gBAAA,GAAmB,CAAC,aAAA,EAAe,SAAA,EAAW,UAAU,CAAA;AAM9D,SAAS,gBAAgB,CAAA,EAAoC;AAC3D,EAAA,OAAO;AAAA,IACL,cAAA,EAAgB,EAAE,UAAA,EAAY,KAAA,EAAO,SAAS,OAAO,CAAA,IAAK,EAAE,UAAA,IAAc,KAAA;AAAA,IAC1E,wBAAA,EAA0B,EAAE,iBAAA,IAAqB,KAAA;AAAA,IACjD,eAAA,EAAiB,EAAE,SAAA,IAAa,KAAA;AAAA,IAChC,oBAAA,EAAuB,EAAkC,aAAA,IAAiB,KAAA;AAAA,IAC1E,gBAAA,EAAkB,CAAA,CAAE,KAAA,EAAO,OAAA,IAAW,qBAAA,CAAsB,gBAAA;AAAA,IAC5D,eAAA,EAAiB,CAAA,CAAE,KAAA,EAAO,MAAA,IAAU,qBAAA,CAAsB;AAAA,GAC5D;AACF;AAWO,SAAS,yBAAyB,OAAA,EAAoC;AAC3E,EAAA,MAAM,IAAA,GAAO,kBAAA,CAAmB,kBAAA,CAAmB,OAAO,CAAC,CAAA;AAG3D,EAAA,MAAM,SAAA,GAAY,oBAAoB,IAAI,CAAA;AAC1C,EAAA,IAAI,SAAA,KAAc,MAAA,EAAW,O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;AAAA,EACtC;AACF;AAkBA,eAAsB,mBAAA,CACpB,IAAA,GAAmC,EAAC,EACA;AAGpC,EAAA,gBAAA,EAAiB;AACjB,EAAA,IAAI,oBAAmB,EAAG,OAAO,EAAE,MAAA,EAAQ,SAAA,EAAW,QAAQ,CAAA,EAAE;AAEhE,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,IAAO,OAAA,CAAQ,IAAI,kBAAA,IAAsB,WAAA;AAC1D,EAAA,MAAM,IAAA,GAAO,aAAa,GAAG,CAAA;AAC7B,EAAA,MAAM,MAAM,IAAA,CAAK,IAAA,EAAM,GAAA,KAAQ,MAAM,KAAK,GAAA,EAAI,CAAA;AAE9C,EAAA,IAAI,IAAA,CAAK,UAAU,IAAA,EAAM;AACvB,IAAA,MAAM,MAAA,GAAS,oBAAA,CAAqB,GAAA,EAAK,IAAA,EAAM,GAAG,CAAA;AAClD,IAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AAAA,EACnC;AAEA,EAAA,MAAM,IAAA,GAAO,MAAM,gBAAA,CAAiB,GAAA,EAAK,WAAW,IAAA,CAAK,IAAA,EAAM,KAAK,CAAC,CAAA;AAErE,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,EAAE,QAAQ,OAAA,EAAS,MAAA,EAAQ,kBAAA,CAAmB,GAAG,CAAA,EAAE;AAElF,EAAA,OAAO,eAAA,CAAgB,MAAM,IAAI,CAAA;AACnC;AAGO,SAAS,aAAa,OAAA,EAAyD;AACpF,EAAA,OAAO,oBAAoB,OAAO,CAAA;AACpC","file":"models.js","sourcesContent":["/**\n * T3.10c — Model capability registry (DR3 #17).\n *\n * Typed per-model flags that let the SDK gate features at the boundary\n * (before hitting the provider) instead of letting opaque 400s surface.\n *\n * Resolution algorithm:\n * 1. Strip routing prefixes (openrouter/, vertex/, bedrock/) AND the\n * OpenRouter `:variant` suffix (:free/:nitro/…) to find the bare vendor id.\n * 2. Exact match in the `EXACT` catalog → return entry.\n * 3. Vendor inference (e.g., `claude-*` → `anthropic/claude-*`) → return entry.\n * 4. No match → conservative defaults (all false, minimum tokens).\n *\n * Module is internal, but `ModelCapabilities` + `resolveModelCapabilities` are\n * re-exported publicly via the `@theokit/sdk/models` subpath (see their @public tags).\n */\n\n/**\n * Per-model capability shape. Consumers use this to gate features at\n * the SDK boundary (before request construction, not after 400).\n *\n * @public\n */\nexport interface ModelCapabilities {\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsToolUse: boolean;\n supportsCacheControl: boolean;\n maxContextTokens: number;\n maxOutputTokens: number;\n}\n\nconst CONSERVATIVE_DEFAULTS: ModelCapabilities = {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: false,\n supportsCacheControl: false,\n maxContextTokens: 4096,\n maxOutputTokens: 4096,\n};\n\n/** Routing prefixes to strip to find the underlying vendor model. */\nconst ROUTING_PREFIXES = [\"openrouter/\", \"vertex/\", \"bedrock/\"] as const;\n\nimport { getCatalogModelInfo } from \"../providers/catalog-loader.js\";\nimport type { CatalogModel } from \"../providers/catalog-schema.js\";\n\n/** Map a catalog model block (models.dev shape) to the SDK's ModelCapabilities (M44 — catalog-backed). */\nfunction capsFromCatalog(m: CatalogModel): ModelCapabilities {\n return {\n supportsVision: m.modalities?.input?.includes(\"image\") ?? m.attachment ?? false,\n supportsStructuredOutput: m.structured_output ?? false,\n supportsToolUse: m.tool_call ?? false,\n supportsCacheControl: (m as { cache_control?: boolean }).cache_control ?? false,\n maxContextTokens: m.limit?.context ?? CONSERVATIVE_DEFAULTS.maxContextTokens,\n maxOutputTokens: m.limit?.output ?? CONSERVATIVE_DEFAULTS.maxOutputTokens,\n };\n}\n\n/**\n * Resolve per-model capability flags (vision/structured-output/tool-use/cache +\n * `maxContextTokens`/`maxOutputTokens`) for a model id. Pure, sync, offline (a\n * static catalog — no network). Strips routing prefixes (`openrouter/`/`vertex/`/\n * `bedrock/`) and OpenRouter `:variant` suffixes before lookup; unknown models get\n * conservative defaults. Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function resolveModelCapabilities(modelId: string): ModelCapabilities {\n const bare = stripVariantSuffix(stripRoutingPrefix(modelId));\n // M44 — the catalog model-info index replaced the hand-curated EXACT map (single source of truth; the\n // vendored provider-catalog.json carries the migrated data — parity-tested against the old map snapshot).\n const fromIndex = getCatalogModelInfo(bare);\n if (fromIndex !== undefined) return capsFromCatalog(fromIndex);\n // Routing-prefixed models (vertex/claude-3-5-sonnet) strip to bare\n // model name without vendor. Try inferring the vendor from the name.\n const withVendor = inferVendorPrefix(bare);\n if (withVendor !== bare) {\n const vendored = getCatalogModelInfo(withVendor);\n if (vendored !== undefined) return capsFromCatalog(vendored);\n }\n return CONSERVATIVE_DEFAULTS;\n}\n\nfunction stripRoutingPrefix(modelId: string): string {\n for (const prefix of ROUTING_PREFIXES) {\n if (modelId.startsWith(prefix)) return modelId.slice(prefix.length);\n }\n return modelId;\n}\n\n/**\n * Strip an OpenRouter variant suffix (`:free`/`:nitro`/`:floor`/`:beta`/…) so the\n * catalog lookup hits the underlying model. Model slugs contain no `:` except the\n * variant separator, so cutting at the first `:` is safe.\n */\nfunction stripVariantSuffix(modelId: string): string {\n const i = modelId.indexOf(\":\");\n return i >= 0 ? modelId.slice(0, i) : modelId;\n}\n\n/** Infer vendor prefix from bare model name for routing-prefixed lookups. */\nfunction inferVendorPrefix(bare: string): string {\n if (bare.startsWith(\"claude\")) return `anthropic/${bare}`;\n if (bare.startsWith(\"gpt-\") || bare.startsWith(\"o1\") || bare.startsWith(\"o3\"))\n return `openai/${bare}`;\n if (bare.startsWith(\"gemini\")) return `google/${bare}`;\n return bare;\n}\n","import { parseModelId } from \"./model-identifier.js\";\n\n/**\n * A UI-friendly model option — the shape a `<select>`/dropdown consumes.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport interface ModelOption {\n /** The original model id (what you pass back to the SDK). */\n value: string;\n /** Best-effort human label (see {@link humanizeModelName}). */\n label: string;\n /** Provider from the slug prefix, or `undefined` when none. */\n provider: string | undefined;\n}\n\n/** Tokens rendered upper-case rather than title-case. */\nconst ACRONYMS = new Set([\"gpt\", \"ai\", \"hd\", \"ui\", \"api\", \"sdk\", \"llm\", \"xl\"]);\n\nfunction prettyToken(token: string): string {\n if (ACRONYMS.has(token.toLowerCase())) return token.toUpperCase();\n return token.charAt(0).toUpperCase() + token.slice(1);\n}\n\n/**\n * Turn a model id into a best-effort human label: strip the routing/vendor\n * prefix to the core model segment, split on `-`/`_`/`.`/whitespace, title-case\n * each token (known acronyms upper-cased), and append an OpenRouter `:variant`\n * in parentheses. Deterministic, pure, dependency-free.\n *\n * Best-effort, NOT vendor-canonical: `\"anthropic/claude-3-5-sonnet\"` →\n * `\"Claude 3 5 Sonnet\"`. A UI wanting exact marketing names overrides per id.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function humanizeModelName(modelId: string): string {\n const { name } = parseModelId(modelId);\n if (name.length === 0) return \"\";\n const colon = name.indexOf(\":\");\n // Strip a trailing slash so a typo'd `gpt-4o/` keeps its name (not lost to an\n // empty last segment).\n //\n // Done by index rather than with `/\\/+$/`, and the difference is not stylistic: that pattern\n // consumes slashes to the end of the string at every start position and then backtracks\n // looking for an end-anchor that is not there (CodeQL js/polynomial-redos #6). This function\n // is `@public` and takes a caller-supplied model id. Measured on a run of slashes followed by\n // one other character: 25_000 took 496 ms, 100_000 took 31_305 ms — half a minute of pinned\n // CPU to render a label. Walking back from the end is linear and cannot backtrack.\n const base = trimTrailingSlashes(colon >= 0 ? name.slice(0, colon) : name);\n const variant = colon >= 0 ? name.slice(colon + 1) : \"\";\n const lastSlash = base.lastIndexOf(\"/\");\n const core = lastSlash >= 0 ? base.slice(lastSlash + 1) : base;\n const label = core\n .split(/[-_.\\s]+/)\n .filter((t) => t.length > 0)\n .map(prettyToken)\n .join(\" \");\n if (label.length === 0) return variant; // no base label (e.g. \":free\") → bare variant\n return variant.length > 0 ? `${label} (${variant})` : label;\n}\n\n/**\n * Build a {@link ModelOption} (`{ value, label, provider }`) for a model id —\n * a dropdown-ready entry composing {@link humanizeModelName} + `parseModelId`.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function toModelOption(modelId: string): ModelOption {\n return {\n value: modelId,\n label: humanizeModelName(modelId),\n provider: parseModelId(modelId).provider,\n };\n}\n\nconst SLASH_CODE = 47; // \"/\"\n\n/** Removes trailing `/` characters in one linear pass. See the call site for why not a regex. */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === SLASH_CODE) end--;\n return end === value.length ? value : value.slice(0, end);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { Retry } from \"../../retry.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { boundFetch } from \"../runtime-fetch.js\";\nimport { registerBuiltins } from \"./builtin/index.js\";\nimport { getCatalogModelInfo, loadProviderCatalog, patchModelInfo } from \"./catalog-loader.js\";\nimport { catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile } from \"./registry.js\";\n\n/**\n * M44 — the OPTIONAL models.dev catalog source. Explicit opt-in ONLY (`refreshModelCatalog()`): the SDK\n * NEVER fetches at startup or per-request — the vendored catalog + any existing disk cache are the offline\n * base, and every failure mode fails CLOSED back to them (ROADMAP constraint: no runtime hard network dep).\n *\n * The models.dev consumption mechanism:\n * disk cache with mtime TTL, atomic tempfile+rename write, corrupt-cache delete-and-fall-through, kill-switch\n * env. Library adaptations: NO background refresh loop (a consumer composes refresh with the SDK's cron);\n * TTL 1h (not 5min — no background refresher to keep it warm); no cross-process flock v1 (atomic rename +\n * idempotent upstream content — at most one wasted fetch).\n *\n * @internal (the public surface is `refreshModelCatalog` re-exported via `@theokit/sdk/models`)\n */\n\nconst DEFAULT_URL = \"https://models.dev/api.json\";\n\n/**\n * Ceiling on a fetched catalog, before it is parsed or written to the cache.\n *\n * The response body was read with `res.text()` and persisted with no bound, so a host serving a\n * multi-gigabyte document would have been materialised in memory and then written to disk. The\n * default URL is trusted, but `THEOKIT_MODELS_URL` lets an operator point this anywhere, and a\n * limit is the difference between \"we only fetch from a host we trust\" and \"we cannot be hurt by\n * one we do not\".\n *\n * 32 MiB is roughly 40x the real catalog (~800 KiB in 2026-08), so it bounds the failure without\n * being a number anyone has to tune when models.dev grows.\n */\nconst MAX_CATALOG_BYTES = 32 * 1024 * 1024;\nconst TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FETCH_TIMEOUT_MS = 10_000;\n\n/**\n * Arguments to `refreshModelCatalog`, the SDK's only network trigger for model metadata.\n *\n * `url` wins over the `THEOKIT_MODELS_URL` environment variable, which in turn wins over\n * `https://models.dev/api.json`. A non-default URL gets its own cache file, named by a hash of\n * the URL, so switching sources never reads another source's cache.\n *\n * `force` skips only the freshness check — it does not skip the kill switch. When\n * `THEOKIT_DISABLE_MODELS_FETCH` is set to anything other than an empty string, `\"0\"` or\n * `\"false\"`, the call returns `source: \"skipped\"` with no fetch and no cache read, whatever\n * `force` says.\n *\n * Without `force`, a cache file whose mtime is under an hour old is served directly and no\n * request is made.\n *\n * `deps` exists so tests can drive the fetch and the clock; production leaves it unset.\n */\nexport interface RefreshModelCatalogOptions {\n /** Override the source URL (`THEOKIT_MODELS_URL` env also honored). */\n url?: string;\n /** Bypass the TTL freshness gate. */\n force?: boolean;\n /** Injected for tests. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\n/**\n * What `refreshModelCatalog` did. It never throws on a failed refresh, so this is the only place\n * the outcome is reported.\n *\n * `source` is `\"network\"` only when a request succeeded, its body parsed as JSON, and the models\n * were patched in. Every failure path — kill switch aside — returns `\"cache\"`: an HTTP error\n * after retries, a timeout, an unparseable body, or a patch that threw. `\"cache\"` therefore means\n * \"serving what was already there\", which may be a fresh cache, a stale one, or nothing but the\n * vendored catalog. Read `models` to tell those apart. `\"skipped\"` means the kill switch was set.\n *\n * `models` counts the models patched into the index during this call, not the catalog's size. It\n * counts each model once even when the provider has aliases and the model is written under several\n * index keys, and it excludes models whose payload failed schema validation and models under\n * providers the SDK does not know. It is 0 whenever there was no cache to fall back on, and 0 for\n * `\"skipped\"`.\n *\n * A cache write that fails is logged and otherwise ignored: the result can still say `\"network\"`\n * with the data live in memory and nothing on disk.\n */\nexport interface RefreshModelCatalogResult {\n /** Where the data came from: a fresh network fetch, the still-fresh disk cache, or skipped entirely. */\n source: \"network\" | \"cache\" | \"skipped\";\n /** How many models were patched into the index. */\n models: number;\n}\n\n/** The cache file for a source URL (custom URLs get a hash-suffixed name). */\nexport function cachePathFor(url: string): string {\n // M44 L8 fix — honor the SDK home override so tests and multi-home setups never touch the real ~/.theokit.\n const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), \".theokit\");\n const dir = join(base, \"cache\", \"models-dev\");\n if (url === DEFAULT_URL) return join(dir, \"api.json\");\n const hash = createHash(\"sha256\").update(url).digest(\"hex\").slice(0, 12);\n return join(dir, `api-${hash}.json`);\n}\n\n/** Atomic write: temp file + rename (crash mid-write never leaves a partial cache). */\nfunction writeCacheAtomic(path: string, body: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${randomBytes(6).toString(\"hex\")}`;\n try {\n writeFileSync(tmp, body);\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best effort\n }\n throw err;\n }\n}\n\n/**\n * M44 H3 fix — models.dev provider ids ≠ theokit ids (google↔google-gemini, zai↔zhipu, togetherai↔together,\n * fireworks-ai↔fireworks, amazon-bedrock↔bedrock, google-vertex↔vertex). The RUNTIME mapping mirrors the\n * maintenance script's table; targets resolve against the CATALOG entries (id + aliases — the same namespace\n * the vendored index uses) first, then the registry.\n */\nconst MODELS_DEV_ID_MAP: Record<string, string> = {\n google: \"google-gemini\",\n zai: \"zhipu\",\n togetherai: \"together\",\n \"fireworks-ai\": \"fireworks\",\n \"amazon-bedrock\": \"bedrock\",\n \"google-vertex\": \"vertex\",\n};\n\nlet _catalogTargets: Map<string, { keys: string[] }> | undefined;\n/** external-id → the index keys (entry id + aliases) its models patch under. Lazy; catalog-first. */\nfunction catalogTargets(): Map<string, { keys: string[] }> {\n if (_catalogTargets !== undefined) return _catalogTargets;\n _catalogTargets = new Map();\n try {\n for (const entry of Object.values(loadProviderCatalog())) {\n const keys = [entry.id, ...(entry.aliases ?? [])];\n for (const k of keys) {\n if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });\n }\n }\n } catch {\n // catalog unavailable — registry fallback below still works\n }\n return _catalogTargets;\n}\n\nfunction resolvePatchKeys(externalId: string): string[] | undefined {\n const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;\n const fromCatalog = catalogTargets().get(mapped);\n if (fromCatalog !== undefined) return fromCatalog.keys;\n const profile = getProviderProfile(mapped);\n if (profile !== undefined) return [profile.name, ...(profile.aliases ?? [])];\n return undefined;\n}\n\n/** Parse + patch the index from an api.json payload. Unknown providers are skipped with WARN (once each). */\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: validates and merges an UNTRUSTED upstream payload (models.dev api.json) shape by shape, dropping a single bad model rather than the file. Each branch is a distinct malformed input; merging them loses which one was seen.\nfunction patchIndexFromApiJson(raw: unknown): number {\n if (typeof raw !== \"object\" || raw === null) return 0;\n let patched = 0;\n const skipped: string[] = [];\n for (const [providerId, provider] of Object.entries(raw as Record<string, unknown>)) {\n const models = (provider as { models?: Record<string, unknown> })?.models;\n if (models === undefined || typeof models !== \"object\") continue;\n // Enrich ONLY providers the SDK knows — models.dev's npm/api fields cannot be mapped to a theokit\n // apiMode/authType safely, so unknown providers are data we cannot route.\n const keys = resolvePatchKeys(providerId);\n if (keys === undefined) {\n skipped.push(providerId);\n continue;\n }\n for (const [modelId, rawModel] of Object.entries(models)) {\n const parsed = catalogModelSchema.safeParse(rawModel);\n if (!parsed.success) continue; // malformed model — drop silently (live data, additive drift expected)\n for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);\n patched++;\n }\n }\n if (skipped.length > 0) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh skipped ${skipped.length} unknown provider(s) (e.g. ${skipped.slice(0, 3).join(\", \")})\\n`,\n );\n }\n return patched;\n}\n\n/**\n * Load an existing disk cache into the index (called by refresh when fresh, or opportunistically by a\n * consumer at startup — NEVER fetches). Corrupt cache → delete + fall through to vendored data.\n */\nexport function loadCacheIntoIndex(url: string = DEFAULT_URL): number {\n const path = cachePathFor(url);\n let body: string;\n try {\n body = readFileSync(path, \"utf-8\");\n } catch {\n return 0; // no cache — vendored data only\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n // corrupt cache: delete and fall through to the vendored catalog.\n // M44 L9 fix — only a PARSE failure is cache corruption; a patch error must never delete a valid cache.\n try {\n unlinkSync(path);\n } catch {\n // best effort\n }\n diag(`[theokit-sdk] WARN: corrupt models-dev cache deleted (${path})\\n`);\n return 0;\n }\n try {\n return patchIndexFromApiJson(parsed);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache patch failed (${(err as Error).message})\\n`);\n return 0;\n }\n}\n\n/**\n * The kill switch, read from the environment.\n *\n * Truthy-only by design (M44 L11): a presence check would treat `THEOKIT_DISABLE_MODELS_FETCH=0`\n * and `=false` as \"disabled\", which is the opposite of what anyone writing them means.\n */\nfunction fetchDisabledByEnv(): boolean {\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n return kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\";\n}\n\n/**\n * The TTL gate: a cache file younger than {@link TTL_MS} serves without touching the network.\n *\n * Returns `undefined` when there is no usable cache — including when `statSync` throws, which is\n * how \"no cache file\" arrives. That is the ONE failure this step owns, and its fallback is simply\n * to let the caller proceed to the fetch.\n */\nfunction servedFromFreshCache(\n url: string,\n path: string,\n now: () => number,\n): RefreshModelCatalogResult | undefined {\n try {\n if (now() - statSync(path).mtimeMs >= TTL_MS) return undefined;\n } catch {\n return undefined; // no cache — proceed to fetch\n }\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n}\n\n/**\n * Fetch the catalog, bound its size, and prove it parses before anyone persists it.\n *\n * Returns `undefined` after logging when ANY of that fails — timeout, non-2xx, oversize, unparseable\n * body. The fallback this step owns is \"serve what we already have\", and the caller applies it.\n * Splitting the step from its fallback was the objection recorded in the suppression this replaces;\n * the fallback is not separated, it is named — `undefined` means \"this step could not produce a\n * body\", and there is exactly one thing to do about that.\n */\nasync function fetchCatalogBody(url: string, fetchImpl: typeof fetch): Promise<string | undefined> {\n try {\n const res = await Retry.run(\n async () => {\n const r = await fetchImpl(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n return r;\n },\n // 2 transient retries with backoff; every error here is worth one more try —\n // the whole call is already fail-closed at the caller.\n { retries: 2, isRetryable: () => true, initialDelayMs: 200 },\n );\n const declaredLength = Number(res.headers.get(\"content-length\") ?? Number.NaN);\n if (Number.isFinite(declaredLength) && declaredLength > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${declaredLength} bytes declared`);\n }\n const body = await res.text();\n // Checked again after reading: `content-length` is the server's claim, and a server that\n // omits it or lies about it is exactly the one worth bounding. Both checks are cheap and\n // neither alone is sufficient.\n if (body.length > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${body.length} bytes received`);\n }\n JSON.parse(body); // validate before persisting — never cache garbage\n return body;\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return undefined;\n }\n}\n\n/**\n * Persist the fetched body and patch it into the index.\n *\n * Two independent failures with two different consequences, which is why they are two try blocks\n * and not one: a cache write that fails costs the NEXT process a fetch and nothing more, so the run\n * continues; a patch that fails means this body never reached the index, so the index is whatever it\n * was and the result says `cache`.\n */\nfunction persistAndPatch(path: string, body: string): RefreshModelCatalogResult {\n try {\n writeCacheAtomic(path, body);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache write failed (${(err as Error).message})\\n`);\n }\n try {\n return { source: \"network\", models: patchIndexFromApiJson(JSON.parse(body)) };\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev patch failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return { source: \"cache\", models: 0 };\n }\n}\n\n/**\n * Explicitly refresh the model catalog from models.dev (the ONLY network trigger in the subsystem).\n * Fail-closed: any failure keeps serving the current index (cache or vendored). Kill-switch:\n * `THEOKIT_DISABLE_MODELS_FETCH`.\n *\n * The sequence carried a cognitive-complexity suppression whose reason said splitting it would\n * \"separate a step from the fallback it owns\". The four helpers above each KEEP their fallback: the\n * TTL gate owns \"no cache\", the fetch owns every network and validation failure, the persist owns\n * the write and the patch. What is left here is the order they run in, which is what this function\n * was always for.\n *\n * Still true, and NOT fixed by the split: three of the paths return `{ source: \"cache\" }`, so a\n * caller cannot tell a timeout from an unparseable body from a patch failure. Distinguishing them\n * means adding a field to the PUBLIC `RefreshModelCatalogResult`, which is a release decision rather\n * than a refactor. The `diag` line already names the cause for an operator.\n */\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works\n // standalone (without the consumer having built an Agent first).\n registerBuiltins();\n if (fetchDisabledByEnv()) return { source: \"skipped\", models: 0 };\n\n const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;\n const path = cachePathFor(url);\n const now = opts.deps?.now ?? (() => Date.now());\n\n if (opts.force !== true) {\n const cached = servedFromFreshCache(url, path, now);\n if (cached !== undefined) return cached;\n }\n\n const body = await fetchCatalogBody(url, boundFetch(opts.deps?.fetch));\n // fail-closed: serve whatever we already have (stale cache if present, else vendored)\n if (body === undefined) return { source: \"cache\", models: loadCacheIntoIndex(url) };\n\n return persistAndPatch(path, body);\n}\n\n/** The enriched per-model view (public via `@theokit/sdk/models`): index lookup by (possibly prefixed) id. */\nexport function getModelInfo(modelId: string): ReturnType<typeof getCatalogModelInfo> {\n return getCatalogModelInfo(modelId);\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/llm/model-option.ts","../src/internal/providers/catalog-source-models-dev.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,IAAM,QAAA,mBAAW,IAAI,GAAA,CAAI,CAAC,KAAA,EAAO,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,IAAI,CAAC,CAAA;AAE7E,SAAS,YAAY,KAAA,EAAuB;AAC1C,EAAA,IAAI,QAAA,CAAS,IAAI,KAAA,CAAM,WAAA,EAAa,CAAA,EAAG,OAAO,MAAM,WAAA,EAAY;AAChE,EAAA,OAAO,KAAA,CAAM,OAAO,CAAC,CAAA,CAAE,aAAY,GAAI,KAAA,CAAM,MAAM,CAAC,CAAA;AACtD;AAeO,SAAS,kBAAkB,OAAA,EAAyB;AACzD,EAAA,MAAM,EAAE,IAAA,EAAK,GAAI,YAAA,CAAa,OAAO,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,EAAA;AAC9B,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,OAAA,CAAQ,GAAG,CAAA;AAU9B,EAAA,MAAM,IAAA,GAAO,oBAAoB,KAAA,IAAS,CAAA,GAAI,KAAK,KAAA,CAAM,CAAA,EAAG,KAAK,CAAA,GAAI,IAAI,CAAA;AACzE,EAAA,MAAM,UAAU,KAAA,IAAS,CAAA,GAAI,KAAK,KAAA,CAAM,KAAA,GAAQ,CAAC,CAA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AAErE,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,EAAE,QAAQ,OAAA,EAAS,MAAA,EAAQ,kBAAA,CAAmB,GAAG,CAAA,EAAE;AAElF,EAAA,OAAO,eAAA,CAAgB,MAAM,IAAI,CAAA;AACnC;AAGO,SAAS,aAAa,OAAA,EAAyD;AACpF,EAAA,OAAO,oBAAoB,OAAO,CAAA;AACpC","file":"models.js","sourcesContent":["import { parseModelId } from \"./model-identifier.js\";\n\n/**\n * A UI-friendly model option — the shape a `<select>`/dropdown consumes.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport interface ModelOption {\n /** The original model id (what you pass back to the SDK). */\n value: string;\n /** Best-effort human label (see {@link humanizeModelName}). */\n label: string;\n /** Provider from the slug prefix, or `undefined` when none. */\n provider: string | undefined;\n}\n\n/** Tokens rendered upper-case rather than title-case. */\nconst ACRONYMS = new Set([\"gpt\", \"ai\", \"hd\", \"ui\", \"api\", \"sdk\", \"llm\", \"xl\"]);\n\nfunction prettyToken(token: string): string {\n if (ACRONYMS.has(token.toLowerCase())) return token.toUpperCase();\n return token.charAt(0).toUpperCase() + token.slice(1);\n}\n\n/**\n * Turn a model id into a best-effort human label: strip the routing/vendor\n * prefix to the core model segment, split on `-`/`_`/`.`/whitespace, title-case\n * each token (known acronyms upper-cased), and append an OpenRouter `:variant`\n * in parentheses. Deterministic, pure, dependency-free.\n *\n * Best-effort, NOT vendor-canonical: `\"anthropic/claude-3-5-sonnet\"` →\n * `\"Claude 3 5 Sonnet\"`. A UI wanting exact marketing names overrides per id.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function humanizeModelName(modelId: string): string {\n const { name } = parseModelId(modelId);\n if (name.length === 0) return \"\";\n const colon = name.indexOf(\":\");\n // Strip a trailing slash so a typo'd `gpt-4o/` keeps its name (not lost to an\n // empty last segment).\n //\n // Done by index rather than with `/\\/+$/`, and the difference is not stylistic: that pattern\n // consumes slashes to the end of the string at every start position and then backtracks\n // looking for an end-anchor that is not there (CodeQL js/polynomial-redos #6). This function\n // is `@public` and takes a caller-supplied model id. Measured on a run of slashes followed by\n // one other character: 25_000 took 496 ms, 100_000 took 31_305 ms — half a minute of pinned\n // CPU to render a label. Walking back from the end is linear and cannot backtrack.\n const base = trimTrailingSlashes(colon >= 0 ? name.slice(0, colon) : name);\n const variant = colon >= 0 ? name.slice(colon + 1) : \"\";\n const lastSlash = base.lastIndexOf(\"/\");\n const core = lastSlash >= 0 ? base.slice(lastSlash + 1) : base;\n const label = core\n .split(/[-_.\\s]+/)\n .filter((t) => t.length > 0)\n .map(prettyToken)\n .join(\" \");\n if (label.length === 0) return variant; // no base label (e.g. \":free\") → bare variant\n return variant.length > 0 ? `${label} (${variant})` : label;\n}\n\n/**\n * Build a {@link ModelOption} (`{ value, label, provider }`) for a model id —\n * a dropdown-ready entry composing {@link humanizeModelName} + `parseModelId`.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function toModelOption(modelId: string): ModelOption {\n return {\n value: modelId,\n label: humanizeModelName(modelId),\n provider: parseModelId(modelId).provider,\n };\n}\n\nconst SLASH_CODE = 47; // \"/\"\n\n/** Removes trailing `/` characters in one linear pass. See the call site for why not a regex. */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === SLASH_CODE) end--;\n return end === value.length ? value : value.slice(0, end);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { Retry } from \"../../retry.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { boundFetch } from \"../runtime-fetch.js\";\nimport { registerBuiltins } from \"./builtin/index.js\";\nimport { getCatalogModelInfo, loadProviderCatalog, patchModelInfo } from \"./catalog-loader.js\";\nimport { catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile } from \"./registry.js\";\n\n/**\n * M44 — the OPTIONAL models.dev catalog source. Explicit opt-in ONLY (`refreshModelCatalog()`): the SDK\n * NEVER fetches at startup or per-request — the vendored catalog + any existing disk cache are the offline\n * base, and every failure mode fails CLOSED back to them (ROADMAP constraint: no runtime hard network dep).\n *\n * The models.dev consumption mechanism:\n * disk cache with mtime TTL, atomic tempfile+rename write, corrupt-cache delete-and-fall-through, kill-switch\n * env. Library adaptations: NO background refresh loop (a consumer composes refresh with the SDK's cron);\n * TTL 1h (not 5min — no background refresher to keep it warm); no cross-process flock v1 (atomic rename +\n * idempotent upstream content — at most one wasted fetch).\n *\n * @internal (the public surface is `refreshModelCatalog` re-exported via `@theokit/sdk/models`)\n */\n\nconst DEFAULT_URL = \"https://models.dev/api.json\";\n\n/**\n * Ceiling on a fetched catalog, before it is parsed or written to the cache.\n *\n * The response body was read with `res.text()` and persisted with no bound, so a host serving a\n * multi-gigabyte document would have been materialised in memory and then written to disk. The\n * default URL is trusted, but `THEOKIT_MODELS_URL` lets an operator point this anywhere, and a\n * limit is the difference between \"we only fetch from a host we trust\" and \"we cannot be hurt by\n * one we do not\".\n *\n * 32 MiB is roughly 40x the real catalog (~800 KiB in 2026-08), so it bounds the failure without\n * being a number anyone has to tune when models.dev grows.\n */\nconst MAX_CATALOG_BYTES = 32 * 1024 * 1024;\nconst TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FETCH_TIMEOUT_MS = 10_000;\n\n/**\n * Arguments to `refreshModelCatalog`, the SDK's only network trigger for model metadata.\n *\n * `url` wins over the `THEOKIT_MODELS_URL` environment variable, which in turn wins over\n * `https://models.dev/api.json`. A non-default URL gets its own cache file, named by a hash of\n * the URL, so switching sources never reads another source's cache.\n *\n * `force` skips only the freshness check — it does not skip the kill switch. When\n * `THEOKIT_DISABLE_MODELS_FETCH` is set to anything other than an empty string, `\"0\"` or\n * `\"false\"`, the call returns `source: \"skipped\"` with no fetch and no cache read, whatever\n * `force` says.\n *\n * Without `force`, a cache file whose mtime is under an hour old is served directly and no\n * request is made.\n *\n * `deps` exists so tests can drive the fetch and the clock; production leaves it unset.\n */\nexport interface RefreshModelCatalogOptions {\n /** Override the source URL (`THEOKIT_MODELS_URL` env also honored). */\n url?: string;\n /** Bypass the TTL freshness gate. */\n force?: boolean;\n /** Injected for tests. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\n/**\n * What `refreshModelCatalog` did. It never throws on a failed refresh, so this is the only place\n * the outcome is reported.\n *\n * `source` is `\"network\"` only when a request succeeded, its body parsed as JSON, and the models\n * were patched in. Every failure path — kill switch aside — returns `\"cache\"`: an HTTP error\n * after retries, a timeout, an unparseable body, or a patch that threw. `\"cache\"` therefore means\n * \"serving what was already there\", which may be a fresh cache, a stale one, or nothing but the\n * vendored catalog. Read `models` to tell those apart. `\"skipped\"` means the kill switch was set.\n *\n * `models` counts the models patched into the index during this call, not the catalog's size. It\n * counts each model once even when the provider has aliases and the model is written under several\n * index keys, and it excludes models whose payload failed schema validation and models under\n * providers the SDK does not know. It is 0 whenever there was no cache to fall back on, and 0 for\n * `\"skipped\"`.\n *\n * A cache write that fails is logged and otherwise ignored: the result can still say `\"network\"`\n * with the data live in memory and nothing on disk.\n */\nexport interface RefreshModelCatalogResult {\n /** Where the data came from: a fresh network fetch, the still-fresh disk cache, or skipped entirely. */\n source: \"network\" | \"cache\" | \"skipped\";\n /** How many models were patched into the index. */\n models: number;\n}\n\n/** The cache file for a source URL (custom URLs get a hash-suffixed name). */\nexport function cachePathFor(url: string): string {\n // M44 L8 fix — honor the SDK home override so tests and multi-home setups never touch the real ~/.theokit.\n const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), \".theokit\");\n const dir = join(base, \"cache\", \"models-dev\");\n if (url === DEFAULT_URL) return join(dir, \"api.json\");\n const hash = createHash(\"sha256\").update(url).digest(\"hex\").slice(0, 12);\n return join(dir, `api-${hash}.json`);\n}\n\n/** Atomic write: temp file + rename (crash mid-write never leaves a partial cache). */\nfunction writeCacheAtomic(path: string, body: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${randomBytes(6).toString(\"hex\")}`;\n try {\n writeFileSync(tmp, body);\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best effort\n }\n throw err;\n }\n}\n\n/**\n * M44 H3 fix — models.dev provider ids ≠ theokit ids (google↔google-gemini, zai↔zhipu, togetherai↔together,\n * fireworks-ai↔fireworks, amazon-bedrock↔bedrock, google-vertex↔vertex). The RUNTIME mapping mirrors the\n * maintenance script's table; targets resolve against the CATALOG entries (id + aliases — the same namespace\n * the vendored index uses) first, then the registry.\n */\nconst MODELS_DEV_ID_MAP: Record<string, string> = {\n google: \"google-gemini\",\n zai: \"zhipu\",\n togetherai: \"together\",\n \"fireworks-ai\": \"fireworks\",\n \"amazon-bedrock\": \"bedrock\",\n \"google-vertex\": \"vertex\",\n};\n\nlet _catalogTargets: Map<string, { keys: string[] }> | undefined;\n/** external-id → the index keys (entry id + aliases) its models patch under. Lazy; catalog-first. */\nfunction catalogTargets(): Map<string, { keys: string[] }> {\n if (_catalogTargets !== undefined) return _catalogTargets;\n _catalogTargets = new Map();\n try {\n for (const entry of Object.values(loadProviderCatalog())) {\n const keys = [entry.id, ...(entry.aliases ?? [])];\n for (const k of keys) {\n if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });\n }\n }\n } catch {\n // catalog unavailable — registry fallback below still works\n }\n return _catalogTargets;\n}\n\nfunction resolvePatchKeys(externalId: string): string[] | undefined {\n const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;\n const fromCatalog = catalogTargets().get(mapped);\n if (fromCatalog !== undefined) return fromCatalog.keys;\n const profile = getProviderProfile(mapped);\n if (profile !== undefined) return [profile.name, ...(profile.aliases ?? [])];\n return undefined;\n}\n\n/** Parse + patch the index from an api.json payload. Unknown providers are skipped with WARN (once each). */\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: validates and merges an UNTRUSTED upstream payload (models.dev api.json) shape by shape, dropping a single bad model rather than the file. Each branch is a distinct malformed input; merging them loses which one was seen.\nfunction patchIndexFromApiJson(raw: unknown): number {\n if (typeof raw !== \"object\" || raw === null) return 0;\n let patched = 0;\n const skipped: string[] = [];\n for (const [providerId, provider] of Object.entries(raw as Record<string, unknown>)) {\n const models = (provider as { models?: Record<string, unknown> })?.models;\n if (models === undefined || typeof models !== \"object\") continue;\n // Enrich ONLY providers the SDK knows — models.dev's npm/api fields cannot be mapped to a theokit\n // apiMode/authType safely, so unknown providers are data we cannot route.\n const keys = resolvePatchKeys(providerId);\n if (keys === undefined) {\n skipped.push(providerId);\n continue;\n }\n for (const [modelId, rawModel] of Object.entries(models)) {\n const parsed = catalogModelSchema.safeParse(rawModel);\n if (!parsed.success) continue; // malformed model — drop silently (live data, additive drift expected)\n for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);\n patched++;\n }\n }\n if (skipped.length > 0) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh skipped ${skipped.length} unknown provider(s) (e.g. ${skipped.slice(0, 3).join(\", \")})\\n`,\n );\n }\n return patched;\n}\n\n/**\n * Load an existing disk cache into the index (called by refresh when fresh, or opportunistically by a\n * consumer at startup — NEVER fetches). Corrupt cache → delete + fall through to vendored data.\n */\nexport function loadCacheIntoIndex(url: string = DEFAULT_URL): number {\n const path = cachePathFor(url);\n let body: string;\n try {\n body = readFileSync(path, \"utf-8\");\n } catch {\n return 0; // no cache — vendored data only\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n // corrupt cache: delete and fall through to the vendored catalog.\n // M44 L9 fix — only a PARSE failure is cache corruption; a patch error must never delete a valid cache.\n try {\n unlinkSync(path);\n } catch {\n // best effort\n }\n diag(`[theokit-sdk] WARN: corrupt models-dev cache deleted (${path})\\n`);\n return 0;\n }\n try {\n return patchIndexFromApiJson(parsed);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache patch failed (${(err as Error).message})\\n`);\n return 0;\n }\n}\n\n/**\n * The kill switch, read from the environment.\n *\n * Truthy-only by design (M44 L11): a presence check would treat `THEOKIT_DISABLE_MODELS_FETCH=0`\n * and `=false` as \"disabled\", which is the opposite of what anyone writing them means.\n */\nfunction fetchDisabledByEnv(): boolean {\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n return kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\";\n}\n\n/**\n * The TTL gate: a cache file younger than {@link TTL_MS} serves without touching the network.\n *\n * Returns `undefined` when there is no usable cache — including when `statSync` throws, which is\n * how \"no cache file\" arrives. That is the ONE failure this step owns, and its fallback is simply\n * to let the caller proceed to the fetch.\n */\nfunction servedFromFreshCache(\n url: string,\n path: string,\n now: () => number,\n): RefreshModelCatalogResult | undefined {\n try {\n if (now() - statSync(path).mtimeMs >= TTL_MS) return undefined;\n } catch {\n return undefined; // no cache — proceed to fetch\n }\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n}\n\n/**\n * Fetch the catalog, bound its size, and prove it parses before anyone persists it.\n *\n * Returns `undefined` after logging when ANY of that fails — timeout, non-2xx, oversize, unparseable\n * body. The fallback this step owns is \"serve what we already have\", and the caller applies it.\n * Splitting the step from its fallback was the objection recorded in the suppression this replaces;\n * the fallback is not separated, it is named — `undefined` means \"this step could not produce a\n * body\", and there is exactly one thing to do about that.\n */\nasync function fetchCatalogBody(url: string, fetchImpl: typeof fetch): Promise<string | undefined> {\n try {\n const res = await Retry.run(\n async () => {\n const r = await fetchImpl(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n return r;\n },\n // 2 transient retries with backoff; every error here is worth one more try —\n // the whole call is already fail-closed at the caller.\n { retries: 2, isRetryable: () => true, initialDelayMs: 200 },\n );\n const declaredLength = Number(res.headers.get(\"content-length\") ?? Number.NaN);\n if (Number.isFinite(declaredLength) && declaredLength > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${declaredLength} bytes declared`);\n }\n const body = await res.text();\n // Checked again after reading: `content-length` is the server's claim, and a server that\n // omits it or lies about it is exactly the one worth bounding. Both checks are cheap and\n // neither alone is sufficient.\n if (body.length > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${body.length} bytes received`);\n }\n JSON.parse(body); // validate before persisting — never cache garbage\n return body;\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return undefined;\n }\n}\n\n/**\n * Persist the fetched body and patch it into the index.\n *\n * Two independent failures with two different consequences, which is why they are two try blocks\n * and not one: a cache write that fails costs the NEXT process a fetch and nothing more, so the run\n * continues; a patch that fails means this body never reached the index, so the index is whatever it\n * was and the result says `cache`.\n */\nfunction persistAndPatch(path: string, body: string): RefreshModelCatalogResult {\n try {\n writeCacheAtomic(path, body);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache write failed (${(err as Error).message})\\n`);\n }\n try {\n return { source: \"network\", models: patchIndexFromApiJson(JSON.parse(body)) };\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev patch failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return { source: \"cache\", models: 0 };\n }\n}\n\n/**\n * Explicitly refresh the model catalog from models.dev (the ONLY network trigger in the subsystem).\n * Fail-closed: any failure keeps serving the current index (cache or vendored). Kill-switch:\n * `THEOKIT_DISABLE_MODELS_FETCH`.\n *\n * The sequence carried a cognitive-complexity suppression whose reason said splitting it would\n * \"separate a step from the fallback it owns\". The four helpers above each KEEP their fallback: the\n * TTL gate owns \"no cache\", the fetch owns every network and validation failure, the persist owns\n * the write and the patch. What is left here is the order they run in, which is what this function\n * was always for.\n *\n * Still true, and NOT fixed by the split: three of the paths return `{ source: \"cache\" }`, so a\n * caller cannot tell a timeout from an unparseable body from a patch failure. Distinguishing them\n * means adding a field to the PUBLIC `RefreshModelCatalogResult`, which is a release decision rather\n * than a refactor. The `diag` line already names the cause for an operator.\n */\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works\n // standalone (without the consumer having built an Agent first).\n registerBuiltins();\n if (fetchDisabledByEnv()) return { source: \"skipped\", models: 0 };\n\n const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;\n const path = cachePathFor(url);\n const now = opts.deps?.now ?? (() => Date.now());\n\n if (opts.force !== true) {\n const cached = servedFromFreshCache(url, path, now);\n if (cached !== undefined) return cached;\n }\n\n const body = await fetchCatalogBody(url, boundFetch(opts.deps?.fetch));\n // fail-closed: serve whatever we already have (stale cache if present, else vendored)\n if (body === undefined) return { source: \"cache\", models: loadCacheIntoIndex(url) };\n\n return persistAndPatch(path, body);\n}\n\n/** The enriched per-model view (public via `@theokit/sdk/models`): index lookup by (possibly prefixed) id. */\nexport function getModelInfo(modelId: string): ReturnType<typeof getCatalogModelInfo> {\n return getCatalogModelInfo(modelId);\n}\n"]}