@theokit/sdk 4.52.1 → 4.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/{agent-U2R2R5JP.cjs → agent-JX5SBYDE.cjs} +13 -12
  3. package/dist/{agent-U2R2R5JP.cjs.map → agent-JX5SBYDE.cjs.map} +1 -1
  4. package/dist/{agent-RDHK6MVT.js → agent-ZAGG6ZBS.js} +12 -11
  5. package/dist/{agent-RDHK6MVT.js.map → agent-ZAGG6ZBS.js.map} +1 -1
  6. package/dist/auth/index.cjs +26 -25
  7. package/dist/auth/index.cjs.map +1 -1
  8. package/dist/auth/index.js +3 -2
  9. package/dist/auth/index.js.map +1 -1
  10. package/dist/chunk-23VZBRDQ.js +147 -0
  11. package/dist/chunk-23VZBRDQ.js.map +1 -0
  12. package/dist/{chunk-CY7MIMI4.cjs → chunk-2QMK627M.cjs} +3 -3
  13. package/dist/{chunk-CY7MIMI4.cjs.map → chunk-2QMK627M.cjs.map} +1 -1
  14. package/dist/{chunk-6GS7JI64.cjs → chunk-2VFZQEDW.cjs} +56 -56
  15. package/dist/{chunk-6GS7JI64.cjs.map → chunk-2VFZQEDW.cjs.map} +1 -1
  16. package/dist/{chunk-M5EK7N6R.js → chunk-2Y5NO2SY.js} +4 -4
  17. package/dist/{chunk-M5EK7N6R.js.map → chunk-2Y5NO2SY.js.map} +1 -1
  18. package/dist/{chunk-V2EJLKGA.js → chunk-2YWWPCGX.js} +4 -3
  19. package/dist/chunk-2YWWPCGX.js.map +1 -0
  20. package/dist/chunk-33L2NVTJ.cjs +177 -0
  21. package/dist/chunk-33L2NVTJ.cjs.map +1 -0
  22. package/dist/{chunk-GNPI5IWZ.js → chunk-3SHW7XKK.js} +3 -3
  23. package/dist/{chunk-GNPI5IWZ.js.map → chunk-3SHW7XKK.js.map} +1 -1
  24. package/dist/{chunk-J4RY5DTI.js → chunk-634YVZLU.js} +3 -3
  25. package/dist/{chunk-J4RY5DTI.js.map → chunk-634YVZLU.js.map} +1 -1
  26. package/dist/{chunk-T6ZCG5AP.cjs → chunk-BC5EUG7R.cjs} +7 -6
  27. package/dist/chunk-BC5EUG7R.cjs.map +1 -0
  28. package/dist/{chunk-WLESQ3ZQ.cjs → chunk-DM6Y5B2G.cjs} +21 -21
  29. package/dist/{chunk-WLESQ3ZQ.cjs.map → chunk-DM6Y5B2G.cjs.map} +1 -1
  30. package/dist/{chunk-NACDF3PK.js → chunk-HTK54K2J.js} +3 -3
  31. package/dist/{chunk-SDJYLCJK.cjs.map → chunk-HTK54K2J.js.map} +1 -1
  32. package/dist/{chunk-42PLABFU.js → chunk-I5OTK2RP.js} +3 -3
  33. package/dist/{chunk-42PLABFU.js.map → chunk-I5OTK2RP.js.map} +1 -1
  34. package/dist/chunk-NUEL6RCZ.cjs +155 -0
  35. package/dist/chunk-NUEL6RCZ.cjs.map +1 -0
  36. package/dist/{chunk-KELIQH7K.js → chunk-NZOR3N4E.js} +11 -11
  37. package/dist/{chunk-KELIQH7K.js.map → chunk-NZOR3N4E.js.map} +1 -1
  38. package/dist/{chunk-ZNEE4WWQ.cjs → chunk-QN5N3ZVT.cjs} +5 -5
  39. package/dist/{chunk-ZNEE4WWQ.cjs.map → chunk-QN5N3ZVT.cjs.map} +1 -1
  40. package/dist/{chunk-OI6RHLGC.cjs → chunk-T5ZWI3MC.cjs} +5 -5
  41. package/dist/{chunk-OI6RHLGC.cjs.map → chunk-T5ZWI3MC.cjs.map} +1 -1
  42. package/dist/{chunk-SDJYLCJK.cjs → chunk-TR4V2LHV.cjs} +3 -3
  43. package/dist/chunk-TR4V2LHV.cjs.map +1 -0
  44. package/dist/chunk-XRI6DXPZ.js +171 -0
  45. package/dist/chunk-XRI6DXPZ.js.map +1 -0
  46. package/dist/{compact-session-FBVWO6B3.cjs → compact-session-6GKIS4SD.cjs} +15 -14
  47. package/dist/{compact-session-FBVWO6B3.cjs.map → compact-session-6GKIS4SD.cjs.map} +1 -1
  48. package/dist/{compact-session-XLXC2CZN.js → compact-session-EJ36VH5I.js} +7 -6
  49. package/dist/{compact-session-XLXC2CZN.js.map → compact-session-EJ36VH5I.js.map} +1 -1
  50. package/dist/cron.cjs +12 -11
  51. package/dist/cron.js +11 -10
  52. package/dist/eval.cjs +15 -14
  53. package/dist/eval.cjs.map +1 -1
  54. package/dist/eval.js +11 -10
  55. package/dist/eval.js.map +1 -1
  56. package/dist/fs-session-store-LIKYT24K.js +10 -0
  57. package/dist/{fs-session-store-2TF3ZWMT.js.map → fs-session-store-LIKYT24K.js.map} +1 -1
  58. package/dist/{fs-session-store-TL4RJTXZ.cjs → fs-session-store-VXXDIBGM.cjs} +5 -5
  59. package/dist/{fs-session-store-TL4RJTXZ.cjs.map → fs-session-store-VXXDIBGM.cjs.map} +1 -1
  60. package/dist/index.cjs +42 -41
  61. package/dist/index.cjs.map +1 -1
  62. package/dist/index.js +13 -12
  63. package/dist/index.js.map +1 -1
  64. package/dist/{inject-session-UBAQ7I3G.cjs → inject-session-67SF65FC.cjs} +4 -4
  65. package/dist/{inject-session-UBAQ7I3G.cjs.map → inject-session-67SF65FC.cjs.map} +1 -1
  66. package/dist/{inject-session-UEH5MAKU.js → inject-session-HO7FYVCX.js} +3 -3
  67. package/dist/{inject-session-UEH5MAKU.js.map → inject-session-HO7FYVCX.js.map} +1 -1
  68. package/dist/internal/mcp/oauth.d.ts +1 -0
  69. package/dist/internal/mcp/token-storage.d.ts +1 -0
  70. package/dist/internal/persistence/index.cjs +6 -6
  71. package/dist/internal/persistence/index.js +1 -1
  72. package/dist/internal/persistence/transcript-ops.d.cts +6 -7
  73. package/dist/internal/persistence/transcript-ops.d.ts +6 -7
  74. package/dist/mcp-auth.cjs +299 -0
  75. package/dist/mcp-auth.cjs.map +1 -0
  76. package/dist/mcp-auth.d.cts +17 -0
  77. package/dist/mcp-auth.d.ts +17 -0
  78. package/dist/mcp-auth.js +292 -0
  79. package/dist/mcp-auth.js.map +1 -0
  80. package/dist/models.cjs +11 -10
  81. package/dist/models.cjs.map +1 -1
  82. package/dist/models.js +3 -2
  83. package/dist/models.js.map +1 -1
  84. package/dist/persistence.cjs +16 -7
  85. package/dist/persistence.cjs.map +1 -1
  86. package/dist/persistence.js +11 -2
  87. package/dist/persistence.js.map +1 -1
  88. package/package.json +11 -1
  89. package/dist/chunk-BKRTYDVN.js +0 -312
  90. package/dist/chunk-BKRTYDVN.js.map +0 -1
  91. package/dist/chunk-NACDF3PK.js.map +0 -1
  92. package/dist/chunk-T6ZCG5AP.cjs.map +0 -1
  93. package/dist/chunk-V2EJLKGA.js.map +0 -1
  94. package/dist/chunk-XK54DTRF.cjs +0 -325
  95. package/dist/chunk-XK54DTRF.cjs.map +0 -1
  96. package/dist/fs-session-store-2TF3ZWMT.js +0 -10
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/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,a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,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,CAAA,EAAE;AAAA,EACtC;AACF;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 const base = (colon >= 0 ? name.slice(0, colon) : name).replace(/\\/+$/, \"\");\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","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 { 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 * Mechanism adapted from OpenCode's models.dev consumption (MIT © 2025 opencode — `core/src/models-dev.ts`):\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\";\nconst TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FETCH_TIMEOUT_MS = 10_000;\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\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, mirroring OpenCode). */\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: see the reason just above\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 (OpenCode's delete-and-fall-through).\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 * 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// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works standalone\n // (without the consumer having built an Agent first).\n registerBuiltins();\n // M44 L11 fix — presence-based would treat \"0\"/\"false\"/\"\" as disabled; only truthy values disable.\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n if (kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\") {\n 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 // TTL gate: a fresh cache serves without network (mtime freshness, OpenCode's gate).\n if (opts.force !== true) {\n try {\n const age = now() - statSync(path).mtimeMs;\n if (age < TTL_MS) {\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n }\n } catch {\n // no cache — proceed to fetch\n }\n }\n\n const fetchImpl = opts.deps?.fetch ?? fetch;\n let body: string;\n try {\n const res = await Retry.create(\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 (OpenCode does the same); 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 body = await res.text();\n JSON.parse(body); // validate before persisting — never cache garbage\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh failed (${(err as Error).message}) — serving existing data\\n`,\n );\n // fail-closed: serve whatever we already have (stale cache if present, else vendored)\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n }\n\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/** 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-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,K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,MAGA,EAAE,OAAA,EAAS,CAAA,EAAG,aAAa,MAAM,IAAA,EAAM,gBAAgB,GAAA;AAAI,KAC7D;AACA,IAAA,IAAA,GAAO,MAAM,IAAI,IAAA,EAAK;AACtB,IAAA,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EACjB,SAAS,GAAA,EAAK;AACZ,IAAA,IAAA;AAAA,MACE,CAAA,+CAAA,EAAmD,IAAc,OAAO,CAAA;AAAA;AAAA,KAC1E;AAEA,IAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,kBAAA,CAAmB,GAAG,CAAA,EAAE;AAAA,EAC5D;AAEA,EAAA,IAAI;AACF,IAAA,gBAAA,CAAiB,MAAM,IAAI,CAAA;AAAA,EAC7B,SAAS,GAAA,EAAK;AACZ,IAAA,IAAA,CAAK,CAAA,mDAAA,EAAuD,IAAc,OAAO,CAAA;AAAA,CAAK,CAAA;AAAA,EACxF;AACA,EAAA,IAAI;AACF,IAAA,OAAO,EAAE,QAAQ,SAAA,EAAW,MAAA,EAAQ,sBAAsB,IAAA,CAAK,KAAA,CAAM,IAAI,CAAC,CAAA,EAAE;AAAA,EAC9E,SAAS,GAAA,EAAK;AACZ,IAAA,IAAA;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;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 const base = (colon >= 0 ? name.slice(0, colon) : name).replace(/\\/+$/, \"\");\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","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 { 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 * Mechanism adapted from OpenCode's models.dev consumption (MIT © 2025 opencode — `core/src/models-dev.ts`):\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\";\nconst TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FETCH_TIMEOUT_MS = 10_000;\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\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, mirroring OpenCode). */\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: see the reason just above\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 (OpenCode's delete-and-fall-through).\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 * 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// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works standalone\n // (without the consumer having built an Agent first).\n registerBuiltins();\n // M44 L11 fix — presence-based would treat \"0\"/\"false\"/\"\" as disabled; only truthy values disable.\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n if (kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\") {\n 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 // TTL gate: a fresh cache serves without network (mtime freshness, OpenCode's gate).\n if (opts.force !== true) {\n try {\n const age = now() - statSync(path).mtimeMs;\n if (age < TTL_MS) {\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n }\n } catch {\n // no cache — proceed to fetch\n }\n }\n\n const fetchImpl = opts.deps?.fetch ?? fetch;\n let body: string;\n try {\n const res = await Retry.create(\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 (OpenCode does the same); 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 body = await res.text();\n JSON.parse(body); // validate before persisting — never cache garbage\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh failed (${(err as Error).message}) — serving existing data\\n`,\n );\n // fail-closed: serve whatever we already have (stale cache if present, else vendored)\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n }\n\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/** 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"]}
@@ -3,7 +3,7 @@
3
3
  var chunkPNVDQL5Y_cjs = require('./chunk-PNVDQL5Y.cjs');
4
4
  var chunkT6QUCG7L_cjs = require('./chunk-T6QUCG7L.cjs');
5
5
  var chunkECPL5RV6_cjs = require('./chunk-ECPL5RV6.cjs');
6
- var chunkSDJYLCJK_cjs = require('./chunk-SDJYLCJK.cjs');
6
+ var chunkTR4V2LHV_cjs = require('./chunk-TR4V2LHV.cjs');
7
7
  var chunkQLAWEGTZ_cjs = require('./chunk-QLAWEGTZ.cjs');
8
8
  var chunkYLQQX5W2_cjs = require('./chunk-YLQQX5W2.cjs');
9
9
  var chunk2CFEET3Y_cjs = require('./chunk-2CFEET3Y.cjs');
@@ -72,13 +72,22 @@ function readRawTail(path, want) {
72
72
  function nonEmptyLines(text) {
73
73
  return text.split("\n").filter((l) => l.trim().length > 0);
74
74
  }
75
+ function isMarkerRecord(line, marker) {
76
+ let record;
77
+ try {
78
+ record = JSON.parse(line);
79
+ } catch {
80
+ return false;
81
+ }
82
+ return record.subtype === marker || record.type === marker;
83
+ }
75
84
  function readJsonlTail(path, options = {}) {
76
85
  const want = options.maxRecords ?? Number.POSITIVE_INFINITY;
77
86
  const { lines, bytesRead } = readRawTail(path, want);
78
87
  let sel = lines;
79
88
  if (options.sinceMarker !== void 0) {
80
89
  const marker = options.sinceMarker;
81
- const idx = sel.findLastIndex((l) => l.includes(marker));
90
+ const idx = sel.findLastIndex((l) => isMarkerRecord(l, marker));
82
91
  if (idx >= 0) sel = sel.slice(idx + 1);
83
92
  }
84
93
  if (Number.isFinite(want)) sel = sel.slice(-want);
@@ -116,23 +125,23 @@ Object.defineProperty(exports, "transcriptRoot", {
116
125
  });
117
126
  Object.defineProperty(exports, "JsonlParseError", {
118
127
  enumerable: true,
119
- get: function () { return chunkSDJYLCJK_cjs.JsonlParseError; }
128
+ get: function () { return chunkTR4V2LHV_cjs.JsonlParseError; }
120
129
  });
121
130
  Object.defineProperty(exports, "appendJsonl", {
122
131
  enumerable: true,
123
- get: function () { return chunkSDJYLCJK_cjs.appendJsonl; }
132
+ get: function () { return chunkTR4V2LHV_cjs.appendJsonl; }
124
133
  });
125
134
  Object.defineProperty(exports, "loadJsonl", {
126
135
  enumerable: true,
127
- get: function () { return chunkSDJYLCJK_cjs.loadJsonl; }
136
+ get: function () { return chunkTR4V2LHV_cjs.loadJsonl; }
128
137
  });
129
138
  Object.defineProperty(exports, "readJsonlIds", {
130
139
  enumerable: true,
131
- get: function () { return chunkSDJYLCJK_cjs.readJsonlIds; }
140
+ get: function () { return chunkTR4V2LHV_cjs.readJsonlIds; }
132
141
  });
133
142
  Object.defineProperty(exports, "withFileLock", {
134
143
  enumerable: true,
135
- get: function () { return chunkSDJYLCJK_cjs.withFileLock; }
144
+ get: function () { return chunkTR4V2LHV_cjs.withFileLock; }
136
145
  });
137
146
  Object.defineProperty(exports, "applyWalWithFallback", {
138
147
  enumerable: true,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/persistence/session-artifacts.ts","../src/internal/persistence/transcript-ops.ts"],"names":["atomicWriteTempTarget","TheokitAgentError","readFileSync","openSync","writeSync","closeSync","statSync","readSync"],"mappings":";;;;;;;;;;;;;;AA6BO,SAAS,uBAAA,CACd,MACA,WAAA,EAC6B;AAE7B,EAAA,IAAI,KAAK,QAAA,CAAS,aAAa,CAAA,EAAG,OAAO,cAAc,gBAAA,GAAmB,MAAA;AAC1E,EAAA,IAAI,aAAa,OAAO,MAAA;AACxB,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,QAAQ,CAAA,EAAG,OAAO,YAAA;AACpC,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,cAAc,CAAA,EAAG,OAAO,aAAA;AAC1C,EAAA,IAAIA,uCAAA,CAAsB,IAAI,CAAA,KAAM,MAAA,EAAW,OAAO,MAAA;AACtD,EAAA,OAAO,MAAA;AACT;ACNO,IAAM,gBAAA,GAAN,cAA+BC,mCAAA,CAAkB;AAAA,EAGtD,YAAqB,IAAA,EAAc;AACjC,IAAA,KAAA;AAAA,MACE,qDAAqD,IAAI,CAAA,+JAAA,CAAA;AAAA,MAGzD,EAAE,IAAA,EAAM,wBAAA,EAA0B,WAAA,EAAa,KAAA;AAAM,KACvD;AANmB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAOrB;AAAA,EAPqB,IAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;A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MAAM,SAAS,OAAA,CAAQ,WAAA;AACvB,IAAA,MAAM,GAAA,GAAM,IAAI,aAAA,CAAc,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,MAAM,CAAC,CAAA;AACvD,IAAA,IAAI,OAAO,CAAA,EAAG,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,MAAM,CAAC,CAAA;AAAA,EACvC;AACA,EAAA,IAAI,MAAA,CAAO,SAAS,IAAI,CAAA,QAAS,GAAA,CAAI,KAAA,CAAM,CAAC,IAAI,CAAA;AAEhD,EAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,CAAC,MAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAM,CAAA;AAC7C,EAAA,OAAO,OAAA,CAAQ,WAAW,IAAA,GAAQ,MAAA,CAAO,OAAO,GAAA,EAAK,EAAE,SAAA,EAAW,CAAA,GAAY,GAAA;AAChF","file":"persistence.cjs","sourcesContent":["import { atomicWriteTempTarget } from \"./atomic-write.js\";\n\n/**\n * The kinds of file this SDK leaves in a project's transcript directory.\n *\n * - `transcript` — the session itself (`transcriptPath`).\n * - `writer-lock` — the cross-process writer lease (`session-writer.ts`, `<file>.writer.lock`).\n * - `lock-directory` — `withFileLock`'s companion, taken by `mkdir`, so it is a DIRECTORY.\n * - `temp` — what `replaceFileAtomic` leaves when a process dies between the open and the rename.\n */\nexport type SessionArtifact = \"transcript\" | \"writer-lock\" | \"lock-directory\" | \"temp\";\n\n/**\n * U-1 — what is this entry, if it is one of ours?\n *\n * The SDK writes four kinds of file into a project directory and reasons about none of them\n * afterwards: there is no retention, no collector, and there was no way even to ask what an entry\n * IS. A consumer wanting to reclaim disk had to re-derive the suffixes by reading this source — and\n * one did, which means a suffix changing here would have left its classifier silently mislabelling\n * files on a path that deletes them.\n *\n * This is deliberately NOT a garbage collector. Retention is policy — how many days, how many to\n * keep, which session is live, whether to delete at all — and policy belongs to the application,\n * which is the only one that can know. What belongs here is the half only the SDK can answer.\n *\n * `undefined` means \"not written by this SDK\", and it is the answer that matters most: a caller\n * deleting what it does not recognise is how an editor's swap file gets collected. The `temp` case\n * defers to {@link atomicWriteTempTarget} rather than matching `.tmp`, for exactly that reason.\n */\nexport function classifySessionArtifact(\n name: string,\n isDirectory: boolean,\n): SessionArtifact | undefined {\n // `withFileLock` takes its lock by `mkdir`, so the same name as a plain file is not ours.\n if (name.endsWith(\".jsonl.lock\")) return isDirectory ? \"lock-directory\" : undefined;\n if (isDirectory) return undefined;\n if (name.endsWith(\".jsonl\")) return \"transcript\";\n if (name.endsWith(\".writer.lock\")) return \"writer-lock\";\n if (atomicWriteTempTarget(name) !== undefined) return \"temp\";\n return undefined;\n}\n","/**\n * M81 — transcript operations the consumer was doing by hand INSIDE the framework's own store.\n *\n * ## What this replaces\n *\n * `agents/lib/session/backtrack.ts:188` (agent-builder) wrote straight into the session store with a\n * bare `writeFileSync` — no atomicity, no lock, no API. 243 lines re-implementing parse, cut and\n * write for a format the framework owns. The consumer is not at fault: nothing here was reachable.\n *\n * ## The rule that travels WITH the operation\n *\n * `rules/audit-trail-rotation.md § Session transcripts (M60)` defines a NEVER-delete list — the live\n * pointer, the most recent transcript, and any active registry entry. That rule lived in the\n * CONSUMER. Moving the operation here without moving the rule would ship an API able to destroy\n * exactly what the rule protects — the same shape of defect as M80's `reconcileUpdateGoalStatus`:\n * critical knowledge outside the module that needs it, applied by convention.\n *\n * So `forkTranscript` takes `liveSessionPaths` and refuses, with a TYPED error, to write over any of\n * them. The caller supplies the list because only the caller knows which session is live; the\n * enforcement lives here because that is where the write happens.\n *\n * @internal\n */\n\nimport { closeSync, openSync, readFileSync, readSync, statSync, writeSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — the target is a protected session (live pointer / most-recent transcript / active entry).\n *\n * Typed rather than a bare `Error` because the caller must distinguish \"this session is protected\"\n * from \"the disk is full\": the first is a correct refusal, the second is an incident.\n */\nexport class LiveSessionError extends TheokitAgentError {\n override readonly name = \"LiveSessionError\";\n\n constructor(readonly path: string) {\n super(\n `refusing to write over a live session transcript: ${path}. ` +\n \"Fork to a new id instead — the live pointer, the most recent transcript and any active \" +\n \"registry entry are never overwritten (audit-trail rotation, M60).\",\n { code: \"live_session_protected\", isRetryable: false },\n );\n }\n}\n\n/** Options for {@link forkTranscript}. */\nexport interface ForkTranscriptOptions {\n /** Keep records `[0, beforeRecordIndex)`. Omit to copy the whole transcript. */\n readonly beforeRecordIndex?: number;\n /**\n * Paths that must never be written over — the live pointer, the most recent transcript, any active\n * registry entry. The caller supplies them because only the caller knows which session is live.\n */\n readonly liveSessionPaths?: readonly string[];\n /**\n * M107 — permission bits for the created destination. Default: `0o600`.\n *\n * A transcript carries the conversation. Before M107 no mode was passed at all, so the file was\n * born `0o666 & ~umask` — measured `0o664` (group-WRITABLE) on a `umask 002` machine, `0o644` on\n * `umask 022`, `0o466` on `umask 0200`. This is a DEFAULT and not a required knob on purpose: a\n * knob would reach zero consumers by omission, which is the failure mode that matters.\n *\n * As with any `open` mode, the `umask` may still CLEAR bits — under `umask 0200` the result is\n * `0o400`. That is accepted: the invariant bought here is \"neither group nor others\", and `0o400`\n * satisfies it more strictly. The SDK deliberately does not `fchmod` the default back, because\n * that would hand back a bit the operator asked to remove.\n */\n readonly mode?: number;\n}\n\n/**\n * Copy `src` into `dst`, keeping the first `beforeRecordIndex` records. The SOURCE is never touched.\n *\n * Atomicity comes from `wx` (exclusive create): two concurrent forks to the same destination cannot\n * both succeed — the loser gets `EEXIST` rather than writing over a half-written file. That is also\n * why an existing destination is a refusal, not a silent overwrite: losing a transcript without an\n * error is the worst failure mode for an operation that touches user sessions.\n */\nexport function forkTranscript(\n src: string,\n dst: string,\n options: ForkTranscriptOptions = {},\n): void {\n for (const live of options.liveSessionPaths ?? []) {\n if (live === dst) throw new LiveSessionError(dst);\n }\n\n const lines = readFileSync(src, \"utf8\")\n .split(\"\\n\")\n .filter((l) => l.trim().length > 0);\n const kept =\n options.beforeRecordIndex === undefined ? lines : lines.slice(0, options.beforeRecordIndex);\n const body = kept.length > 0 ? `${kept.join(\"\\n\")}\\n` : \"\";\n\n // `wx` — fails with EEXIST instead of truncating. The exclusivity IS the concurrency guarantee,\n // and M107 only added the third argument: the mode. See `ForkTranscriptOptions.mode`.\n const fd = openSync(dst, \"wx\", options.mode ?? 0o600);\n try {\n writeSync(fd, body);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Options for {@link readJsonlTail}. */\nexport interface ReadJsonlTailOptions {\n /** Maximum records to return, counted from the END. */\n readonly maxRecords?: number;\n /** Stop once a line contains this marker (exclusive). */\n readonly sinceMarker?: string;\n /** Test-only: also report how many bytes were read, to prove the read is not whole-file. */\n readonly _stats?: boolean;\n}\n\nconst TAIL_CHUNK = 64 * 1024;\n\n/**\n * Reads chunks backwards until enough complete lines have accumulated.\n *\n * Extracted from `readJsonlTail` because the read loop and the record selection are two\n * responsibilities — and together they exceeded the complexity ceiling. The buffer's first line may\n * be cut in half when the read stopped before the start of the file; that is why it is discarded.\n */\nfunction readRawTail(path: string, want: number): { lines: string[]; bytesRead: number } {\n const size = statSync(path).size;\n const fd = openSync(path, \"r\");\n let bytesRead = 0;\n let tail = \"\";\n let pos = size;\n try {\n while (pos > 0) {\n const len = Math.min(TAIL_CHUNK, pos);\n pos -= len;\n const buf = Buffer.alloc(len);\n readSync(fd, buf, 0, len, pos);\n bytesRead += len;\n tail = buf.toString(\"utf8\") + tail;\n if (nonEmptyLines(tail).length > want) break;\n }\n } finally {\n closeSync(fd);\n }\n const lines = nonEmptyLines(tail);\n return { lines: pos > 0 ? lines.slice(1) : lines, bytesRead };\n}\n\n/** Non-empty lines, in file order. */\nfunction nonEmptyLines(text: string): string[] {\n return text.split(\"\\n\").filter((l) => l.trim().length > 0);\n}\n\n/**\n * Read the LAST records of a JSONL file without loading the whole thing.\n *\n * Reads fixed-size chunks backwards from EOF until enough newlines have been seen. A session\n * transcript grows without bound; loading megabytes to show the last three turns is the cost this\n * exists to avoid — and a `slice` over a full read would be that same cost with a better name.\n */\nexport function readJsonlTail<T = Record<string, unknown>>(\n path: string,\n options: ReadJsonlTailOptions = {},\n): T[] {\n const want = options.maxRecords ?? Number.POSITIVE_INFINITY;\n const { lines, bytesRead } = readRawTail(path, want);\n\n let sel = lines;\n if (options.sinceMarker !== undefined) {\n const marker = options.sinceMarker;\n const idx = sel.findLastIndex((l) => l.includes(marker));\n if (idx >= 0) sel = sel.slice(idx + 1);\n }\n if (Number.isFinite(want)) sel = sel.slice(-want);\n\n const out = sel.map((l) => JSON.parse(l) as T);\n return options._stats === true ? (Object.assign(out, { bytesRead }) as T[]) : out;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/persistence/session-artifacts.ts","../src/internal/persistence/transcript-ops.ts"],"names":["atomicWriteTempTarget","TheokitAgentError","readFileSync","openSync","writeSync","closeSync","statSync","readSync"],"mappings":";;;;;;;;;;;;;;AA6BO,SAAS,uBAAA,CACd,MACA,WAAA,EAC6B;AAE7B,EAAA,IAAI,KAAK,QAAA,CAAS,aAAa,CAAA,EAAG,OAAO,cAAc,gBAAA,GAAmB,MAAA;AAC1E,EAAA,IAAI,aAAa,OAAO,MAAA;AACxB,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,QAAQ,CAAA,EAAG,OAAO,YAAA;AACpC,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,cAAc,CAAA,EAAG,OAAO,aAAA;AAC1C,EAAA,IAAIA,uCAAA,CAAsB,IAAI,CAAA,KAAM,MAAA,EAAW,OAAO,MAAA;AACtD,EAAA,OAAO,MAAA;AACT;ACNO,IAAM,gBAAA,GAAN,cAA+BC,mCAAA,CAAkB;AAAA,EAGtD,YAAqB,IAAA,EAAc;AACjC,IAAA,KAAA;AAAA,MACE,qDAAqD,IAAI,CAAA,+JAAA,CAAA;AAAA,MAGzD,EAAE,IAAA,EAAM,wBAAA,EAA0B,WAAA,EAAa,KAAA;AAAM,KACvD;AANmB,IAAA,IAAA,CAAA,IAAA,GAAA,IAA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KAAY,MAAA,IAAU,MAAA,CAAO,IAAA,KAAS,MAAA;AACtD;AAEO,SAAS,aAAA,CACd,IAAA,EACA,OAAA,GAAgC,EAAC,EAC5B;AACL,EAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,UAAA,IAAc,MAAA,CAAO,iBAAA;AAC1C,EAAA,MAAM,EAAE,KAAA,EAAO,SAAA,EAAU,GAAI,WAAA,CAAY,MAAM,IAAI,CAAA;AAEnD,EAAA,IAAI,GAAA,GAAM,KAAA;AACV,EAAA,IAAI,OAAA,CAAQ,gBAAgB,MAAA,EAAW;AACrC,IAAA,MAAM,SAAS,OAAA,CAAQ,WAAA;AAOvB,IAAA,MAAM,GAAA,GAAM,IAAI,aAAA,CAAc,CAAC,MAAM,cAAA,CAAe,CAAA,EAAG,MAAM,CAAC,CAAA;AAC9D,IAAA,IAAI,OAAO,CAAA,EAAG,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,MAAM,CAAC,CAAA;AAAA,EACvC;AACA,EAAA,IAAI,MAAA,CAAO,SAAS,IAAI,CAAA,QAAS,GAAA,CAAI,KAAA,CAAM,CAAC,IAAI,CAAA;AAEhD,EAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,CAAC,MAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAM,CAAA;AAC7C,EAAA,OAAO,OAAA,CAAQ,WAAW,IAAA,GAAQ,MAAA,CAAO,OAAO,GAAA,EAAK,EAAE,SAAA,EAAW,CAAA,GAAY,GAAA;AAChF","file":"persistence.cjs","sourcesContent":["import { atomicWriteTempTarget } from \"./atomic-write.js\";\n\n/**\n * The kinds of file this SDK leaves in a project's transcript directory.\n *\n * - `transcript` — the session itself (`transcriptPath`).\n * - `writer-lock` — the cross-process writer lease (`session-writer.ts`, `<file>.writer.lock`).\n * - `lock-directory` — `withFileLock`'s companion, taken by `mkdir`, so it is a DIRECTORY.\n * - `temp` — what `replaceFileAtomic` leaves when a process dies between the open and the rename.\n */\nexport type SessionArtifact = \"transcript\" | \"writer-lock\" | \"lock-directory\" | \"temp\";\n\n/**\n * U-1 — what is this entry, if it is one of ours?\n *\n * The SDK writes four kinds of file into a project directory and reasons about none of them\n * afterwards: there is no retention, no collector, and there was no way even to ask what an entry\n * IS. A consumer wanting to reclaim disk had to re-derive the suffixes by reading this source — and\n * one did, which means a suffix changing here would have left its classifier silently mislabelling\n * files on a path that deletes them.\n *\n * This is deliberately NOT a garbage collector. Retention is policy — how many days, how many to\n * keep, which session is live, whether to delete at all — and policy belongs to the application,\n * which is the only one that can know. What belongs here is the half only the SDK can answer.\n *\n * `undefined` means \"not written by this SDK\", and it is the answer that matters most: a caller\n * deleting what it does not recognise is how an editor's swap file gets collected. The `temp` case\n * defers to {@link atomicWriteTempTarget} rather than matching `.tmp`, for exactly that reason.\n */\nexport function classifySessionArtifact(\n name: string,\n isDirectory: boolean,\n): SessionArtifact | undefined {\n // `withFileLock` takes its lock by `mkdir`, so the same name as a plain file is not ours.\n if (name.endsWith(\".jsonl.lock\")) return isDirectory ? \"lock-directory\" : undefined;\n if (isDirectory) return undefined;\n if (name.endsWith(\".jsonl\")) return \"transcript\";\n if (name.endsWith(\".writer.lock\")) return \"writer-lock\";\n if (atomicWriteTempTarget(name) !== undefined) return \"temp\";\n return undefined;\n}\n","/**\n * M81 — transcript operations the consumer was doing by hand INSIDE the framework's own store.\n *\n * ## What this replaces\n *\n * `agents/lib/session/backtrack.ts:188` (agent-builder) wrote straight into the session store with a\n * bare `writeFileSync` — no atomicity, no lock, no API. 243 lines re-implementing parse, cut and\n * write for a format the framework owns. The consumer is not at fault: nothing here was reachable.\n *\n * ## The rule that travels WITH the operation\n *\n * `rules/audit-trail-rotation.md § Session transcripts (M60)` defines a NEVER-delete list — the live\n * pointer, the most recent transcript, and any active registry entry. That rule lived in the\n * CONSUMER. Moving the operation here without moving the rule would ship an API able to destroy\n * exactly what the rule protects — the same shape of defect as M80's `reconcileUpdateGoalStatus`:\n * critical knowledge outside the module that needs it, applied by convention.\n *\n * So `forkTranscript` takes `liveSessionPaths` and refuses, with a TYPED error, to write over any of\n * them. The caller supplies the list because only the caller knows which session is live; the\n * enforcement lives here because that is where the write happens.\n *\n * @internal\n */\n\nimport { closeSync, openSync, readFileSync, readSync, statSync, writeSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — the target is a protected session (live pointer / most-recent transcript / active entry).\n *\n * Typed rather than a bare `Error` because the caller must distinguish \"this session is protected\"\n * from \"the disk is full\": the first is a correct refusal, the second is an incident.\n */\nexport class LiveSessionError extends TheokitAgentError {\n override readonly name = \"LiveSessionError\";\n\n constructor(readonly path: string) {\n super(\n `refusing to write over a live session transcript: ${path}. ` +\n \"Fork to a new id instead — the live pointer, the most recent transcript and any active \" +\n \"registry entry are never overwritten (audit-trail rotation, M60).\",\n { code: \"live_session_protected\", isRetryable: false },\n );\n }\n}\n\n/** Options for {@link forkTranscript}. */\nexport interface ForkTranscriptOptions {\n /** Keep records `[0, beforeRecordIndex)`. Omit to copy the whole transcript. */\n readonly beforeRecordIndex?: number;\n /**\n * Paths that must never be written over — the live pointer, the most recent transcript, any active\n * registry entry. The caller supplies them because only the caller knows which session is live.\n */\n readonly liveSessionPaths?: readonly string[];\n /**\n * M107 — permission bits for the created destination. Default: `0o600`.\n *\n * A transcript carries the conversation. Before M107 no mode was passed at all, so the file was\n * born `0o666 & ~umask` — measured `0o664` (group-WRITABLE) on a `umask 002` machine, `0o644` on\n * `umask 022`, `0o466` on `umask 0200`. This is a DEFAULT and not a required knob on purpose: a\n * knob would reach zero consumers by omission, which is the failure mode that matters.\n *\n * As with any `open` mode, the `umask` may still CLEAR bits — under `umask 0200` the result is\n * `0o400`. That is accepted: the invariant bought here is \"neither group nor others\", and `0o400`\n * satisfies it more strictly. The SDK deliberately does not `fchmod` the default back, because\n * that would hand back a bit the operator asked to remove.\n */\n readonly mode?: number;\n}\n\n/**\n * Copy `src` into `dst`, keeping the first `beforeRecordIndex` records. The SOURCE is never touched.\n *\n * Atomicity comes from `wx` (exclusive create): two concurrent forks to the same destination cannot\n * both succeed — the loser gets `EEXIST` rather than writing over a half-written file. That is also\n * why an existing destination is a refusal, not a silent overwrite: losing a transcript without an\n * error is the worst failure mode for an operation that touches user sessions.\n */\nexport function forkTranscript(\n src: string,\n dst: string,\n options: ForkTranscriptOptions = {},\n): void {\n for (const live of options.liveSessionPaths ?? []) {\n if (live === dst) throw new LiveSessionError(dst);\n }\n\n const lines = readFileSync(src, \"utf8\")\n .split(\"\\n\")\n .filter((l) => l.trim().length > 0);\n const kept =\n options.beforeRecordIndex === undefined ? lines : lines.slice(0, options.beforeRecordIndex);\n const body = kept.length > 0 ? `${kept.join(\"\\n\")}\\n` : \"\";\n\n // `wx` — fails with EEXIST instead of truncating. The exclusivity IS the concurrency guarantee,\n // and M107 only added the third argument: the mode. See `ForkTranscriptOptions.mode`.\n const fd = openSync(dst, \"wx\", options.mode ?? 0o600);\n try {\n writeSync(fd, body);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Options for {@link readJsonlTail}. */\nexport interface ReadJsonlTailOptions {\n /** Maximum records to return, counted from the END. */\n readonly maxRecords?: number;\n /** Stop once a line contains this marker (exclusive). */\n /**\n * Start the window AFTER the last record whose `subtype` (or `type`) equals this.\n *\n * Matched STRUCTURALLY since T2.5. It used to be `line.includes(marker)`, so any message\n * mentioning the marker in its text truncated the read — silently, with a successful return.\n */\n readonly sinceMarker?: string;\n /** Test-only: also report how many bytes were read, to prove the read is not whole-file. */\n readonly _stats?: boolean;\n}\n\nconst TAIL_CHUNK = 64 * 1024;\n\n/**\n * Reads chunks backwards until enough complete lines have accumulated.\n *\n * Extracted from `readJsonlTail` because the read loop and the record selection are two\n * responsibilities — and together they exceeded the complexity ceiling. The buffer's first line may\n * be cut in half when the read stopped before the start of the file; that is why it is discarded.\n */\nfunction readRawTail(path: string, want: number): { lines: string[]; bytesRead: number } {\n const size = statSync(path).size;\n const fd = openSync(path, \"r\");\n let bytesRead = 0;\n let tail = \"\";\n let pos = size;\n try {\n while (pos > 0) {\n const len = Math.min(TAIL_CHUNK, pos);\n pos -= len;\n const buf = Buffer.alloc(len);\n readSync(fd, buf, 0, len, pos);\n bytesRead += len;\n tail = buf.toString(\"utf8\") + tail;\n if (nonEmptyLines(tail).length > want) break;\n }\n } finally {\n closeSync(fd);\n }\n const lines = nonEmptyLines(tail);\n return { lines: pos > 0 ? lines.slice(1) : lines, bytesRead };\n}\n\n/** Non-empty lines, in file order. */\nfunction nonEmptyLines(text: string): string[] {\n return text.split(\"\\n\").filter((l) => l.trim().length > 0);\n}\n\n/**\n * Read the LAST records of a JSONL file without loading the whole thing.\n *\n * Reads fixed-size chunks backwards from EOF until enough newlines have been seen. A session\n * transcript grows without bound; loading megabytes to show the last three turns is the cost this\n * exists to avoid — and a `slice` over a full read would be that same cost with a better name.\n */\n\n/**\n * Whether a raw JSONL line IS the marker record, rather than a line that talks about it.\n *\n * Matches on the record's own discriminants (`subtype`, then `type`) — the fields that identify\n * what a record *is*. Free text is never consulted, which is the whole point: content is the user's\n * and must not steer the reader.\n *\n * A line that does not parse is not a marker. Deciding a window boundary from bytes that are not a\n * record would be guessing, and this function exists because guessing is what it replaced.\n */\nfunction isMarkerRecord(line: string, marker: string): boolean {\n let record: { type?: unknown; subtype?: unknown };\n try {\n record = JSON.parse(line) as { type?: unknown; subtype?: unknown };\n } catch {\n return false;\n }\n return record.subtype === marker || record.type === marker;\n}\n\nexport function readJsonlTail<T = Record<string, unknown>>(\n path: string,\n options: ReadJsonlTailOptions = {},\n): T[] {\n const want = options.maxRecords ?? Number.POSITIVE_INFINITY;\n const { lines, bytesRead } = readRawTail(path, want);\n\n let sel = lines;\n if (options.sinceMarker !== undefined) {\n const marker = options.sinceMarker;\n // STRUCTURAL, not `line.includes(marker)`.\n //\n // A raw substring match is true for any line that merely MENTIONS the marker — a user asking\n // \"how does compact_boundary work?\" silently truncated the window to start at their question.\n // The read then succeeded, returned fewer records than exist, and said nothing. That is the\n // measured reason the only would-be consumer kept its own reader instead of this one.\n const idx = sel.findLastIndex((l) => isMarkerRecord(l, marker));\n if (idx >= 0) sel = sel.slice(idx + 1);\n }\n if (Number.isFinite(want)) sel = sel.slice(-want);\n\n const out = sel.map((l) => JSON.parse(l) as T);\n return options._stats === true ? (Object.assign(out, { bytesRead }) as T[]) : out;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  export { PersistenceSchema } from './chunk-CAH3G4IS.js';
2
2
  export { SessionBusyError, acquireSessionWriter, sessionHasWriter } from './chunk-R7TKOQMJ.js';
3
3
  export { encodeProjectDir, transcriptPath, transcriptRoot } from './chunk-C4EU627W.js';
4
- export { JsonlParseError, appendJsonl, loadJsonl, readJsonlIds, withFileLock } from './chunk-NACDF3PK.js';
4
+ export { JsonlParseError, appendJsonl, loadJsonl, readJsonlIds, withFileLock } from './chunk-HTK54K2J.js';
5
5
  export { applyWalWithFallback, isCorruptionError, openSqliteResilient, sanitizeFts5Query } from './chunk-W4FV7JBH.js';
6
6
  export { withCwdMutex } from './chunk-2XLKLVVR.js';
7
7
  import { atomicWriteTempTarget } from './chunk-CHVSMEKM.js';
@@ -71,13 +71,22 @@ function readRawTail(path, want) {
71
71
  function nonEmptyLines(text) {
72
72
  return text.split("\n").filter((l) => l.trim().length > 0);
73
73
  }
74
+ function isMarkerRecord(line, marker) {
75
+ let record;
76
+ try {
77
+ record = JSON.parse(line);
78
+ } catch {
79
+ return false;
80
+ }
81
+ return record.subtype === marker || record.type === marker;
82
+ }
74
83
  function readJsonlTail(path, options = {}) {
75
84
  const want = options.maxRecords ?? Number.POSITIVE_INFINITY;
76
85
  const { lines, bytesRead } = readRawTail(path, want);
77
86
  let sel = lines;
78
87
  if (options.sinceMarker !== void 0) {
79
88
  const marker = options.sinceMarker;
80
- const idx = sel.findLastIndex((l) => l.includes(marker));
89
+ const idx = sel.findLastIndex((l) => isMarkerRecord(l, marker));
81
90
  if (idx >= 0) sel = sel.slice(idx + 1);
82
91
  }
83
92
  if (Number.isFinite(want)) sel = sel.slice(-want);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/persistence/session-artifacts.ts","../src/internal/persistence/transcript-ops.ts"],"names":[],"mappings":";;;;;;;;;;;;;AA6BO,SAAS,uBAAA,CACd,MACA,WAAA,EAC6B;AAE7B,EAAA,IAAI,KAAK,QAAA,CAAS,aAAa,CAAA,EAAG,OAAO,cAAc,gBAAA,GAAmB,MAAA;AAC1E,EAAA,IAAI,aAAa,OAAO,MAAA;AACxB,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,QAAQ,CAAA,EAAG,OAAO,YAAA;AACpC,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,cAAc,CAAA,EAAG,OAAO,aAAA;AAC1C,EAAA,IAAI,qBAAA,CAAsB,IAAI,CAAA,KAAM,MAAA,EAAW,OAAO,MAAA;AACtD,EAAA,OAAO,MAAA;AACT;ACNO,IAAM,gBAAA,GAAN,cAA+B,iBAAA,CAAkB;AAAA,EAGtD,YAAqB,IAAA,EAAc;AACjC,IAAA,KAAA;AAAA,MACE,qDAAqD,IAAI,CAAA,+JAAA,CAAA;AAAA,MAGzD,EAAE,IAAA,EAAM,wBAAA,EAA0B,WAAA,EAAa,KAAA;AAAM,KACvD;AANmB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAOrB;AAAA,EAPqB,IAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;AAmCO,SAAS,cAAA,CACd,GAAA,EACA,GAAA,EACA,OAAA,GAAiC,EAAC,EAC5B;AACN,EAAA,KAAA,MAAW,IAAA,IAAQ,OAAA,CAAQ,gBAAA,IAAoB,EAAC,EAAG;AACjD,IAAA,IAAI,IAAA,KAAS,GAAA,EAAK,MAAM,IAAI,iBAAiB,GAAG,CAAA;AAAA,EAClD;AAEA,EAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,GAAA,EAAK,MAAM,EACnC,KAAA,CAAM,IAAI,CAAA,CACV,MAAA,CAAO,CAAC,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GAAM,IAAI,GAAA,CAAI,CAAC,MAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAM,CAAA;AAC7C,EAAA,OAAO,OAAA,CAAQ,WAAW,IAAA,GAAQ,MAAA,CAAO,OAAO,GAAA,EAAK,EAAE,SAAA,EAAW,CAAA,GAAY,GAAA;AAChF","file":"persistence.js","sourcesContent":["import { atomicWriteTempTarget } from \"./atomic-write.js\";\n\n/**\n * The kinds of file this SDK leaves in a project's transcript directory.\n *\n * - `transcript` — the session itself (`transcriptPath`).\n * - `writer-lock` — the cross-process writer lease (`session-writer.ts`, `<file>.writer.lock`).\n * - `lock-directory` — `withFileLock`'s companion, taken by `mkdir`, so it is a DIRECTORY.\n * - `temp` — what `replaceFileAtomic` leaves when a process dies between the open and the rename.\n */\nexport type SessionArtifact = \"transcript\" | \"writer-lock\" | \"lock-directory\" | \"temp\";\n\n/**\n * U-1 — what is this entry, if it is one of ours?\n *\n * The SDK writes four kinds of file into a project directory and reasons about none of them\n * afterwards: there is no retention, no collector, and there was no way even to ask what an entry\n * IS. A consumer wanting to reclaim disk had to re-derive the suffixes by reading this source — and\n * one did, which means a suffix changing here would have left its classifier silently mislabelling\n * files on a path that deletes them.\n *\n * This is deliberately NOT a garbage collector. Retention is policy — how many days, how many to\n * keep, which session is live, whether to delete at all — and policy belongs to the application,\n * which is the only one that can know. What belongs here is the half only the SDK can answer.\n *\n * `undefined` means \"not written by this SDK\", and it is the answer that matters most: a caller\n * deleting what it does not recognise is how an editor's swap file gets collected. The `temp` case\n * defers to {@link atomicWriteTempTarget} rather than matching `.tmp`, for exactly that reason.\n */\nexport function classifySessionArtifact(\n name: string,\n isDirectory: boolean,\n): SessionArtifact | undefined {\n // `withFileLock` takes its lock by `mkdir`, so the same name as a plain file is not ours.\n if (name.endsWith(\".jsonl.lock\")) return isDirectory ? \"lock-directory\" : undefined;\n if (isDirectory) return undefined;\n if (name.endsWith(\".jsonl\")) return \"transcript\";\n if (name.endsWith(\".writer.lock\")) return \"writer-lock\";\n if (atomicWriteTempTarget(name) !== undefined) return \"temp\";\n return undefined;\n}\n","/**\n * M81 — transcript operations the consumer was doing by hand INSIDE the framework's own store.\n *\n * ## What this replaces\n *\n * `agents/lib/session/backtrack.ts:188` (agent-builder) wrote straight into the session store with a\n * bare `writeFileSync` — no atomicity, no lock, no API. 243 lines re-implementing parse, cut and\n * write for a format the framework owns. The consumer is not at fault: nothing here was reachable.\n *\n * ## The rule that travels WITH the operation\n *\n * `rules/audit-trail-rotation.md § Session transcripts (M60)` defines a NEVER-delete list — the live\n * pointer, the most recent transcript, and any active registry entry. That rule lived in the\n * CONSUMER. Moving the operation here without moving the rule would ship an API able to destroy\n * exactly what the rule protects — the same shape of defect as M80's `reconcileUpdateGoalStatus`:\n * critical knowledge outside the module that needs it, applied by convention.\n *\n * So `forkTranscript` takes `liveSessionPaths` and refuses, with a TYPED error, to write over any of\n * them. The caller supplies the list because only the caller knows which session is live; the\n * enforcement lives here because that is where the write happens.\n *\n * @internal\n */\n\nimport { closeSync, openSync, readFileSync, readSync, statSync, writeSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — the target is a protected session (live pointer / most-recent transcript / active entry).\n *\n * Typed rather than a bare `Error` because the caller must distinguish \"this session is protected\"\n * from \"the disk is full\": the first is a correct refusal, the second is an incident.\n */\nexport class LiveSessionError extends TheokitAgentError {\n override readonly name = \"LiveSessionError\";\n\n constructor(readonly path: string) {\n super(\n `refusing to write over a live session transcript: ${path}. ` +\n \"Fork to a new id instead — the live pointer, the most recent transcript and any active \" +\n \"registry entry are never overwritten (audit-trail rotation, M60).\",\n { code: \"live_session_protected\", isRetryable: false },\n );\n }\n}\n\n/** Options for {@link forkTranscript}. */\nexport interface ForkTranscriptOptions {\n /** Keep records `[0, beforeRecordIndex)`. Omit to copy the whole transcript. */\n readonly beforeRecordIndex?: number;\n /**\n * Paths that must never be written over — the live pointer, the most recent transcript, any active\n * registry entry. The caller supplies them because only the caller knows which session is live.\n */\n readonly liveSessionPaths?: readonly string[];\n /**\n * M107 — permission bits for the created destination. Default: `0o600`.\n *\n * A transcript carries the conversation. Before M107 no mode was passed at all, so the file was\n * born `0o666 & ~umask` — measured `0o664` (group-WRITABLE) on a `umask 002` machine, `0o644` on\n * `umask 022`, `0o466` on `umask 0200`. This is a DEFAULT and not a required knob on purpose: a\n * knob would reach zero consumers by omission, which is the failure mode that matters.\n *\n * As with any `open` mode, the `umask` may still CLEAR bits — under `umask 0200` the result is\n * `0o400`. That is accepted: the invariant bought here is \"neither group nor others\", and `0o400`\n * satisfies it more strictly. The SDK deliberately does not `fchmod` the default back, because\n * that would hand back a bit the operator asked to remove.\n */\n readonly mode?: number;\n}\n\n/**\n * Copy `src` into `dst`, keeping the first `beforeRecordIndex` records. The SOURCE is never touched.\n *\n * Atomicity comes from `wx` (exclusive create): two concurrent forks to the same destination cannot\n * both succeed — the loser gets `EEXIST` rather than writing over a half-written file. That is also\n * why an existing destination is a refusal, not a silent overwrite: losing a transcript without an\n * error is the worst failure mode for an operation that touches user sessions.\n */\nexport function forkTranscript(\n src: string,\n dst: string,\n options: ForkTranscriptOptions = {},\n): void {\n for (const live of options.liveSessionPaths ?? []) {\n if (live === dst) throw new LiveSessionError(dst);\n }\n\n const lines = readFileSync(src, \"utf8\")\n .split(\"\\n\")\n .filter((l) => l.trim().length > 0);\n const kept =\n options.beforeRecordIndex === undefined ? lines : lines.slice(0, options.beforeRecordIndex);\n const body = kept.length > 0 ? `${kept.join(\"\\n\")}\\n` : \"\";\n\n // `wx` — fails with EEXIST instead of truncating. The exclusivity IS the concurrency guarantee,\n // and M107 only added the third argument: the mode. See `ForkTranscriptOptions.mode`.\n const fd = openSync(dst, \"wx\", options.mode ?? 0o600);\n try {\n writeSync(fd, body);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Options for {@link readJsonlTail}. */\nexport interface ReadJsonlTailOptions {\n /** Maximum records to return, counted from the END. */\n readonly maxRecords?: number;\n /** Stop once a line contains this marker (exclusive). */\n readonly sinceMarker?: string;\n /** Test-only: also report how many bytes were read, to prove the read is not whole-file. */\n readonly _stats?: boolean;\n}\n\nconst TAIL_CHUNK = 64 * 1024;\n\n/**\n * Reads chunks backwards until enough complete lines have accumulated.\n *\n * Extracted from `readJsonlTail` because the read loop and the record selection are two\n * responsibilities — and together they exceeded the complexity ceiling. The buffer's first line may\n * be cut in half when the read stopped before the start of the file; that is why it is discarded.\n */\nfunction readRawTail(path: string, want: number): { lines: string[]; bytesRead: number } {\n const size = statSync(path).size;\n const fd = openSync(path, \"r\");\n let bytesRead = 0;\n let tail = \"\";\n let pos = size;\n try {\n while (pos > 0) {\n const len = Math.min(TAIL_CHUNK, pos);\n pos -= len;\n const buf = Buffer.alloc(len);\n readSync(fd, buf, 0, len, pos);\n bytesRead += len;\n tail = buf.toString(\"utf8\") + tail;\n if (nonEmptyLines(tail).length > want) break;\n }\n } finally {\n closeSync(fd);\n }\n const lines = nonEmptyLines(tail);\n return { lines: pos > 0 ? lines.slice(1) : lines, bytesRead };\n}\n\n/** Non-empty lines, in file order. */\nfunction nonEmptyLines(text: string): string[] {\n return text.split(\"\\n\").filter((l) => l.trim().length > 0);\n}\n\n/**\n * Read the LAST records of a JSONL file without loading the whole thing.\n *\n * Reads fixed-size chunks backwards from EOF until enough newlines have been seen. A session\n * transcript grows without bound; loading megabytes to show the last three turns is the cost this\n * exists to avoid — and a `slice` over a full read would be that same cost with a better name.\n */\nexport function readJsonlTail<T = Record<string, unknown>>(\n path: string,\n options: ReadJsonlTailOptions = {},\n): T[] {\n const want = options.maxRecords ?? Number.POSITIVE_INFINITY;\n const { lines, bytesRead } = readRawTail(path, want);\n\n let sel = lines;\n if (options.sinceMarker !== undefined) {\n const marker = options.sinceMarker;\n const idx = sel.findLastIndex((l) => l.includes(marker));\n if (idx >= 0) sel = sel.slice(idx + 1);\n }\n if (Number.isFinite(want)) sel = sel.slice(-want);\n\n const out = sel.map((l) => JSON.parse(l) as T);\n return options._stats === true ? (Object.assign(out, { bytesRead }) as T[]) : out;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/persistence/session-artifacts.ts","../src/internal/persistence/transcript-ops.ts"],"names":[],"mappings":";;;;;;;;;;;;;AA6BO,SAAS,uBAAA,CACd,MACA,WAAA,EAC6B;AAE7B,EAAA,IAAI,KAAK,QAAA,CAAS,aAAa,CAAA,EAAG,OAAO,cAAc,gBAAA,GAAmB,MAAA;AAC1E,EAAA,IAAI,aAAa,OAAO,MAAA;AACxB,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,QAAQ,CAAA,EAAG,OAAO,YAAA;AACpC,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,cAAc,CAAA,EAAG,OAAO,aAAA;AAC1C,EAAA,IAAI,qBAAA,CAAsB,IAAI,CAAA,KAAM,MAAA,EAAW,OAAO,MAAA;AACtD,EAAA,OAAO,MAAA;AACT;ACNO,IAAM,gBAAA,GAAN,cAA+B,iBAAA,CAAkB;AAAA,EAGtD,YAAqB,IAAA,EAAc;AACjC,IAAA,KAAA;AAAA,MACE,qDAAqD,IAAI,CAAA,+JAAA,CAAA;AAAA,MAGzD,EAAE,IAAA,EAAM,wBAAA,EAA0B,WAAA,EAAa,KAAA;AAAM,KACvD;AANmB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAOrB;AAAA,EAPqB,IAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;AAmCO,SAAS,cAAA,CACd,GAAA,EACA,GAAA,EACA,OAAA,GAAiC,EAAC,EAC5B;AACN,EAAA,KAAA,MAAW,IAAA,IAAQ,OAAA,CAAQ,gBAAA,IAAoB,EAAC,EAAG;AACjD,IAAA,IAAI,IAAA,KAAS,GAAA,EAAK,MAAM,IAAI,iBAAiB,GAAG,CAAA;AAAA,EAClD;AAEA,EAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,GAAA,EAAK,MAAM,EACnC,KAAA,CAAM,IAAI,CAAA,CACV,MAAA,CAAO,CAAC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GAAM,IAAI,aAAA,CAAc,CAAC,MAAM,cAAA,CAAe,CAAA,EAAG,MAAM,CAAC,CAAA;AAC9D,IAAA,IAAI,OAAO,CAAA,EAAG,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,MAAM,CAAC,CAAA;AAAA,EACvC;AACA,EAAA,IAAI,MAAA,CAAO,SAAS,IAAI,CAAA,QAAS,GAAA,CAAI,KAAA,CAAM,CAAC,IAAI,CAAA;AAEhD,EAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,CAAC,MAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAM,CAAA;AAC7C,EAAA,OAAO,OAAA,CAAQ,WAAW,IAAA,GAAQ,MAAA,CAAO,OAAO,GAAA,EAAK,EAAE,SAAA,EAAW,CAAA,GAAY,GAAA;AAChF","file":"persistence.js","sourcesContent":["import { atomicWriteTempTarget } from \"./atomic-write.js\";\n\n/**\n * The kinds of file this SDK leaves in a project's transcript directory.\n *\n * - `transcript` — the session itself (`transcriptPath`).\n * - `writer-lock` — the cross-process writer lease (`session-writer.ts`, `<file>.writer.lock`).\n * - `lock-directory` — `withFileLock`'s companion, taken by `mkdir`, so it is a DIRECTORY.\n * - `temp` — what `replaceFileAtomic` leaves when a process dies between the open and the rename.\n */\nexport type SessionArtifact = \"transcript\" | \"writer-lock\" | \"lock-directory\" | \"temp\";\n\n/**\n * U-1 — what is this entry, if it is one of ours?\n *\n * The SDK writes four kinds of file into a project directory and reasons about none of them\n * afterwards: there is no retention, no collector, and there was no way even to ask what an entry\n * IS. A consumer wanting to reclaim disk had to re-derive the suffixes by reading this source — and\n * one did, which means a suffix changing here would have left its classifier silently mislabelling\n * files on a path that deletes them.\n *\n * This is deliberately NOT a garbage collector. Retention is policy — how many days, how many to\n * keep, which session is live, whether to delete at all — and policy belongs to the application,\n * which is the only one that can know. What belongs here is the half only the SDK can answer.\n *\n * `undefined` means \"not written by this SDK\", and it is the answer that matters most: a caller\n * deleting what it does not recognise is how an editor's swap file gets collected. The `temp` case\n * defers to {@link atomicWriteTempTarget} rather than matching `.tmp`, for exactly that reason.\n */\nexport function classifySessionArtifact(\n name: string,\n isDirectory: boolean,\n): SessionArtifact | undefined {\n // `withFileLock` takes its lock by `mkdir`, so the same name as a plain file is not ours.\n if (name.endsWith(\".jsonl.lock\")) return isDirectory ? \"lock-directory\" : undefined;\n if (isDirectory) return undefined;\n if (name.endsWith(\".jsonl\")) return \"transcript\";\n if (name.endsWith(\".writer.lock\")) return \"writer-lock\";\n if (atomicWriteTempTarget(name) !== undefined) return \"temp\";\n return undefined;\n}\n","/**\n * M81 — transcript operations the consumer was doing by hand INSIDE the framework's own store.\n *\n * ## What this replaces\n *\n * `agents/lib/session/backtrack.ts:188` (agent-builder) wrote straight into the session store with a\n * bare `writeFileSync` — no atomicity, no lock, no API. 243 lines re-implementing parse, cut and\n * write for a format the framework owns. The consumer is not at fault: nothing here was reachable.\n *\n * ## The rule that travels WITH the operation\n *\n * `rules/audit-trail-rotation.md § Session transcripts (M60)` defines a NEVER-delete list — the live\n * pointer, the most recent transcript, and any active registry entry. That rule lived in the\n * CONSUMER. Moving the operation here without moving the rule would ship an API able to destroy\n * exactly what the rule protects — the same shape of defect as M80's `reconcileUpdateGoalStatus`:\n * critical knowledge outside the module that needs it, applied by convention.\n *\n * So `forkTranscript` takes `liveSessionPaths` and refuses, with a TYPED error, to write over any of\n * them. The caller supplies the list because only the caller knows which session is live; the\n * enforcement lives here because that is where the write happens.\n *\n * @internal\n */\n\nimport { closeSync, openSync, readFileSync, readSync, statSync, writeSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — the target is a protected session (live pointer / most-recent transcript / active entry).\n *\n * Typed rather than a bare `Error` because the caller must distinguish \"this session is protected\"\n * from \"the disk is full\": the first is a correct refusal, the second is an incident.\n */\nexport class LiveSessionError extends TheokitAgentError {\n override readonly name = \"LiveSessionError\";\n\n constructor(readonly path: string) {\n super(\n `refusing to write over a live session transcript: ${path}. ` +\n \"Fork to a new id instead — the live pointer, the most recent transcript and any active \" +\n \"registry entry are never overwritten (audit-trail rotation, M60).\",\n { code: \"live_session_protected\", isRetryable: false },\n );\n }\n}\n\n/** Options for {@link forkTranscript}. */\nexport interface ForkTranscriptOptions {\n /** Keep records `[0, beforeRecordIndex)`. Omit to copy the whole transcript. */\n readonly beforeRecordIndex?: number;\n /**\n * Paths that must never be written over — the live pointer, the most recent transcript, any active\n * registry entry. The caller supplies them because only the caller knows which session is live.\n */\n readonly liveSessionPaths?: readonly string[];\n /**\n * M107 — permission bits for the created destination. Default: `0o600`.\n *\n * A transcript carries the conversation. Before M107 no mode was passed at all, so the file was\n * born `0o666 & ~umask` — measured `0o664` (group-WRITABLE) on a `umask 002` machine, `0o644` on\n * `umask 022`, `0o466` on `umask 0200`. This is a DEFAULT and not a required knob on purpose: a\n * knob would reach zero consumers by omission, which is the failure mode that matters.\n *\n * As with any `open` mode, the `umask` may still CLEAR bits — under `umask 0200` the result is\n * `0o400`. That is accepted: the invariant bought here is \"neither group nor others\", and `0o400`\n * satisfies it more strictly. The SDK deliberately does not `fchmod` the default back, because\n * that would hand back a bit the operator asked to remove.\n */\n readonly mode?: number;\n}\n\n/**\n * Copy `src` into `dst`, keeping the first `beforeRecordIndex` records. The SOURCE is never touched.\n *\n * Atomicity comes from `wx` (exclusive create): two concurrent forks to the same destination cannot\n * both succeed — the loser gets `EEXIST` rather than writing over a half-written file. That is also\n * why an existing destination is a refusal, not a silent overwrite: losing a transcript without an\n * error is the worst failure mode for an operation that touches user sessions.\n */\nexport function forkTranscript(\n src: string,\n dst: string,\n options: ForkTranscriptOptions = {},\n): void {\n for (const live of options.liveSessionPaths ?? []) {\n if (live === dst) throw new LiveSessionError(dst);\n }\n\n const lines = readFileSync(src, \"utf8\")\n .split(\"\\n\")\n .filter((l) => l.trim().length > 0);\n const kept =\n options.beforeRecordIndex === undefined ? lines : lines.slice(0, options.beforeRecordIndex);\n const body = kept.length > 0 ? `${kept.join(\"\\n\")}\\n` : \"\";\n\n // `wx` — fails with EEXIST instead of truncating. The exclusivity IS the concurrency guarantee,\n // and M107 only added the third argument: the mode. See `ForkTranscriptOptions.mode`.\n const fd = openSync(dst, \"wx\", options.mode ?? 0o600);\n try {\n writeSync(fd, body);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Options for {@link readJsonlTail}. */\nexport interface ReadJsonlTailOptions {\n /** Maximum records to return, counted from the END. */\n readonly maxRecords?: number;\n /** Stop once a line contains this marker (exclusive). */\n /**\n * Start the window AFTER the last record whose `subtype` (or `type`) equals this.\n *\n * Matched STRUCTURALLY since T2.5. It used to be `line.includes(marker)`, so any message\n * mentioning the marker in its text truncated the read — silently, with a successful return.\n */\n readonly sinceMarker?: string;\n /** Test-only: also report how many bytes were read, to prove the read is not whole-file. */\n readonly _stats?: boolean;\n}\n\nconst TAIL_CHUNK = 64 * 1024;\n\n/**\n * Reads chunks backwards until enough complete lines have accumulated.\n *\n * Extracted from `readJsonlTail` because the read loop and the record selection are two\n * responsibilities — and together they exceeded the complexity ceiling. The buffer's first line may\n * be cut in half when the read stopped before the start of the file; that is why it is discarded.\n */\nfunction readRawTail(path: string, want: number): { lines: string[]; bytesRead: number } {\n const size = statSync(path).size;\n const fd = openSync(path, \"r\");\n let bytesRead = 0;\n let tail = \"\";\n let pos = size;\n try {\n while (pos > 0) {\n const len = Math.min(TAIL_CHUNK, pos);\n pos -= len;\n const buf = Buffer.alloc(len);\n readSync(fd, buf, 0, len, pos);\n bytesRead += len;\n tail = buf.toString(\"utf8\") + tail;\n if (nonEmptyLines(tail).length > want) break;\n }\n } finally {\n closeSync(fd);\n }\n const lines = nonEmptyLines(tail);\n return { lines: pos > 0 ? lines.slice(1) : lines, bytesRead };\n}\n\n/** Non-empty lines, in file order. */\nfunction nonEmptyLines(text: string): string[] {\n return text.split(\"\\n\").filter((l) => l.trim().length > 0);\n}\n\n/**\n * Read the LAST records of a JSONL file without loading the whole thing.\n *\n * Reads fixed-size chunks backwards from EOF until enough newlines have been seen. A session\n * transcript grows without bound; loading megabytes to show the last three turns is the cost this\n * exists to avoid — and a `slice` over a full read would be that same cost with a better name.\n */\n\n/**\n * Whether a raw JSONL line IS the marker record, rather than a line that talks about it.\n *\n * Matches on the record's own discriminants (`subtype`, then `type`) — the fields that identify\n * what a record *is*. Free text is never consulted, which is the whole point: content is the user's\n * and must not steer the reader.\n *\n * A line that does not parse is not a marker. Deciding a window boundary from bytes that are not a\n * record would be guessing, and this function exists because guessing is what it replaced.\n */\nfunction isMarkerRecord(line: string, marker: string): boolean {\n let record: { type?: unknown; subtype?: unknown };\n try {\n record = JSON.parse(line) as { type?: unknown; subtype?: unknown };\n } catch {\n return false;\n }\n return record.subtype === marker || record.type === marker;\n}\n\nexport function readJsonlTail<T = Record<string, unknown>>(\n path: string,\n options: ReadJsonlTailOptions = {},\n): T[] {\n const want = options.maxRecords ?? Number.POSITIVE_INFINITY;\n const { lines, bytesRead } = readRawTail(path, want);\n\n let sel = lines;\n if (options.sinceMarker !== undefined) {\n const marker = options.sinceMarker;\n // STRUCTURAL, not `line.includes(marker)`.\n //\n // A raw substring match is true for any line that merely MENTIONS the marker — a user asking\n // \"how does compact_boundary work?\" silently truncated the window to start at their question.\n // The read then succeeded, returned fewer records than exist, and said nothing. That is the\n // measured reason the only would-be consumer kept its own reader instead of this one.\n const idx = sel.findLastIndex((l) => isMarkerRecord(l, marker));\n if (idx >= 0) sel = sel.slice(idx + 1);\n }\n if (Number.isFinite(want)) sel = sel.slice(-want);\n\n const out = sel.map((l) => JSON.parse(l) as T);\n return options._stats === true ? (Object.assign(out, { bytesRead }) as T[]) : out;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/sdk",
3
- "version": "4.52.1",
3
+ "version": "4.53.0",
4
4
  "description": "TypeScript SDK for the Theo agent harness — same surface, local or cloud.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/usetheodev/theokit-sdk#readme",
@@ -238,6 +238,16 @@
238
238
  "default": "./dist/auth/index.cjs"
239
239
  }
240
240
  },
241
+ "./mcp-auth": {
242
+ "import": {
243
+ "types": "./dist/mcp-auth.d.ts",
244
+ "default": "./dist/mcp-auth.js"
245
+ },
246
+ "require": {
247
+ "types": "./dist/mcp-auth.d.cts",
248
+ "default": "./dist/mcp-auth.cjs"
249
+ }
250
+ },
241
251
  "./internal/persistence": {
242
252
  "import": {
243
253
  "types": "./dist/internal/persistence/index.d.ts",