@theokit/sdk 4.41.1 → 4.42.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +60 -0
- package/dist/{agent-JDJEBJHU.cjs → agent-DRUORJTU.cjs} +8 -7
- package/dist/{agent-JDJEBJHU.cjs.map → agent-DRUORJTU.cjs.map} +1 -1
- package/dist/{agent-LVKAYADR.js → agent-MVYGMWPM.js} +7 -6
- package/dist/{agent-LVKAYADR.js.map → agent-MVYGMWPM.js.map} +1 -1
- package/dist/{chunk-RPL3POFZ.cjs → chunk-4OQXDCMN.cjs} +50 -380
- package/dist/chunk-4OQXDCMN.cjs.map +1 -0
- package/dist/{chunk-ZO2L5U6F.cjs → chunk-FAUKVJCC.cjs} +3 -3
- package/dist/{chunk-ZO2L5U6F.cjs.map → chunk-FAUKVJCC.cjs.map} +1 -1
- package/dist/chunk-GAXYZXYY.cjs +352 -0
- package/dist/chunk-GAXYZXYY.cjs.map +1 -0
- package/dist/{chunk-GTLH2NI2.cjs → chunk-HLGEXZZP.cjs} +5 -5
- package/dist/{chunk-GTLH2NI2.cjs.map → chunk-HLGEXZZP.cjs.map} +1 -1
- package/dist/{chunk-AUMSEL33.js → chunk-O67XODD5.js} +3 -3
- package/dist/{chunk-AUMSEL33.js.map → chunk-O67XODD5.js.map} +1 -1
- package/dist/{chunk-FMIKUGF2.cjs → chunk-QFFNMJAS.cjs} +5 -5
- package/dist/{chunk-FMIKUGF2.cjs.map → chunk-QFFNMJAS.cjs.map} +1 -1
- package/dist/{chunk-UTYCG4RB.js → chunk-TDDRPFO3.js} +3 -3
- package/dist/{chunk-UTYCG4RB.js.map → chunk-TDDRPFO3.js.map} +1 -1
- package/dist/{chunk-IMX5YODO.js → chunk-UJ7HK7BX.js} +3 -3
- package/dist/{chunk-IMX5YODO.js.map → chunk-UJ7HK7BX.js.map} +1 -1
- package/dist/{chunk-DHLVOLUX.js → chunk-V5V5A6B7.js} +12 -342
- package/dist/chunk-V5V5A6B7.js.map +1 -0
- package/dist/chunk-ZZAAQOAZ.js +344 -0
- package/dist/chunk-ZZAAQOAZ.js.map +1 -0
- package/dist/{compact-session-65XCKO6H.js → compact-session-GF2CBKXB.js} +4 -4
- package/dist/{compact-session-65XCKO6H.js.map → compact-session-GF2CBKXB.js.map} +1 -1
- package/dist/{compact-session-OU6SRPVJ.cjs → compact-session-UUCBTBCZ.cjs} +12 -12
- package/dist/{compact-session-OU6SRPVJ.cjs.map → compact-session-UUCBTBCZ.cjs.map} +1 -1
- package/dist/context/index.cjs +35 -0
- package/dist/context/index.cjs.map +1 -0
- package/dist/context/index.d.cts +78 -0
- package/dist/context/index.d.ts +78 -0
- package/dist/context/index.js +18 -0
- package/dist/context/index.js.map +1 -0
- package/dist/cron.cjs +7 -6
- package/dist/cron.js +6 -5
- package/dist/eval.cjs +6 -5
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +5 -4
- package/dist/eval.js.map +1 -1
- package/dist/index.cjs +34 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +9 -8
- package/dist/index.js.map +1 -1
- package/dist/{inject-session-DDC36KKP.cjs → inject-session-I3HK3AHB.cjs} +4 -4
- package/dist/{inject-session-DDC36KKP.cjs.map → inject-session-I3HK3AHB.cjs.map} +1 -1
- package/dist/{inject-session-UBM4KVSV.js → inject-session-NR64GB3T.js} +3 -3
- package/dist/{inject-session-UBM4KVSV.js.map → inject-session-NR64GB3T.js.map} +1 -1
- package/dist/internal/runtime/context/path-containment.d.ts +24 -0
- package/package.json +23 -12
- package/dist/chunk-DHLVOLUX.js.map +0 -1
- package/dist/chunk-RPL3POFZ.cjs.map +0 -1
|
@@ -48,7 +48,7 @@ function persistTurnToTranscript(store, loc, sessionId, turn, onCompact) {
|
|
|
48
48
|
const count = (recordCounts.get(key) ?? 0) + 1;
|
|
49
49
|
recordCounts.set(key, count);
|
|
50
50
|
if (turn.autoCompact !== void 0) {
|
|
51
|
-
const { autoCompactIfNeeded } = await import('./compact-session-
|
|
51
|
+
const { autoCompactIfNeeded } = await import('./compact-session-UUCBTBCZ.cjs');
|
|
52
52
|
const fired = await autoCompactIfNeeded({
|
|
53
53
|
store,
|
|
54
54
|
loc,
|
|
@@ -114,5 +114,5 @@ exports.flushSessionWrites = flushSessionWrites;
|
|
|
114
114
|
exports.getSessionMessages = getSessionMessages;
|
|
115
115
|
exports.hydrateSession = hydrateSession;
|
|
116
116
|
exports.persistTurnToTranscript = persistTurnToTranscript;
|
|
117
|
-
//# sourceMappingURL=chunk-
|
|
118
|
-
//# sourceMappingURL=chunk-
|
|
117
|
+
//# sourceMappingURL=chunk-FAUKVJCC.cjs.map
|
|
118
|
+
//# sourceMappingURL=chunk-FAUKVJCC.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":["sessions","transcriptKey","hydratedKeys","persistTurn","diag","readSessionMessages"],"mappings":";;;;;;;AAwCA,IAAM,aAAA,uBAAoB,GAAA,EAA2B;AACrD,IAAM,YAAA,uBAAmB,GAAA,EAAoB;AAStC,SAAS,oBAAA,CAAqB,SAAiB,OAAA,EAA+B;AACnF,EAAA,MAAM,QAAA,GAAWA,0BAAA,CAAS,GAAA,CAAI,OAAO,KAAK,EAAC;AAC3C,EAAA,QAAA,CAAS,KAAK,OAAO,CAAA;AAIrB,EAAAA,0BAAA,CAAS,OAAO,OAAO,CAAA;AACvB,EAAAA,0BAAA,CAAS,GAAA,CAAI,SAAS,QAAQ,CAAA;AAC9B,EAAA,cAAA,EAAe;AACjB;AAWO,IAAM,mBAAA,GAAsB,EAAA;AAEnC,SAAS,cAAA,GAAuB;AAC9B,EAAA,OAAOA,0BAAA,CAAS,OAAO,mBAAA,EAAqB;AAC1C,IAAA,MAAM,MAAA,GAASA,0BAAA,CAAS,IAAA,EAAK,CAAE,MAAK,CAAE,KAAA;AACtC,IAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,IAAAA,0BAAA,C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A;AAAA,IACA,MAAA,CAAO,IAAA;AAAA,MACL,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-ZO2L5U6F.cjs","sourcesContent":["import type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type PersistTurnInput,\n persistTurn,\n readSessionMessages,\n type TranscriptLocation,\n} from \"./agent-session-store.js\";\n\n/**\n * Per-agent conversation history kept across runs (and across `Agent.resume()`\n * within the same process). Lets the fixture responder recall prior facts when\n * the user asks a follow-up question.\n *\n * SE40 — disk persistence IS the native Claude-shaped `.jsonl` transcript. The\n * in-memory cache holds the narrowed `SessionMessage[]` (user/assistant text) so\n * a send can read `priorMessages` synchronously; the whole rich turn (user +\n * assistant + tool blocks) lands on disk once per send via {@link persistTurnToTranscript}\n * (fed by `run.conversation()`). Hydration on resume reconstructs the session by\n * walking the transcript DAG (`readSessionMessages`).\n *\n * @internal\n */\n\n// `SessionMessage` lives in `./session-types.ts` (leaf types file). Re-exported\n// for back-compat with downstream importers that pulled it from here.\nexport type { SessionMessage } from \"./session-types.js\";\n\nimport type { SessionMessage } from \"./session-types.js\";\n\n// M75 — the cache lives in a leaf; see session-cache.ts for the reason (cycle broken by extraction).\nexport {\n hydratedKeys,\n invalidateSessionCache,\n sessions,\n transcriptKey,\n} from \"./session-cache.js\";\n\nimport { diag } from \"../diagnostics.js\";\nimport { hydratedKeys, sessions, transcriptKey } from \"./session-cache.js\";\n\nconst pendingWrites = new Map<string, Promise<void>>();\nconst recordCounts = new Map<string, number>();\n\n/**\n * Append a session message to the in-memory cache only. Disk persistence for the\n * whole turn happens once per send via {@link persistTurnToTranscript}; the cache\n * feeds `priorMessages` / `onBeforeSend.previousMessageCount` synchronously.\n *\n * @internal\n */\nexport function appendSessionMessage(agentId: string, message: SessionMessage): void {\n const existing = sessions.get(agentId) ?? [];\n existing.push(message);\n // `delete` + `set` reinserts at the END: a JS `Map` preserves insertion order, so the first key\n // is always the least recently touched. That is the entire LRU, with no new structure (parsimony\n // rungs 2/5 — the ordering we need is already a language guarantee).\n sessions.delete(agentId);\n sessions.set(agentId, existing);\n enforceCeiling();\n}\n\n/**\n * Ceiling on sessions kept in memory.\n *\n * The runtime only reads the **active** session; the rest is pure cache, rebuildable from the\n * on-disk transcript. 32 is deliberately generous — the primary removal path is the explicit\n * `discardSession()` at the end of the agent's life, and this ceiling is a safety net against a\n * long-lived process running hundreds of sessions (plan risk #2: a tight ceiling could evict a\n * session still referenced by an in-flight async path).\n */\nexport const MAX_CACHED_SESSIONS = 32;\n\nfunction enforceCeiling(): void {\n while (sessions.size > MAX_CACHED_SESSIONS) {\n const oldest = sessions.keys().next().value;\n if (oldest === undefined) return;\n sessions.delete(oldest);\n forgetBookkeeping(oldest);\n }\n}\n\n/**\n * Erases the bookkeeping for an `agentId` across EVERY `cwd` it appears in.\n *\n * The three maps are keyed by `transcriptKey(cwd, agentId)`; `sessions` is the only one keyed by the\n * raw `agentId`. The ceiling's first version deleted from all three using `sessions`' key — that is,\n * deleted nothing — and left `hydratedKeys` **orphaned**. Since `hydrateSession` returns early when\n * the marker is present, an evicted session came back **empty** instead of rehydrating from disk:\n * silent amnesia, and a regression new to M95, because before it nothing evicted.\n *\n * The ceiling only knows the `agentId`, not the `cwd`, so it scans by suffix — which is the format\n * `transcriptKey` produces. A scan rather than an index because these maps hold tens of entries, not\n * thousands: a reverse index here would be new structure for a problem that does not exist.\n */\nfunction forgetBookkeeping(agentId: string): void {\n const suffix = transcriptKey(\"\", agentId).slice(0 - agentId.length - 2);\n for (const k of [...hydratedKeys]) if (k.endsWith(suffix)) hydratedKeys.delete(k);\n for (const k of [...pendingWrites.keys()]) if (k.endsWith(suffix)) pendingWrites.delete(k);\n for (const k of [...recordCounts.keys()]) if (k.endsWith(suffix)) recordCounts.delete(k);\n}\n\n/**\n * Erases the agent's module bookkeeping and returns how many entries were removed.\n *\n * M95 — `invalidateSessionCache` used to clear **two** of the four maps (`sessions`, `hydratedKeys`);\n * `pendingWrites` and `recordCounts` were never touched by id, so they grew for the life of the\n * process. Neither is large per entry — the leak is in count, not volume — but a cache with no owner\n * for removal is a cache that only grows.\n *\n * Returns the count so the caller can prove the removal; a second discard returns 0, which is what\n * makes the idempotency test possible without exposing the maps.\n */\nexport function discardSession(cwd: string, agentId: string): number {\n const key = transcriptKey(cwd, agentId);\n let removed = 0;\n // `sessions` is NOT erased here — and the distinction is measured, not aesthetic. It holds the\n // readable conversation, and there is a legitimate reader AFTER dispose: the golden\n // `two-concurrent-sends-serialize` calls `getSessionMessages(agentId)` after `agent.dispose()`.\n // Erasing it here returned an empty list and broke two goldens. What bounds it is the LRU ceiling\n // above; the three below are pure bookkeeping, with no post-dispose reader.\n //\n // The key is `transcriptKey(cwd, agentId)` in ALL THREE — not the raw `agentId`. The first version\n // erased two of them by `agentId` and therefore **never erased anything**; the test did not catch\n // it because it only asserted that the SECOND call returns 0, which is true either way.\n if (hydratedKeys.delete(key)) removed++;\n if (pendingWrites.delete(key)) removed++;\n if (recordCounts.delete(key)) removed++;\n return removed;\n}\n\nexport function getSessionMessages(agentId: string): SessionMessage[] {\n return sessions.get(agentId) ?? [];\n}\n\n/**\n * Persist a full conversation turn (user + assistant + tool blocks) to the native\n * transcript. Chained per-(agent, transcript) so on-disk order matches send order,\n * and fire-and-forget so `send()` is not blocked by disk I/O. Every\n * M50 — when the caller supplies `turn.autoCompact`, size-driven auto-compaction (usage real vs\n * the model's context window) runs in this same chain, surfaced via the optional `onCompact` observer.\n *\n * @internal\n */\nexport function persistTurnToTranscript(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n onCompact?: () => void,\n): void {\n const key = transcriptKey(loc.cwd, loc.agentId);\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\n const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {\n try {\n await persistTurn(store, loc, sessionId, turn);\n const count = (recordCounts.get(key) ?? 0) + 1;\n recordCounts.set(key, count);\n // M50 — the 50-turn no-summary boundary stub is GONE (it silently amnesia'd the session).\n // Auto-compaction is now size-driven with a real summary: see `maybeAutoCompact` below,\n // invoked in this same write chain by the post-run lifecycle when usage is known.\n if (turn.autoCompact !== undefined) {\n const { autoCompactIfNeeded } = await import(\"./compact-session.js\");\n const fired = await autoCompactIfNeeded({\n store,\n loc,\n sessionId,\n usageTotal: turn.autoCompact.usageTotal,\n contextWindow: turn.autoCompact.contextWindow,\n turnCount: count,\n summarize: turn.autoCompact.summarize,\n });\n if (fired) onCompact?.();\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}\\n`);\n }\n });\n pendingWrites.set(\n key,\n chained.then(\n () => undefined,\n () => undefined,\n ),\n );\n}\n\n/**\n * Load the persisted transcript into the in-memory cache. Idempotent per\n * (baseDir, cwd, agentId). Call once per agent lifecycle before the first read.\n *\n * @internal\n */\nexport async function hydrateSession(\n agentId: string,\n loc: { store: SessionStore; cwd: string },\n): Promise<void> {\n const key = transcriptKey(loc.cwd, agentId);\n if (hydratedKeys.has(key)) return;\n hydratedKeys.add(key);\n\n const persisted = await readSessionMessages(loc.store, agentId);\n if (persisted.length === 0) return;\n // M51 review F4 — the DISK is the source of truth at hydration time: after an invalidation\n // (compact/inject), an in-flight turn may have repopulated the cache with a SINGLE message before\n // this hydrate ran; the old \"skip when non-empty\" guard then pinned the parent to a 1-message\n // context (history + injected pair lost until restart). The persist chain serializes writes, so\n // the disk already contains that in-flight turn — replacing is always correct.\n sessions.set(agentId, persisted);\n}\n\n/**\n * Wait for all pending transcript writes to settle. Used by tests and by the\n * agent dispose path so on-disk state matches in-memory before the caller proceeds.\n *\n * @internal\n */\nexport async function flushSessionWrites(): Promise<void> {\n while (pendingWrites.size > 0) {\n const all = Array.from(pendingWrites.values());\n pendingWrites.clear();\n await Promise.all(all);\n }\n}\n\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\n\n/**\n * M50 review F1 — drop BOTH the message cache and the hydration marker so the NEXT send re-hydrates\n * from disk. Without this, a compaction only helps after a process restart: the live process keeps\n * sending the full pre-compact history (the cache is read synchronously by every send).\n */\n/**\n * M50 review F5 — run `fn` serialized on the SAME per-(cwd,agentId) write chain the per-turn\n * persistence uses, so a manual `Agent.compact` can never interleave with an in-flight turn's\n * writes (boundary landing mid-turn would orphan the turn from the replay).\n */\nexport function enqueueSessionWrite<T>(\n cwd: string,\n agentId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = transcriptKey(cwd, agentId);\n const prior = pendingWrites.get(key) ?? Promise.resolve();\n const result = prior.then(fn);\n pendingWrites.set(\n key,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n return result;\n}\n\n/** Test-only: drop every cached session and hydration marker. @internal */\nexport function clearAllSessions(): void {\n sessions.clear();\n hydratedKeys.clear();\n recordCounts.clear();\n // M50 review F11 — the auto-compact attempt marks live on globalThis; tests reset them here.\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n g[sym]?.clear();\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":["sessions","transcriptKey","hydratedKeys","persistTurn","diag","readSessionMessages"],"mappings":";;;;;;;AAwCA,IAAM,aAAA,uBAAoB,GAAA,EAA2B;AACrD,IAAM,YAAA,uBAAmB,GAAA,EAAoB;AAStC,SAAS,oBAAA,CAAqB,SAAiB,OAAA,EAA+B;AACnF,EAAA,MAAM,QAAA,GAAWA,0BAAA,CAAS,GAAA,CAAI,OAAO,KAAK,EAAC;AAC3C,EAAA,QAAA,CAAS,KAAK,OAAO,CAAA;AAIrB,EAAAA,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D,EAAAA,0BAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAYO,SAAS,mBAAA,CACd,GAAA,EACA,OAAA,EACA,EAAA,EACY;AACZ,EAAA,MAAM,GAAA,GAAMC,+BAAA,CAAc,GAAA,EAAK,OAAO,CAAA;AACtC,EAAA,MAAM,QAAQ,aAAA,CAAc,GAAA,CAAI,GAAG,CAAA,IAAK,QAAQ,OAAA,EAAQ;AACxD,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,EAAE,CAAA;AAC5B,EAAA,aAAA,CAAc,GAAA;AAAA,IACZ,GAAA;AAAA,IACA,MAAA,CAAO,IAAA;AAAA,MACL,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-FAUKVJCC.cjs","sourcesContent":["import type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type PersistTurnInput,\n persistTurn,\n readSessionMessages,\n type TranscriptLocation,\n} from \"./agent-session-store.js\";\n\n/**\n * Per-agent conversation history kept across runs (and across `Agent.resume()`\n * within the same process). Lets the fixture responder recall prior facts when\n * the user asks a follow-up question.\n *\n * SE40 — disk persistence IS the native Claude-shaped `.jsonl` transcript. The\n * in-memory cache holds the narrowed `SessionMessage[]` (user/assistant text) so\n * a send can read `priorMessages` synchronously; the whole rich turn (user +\n * assistant + tool blocks) lands on disk once per send via {@link persistTurnToTranscript}\n * (fed by `run.conversation()`). Hydration on resume reconstructs the session by\n * walking the transcript DAG (`readSessionMessages`).\n *\n * @internal\n */\n\n// `SessionMessage` lives in `./session-types.ts` (leaf types file). Re-exported\n// for back-compat with downstream importers that pulled it from here.\nexport type { SessionMessage } from \"./session-types.js\";\n\nimport type { SessionMessage } from \"./session-types.js\";\n\n// M75 — the cache lives in a leaf; see session-cache.ts for the reason (cycle broken by extraction).\nexport {\n hydratedKeys,\n invalidateSessionCache,\n sessions,\n transcriptKey,\n} from \"./session-cache.js\";\n\nimport { diag } from \"../diagnostics.js\";\nimport { hydratedKeys, sessions, transcriptKey } from \"./session-cache.js\";\n\nconst pendingWrites = new Map<string, Promise<void>>();\nconst recordCounts = new Map<string, number>();\n\n/**\n * Append a session message to the in-memory cache only. Disk persistence for the\n * whole turn happens once per send via {@link persistTurnToTranscript}; the cache\n * feeds `priorMessages` / `onBeforeSend.previousMessageCount` synchronously.\n *\n * @internal\n */\nexport function appendSessionMessage(agentId: string, message: SessionMessage): void {\n const existing = sessions.get(agentId) ?? [];\n existing.push(message);\n // `delete` + `set` reinserts at the END: a JS `Map` preserves insertion order, so the first key\n // is always the least recently touched. That is the entire LRU, with no new structure (parsimony\n // rungs 2/5 — the ordering we need is already a language guarantee).\n sessions.delete(agentId);\n sessions.set(agentId, existing);\n enforceCeiling();\n}\n\n/**\n * Ceiling on sessions kept in memory.\n *\n * The runtime only reads the **active** session; the rest is pure cache, rebuildable from the\n * on-disk transcript. 32 is deliberately generous — the primary removal path is the explicit\n * `discardSession()` at the end of the agent's life, and this ceiling is a safety net against a\n * long-lived process running hundreds of sessions (plan risk #2: a tight ceiling could evict a\n * session still referenced by an in-flight async path).\n */\nexport const MAX_CACHED_SESSIONS = 32;\n\nfunction enforceCeiling(): void {\n while (sessions.size > MAX_CACHED_SESSIONS) {\n const oldest = sessions.keys().next().value;\n if (oldest === undefined) return;\n sessions.delete(oldest);\n forgetBookkeeping(oldest);\n }\n}\n\n/**\n * Erases the bookkeeping for an `agentId` across EVERY `cwd` it appears in.\n *\n * The three maps are keyed by `transcriptKey(cwd, agentId)`; `sessions` is the only one keyed by the\n * raw `agentId`. The ceiling's first version deleted from all three using `sessions`' key — that is,\n * deleted nothing — and left `hydratedKeys` **orphaned**. Since `hydrateSession` returns early when\n * the marker is present, an evicted session came back **empty** instead of rehydrating from disk:\n * silent amnesia, and a regression new to M95, because before it nothing evicted.\n *\n * The ceiling only knows the `agentId`, not the `cwd`, so it scans by suffix — which is the format\n * `transcriptKey` produces. A scan rather than an index because these maps hold tens of entries, not\n * thousands: a reverse index here would be new structure for a problem that does not exist.\n */\nfunction forgetBookkeeping(agentId: string): void {\n const suffix = transcriptKey(\"\", agentId).slice(0 - agentId.length - 2);\n for (const k of [...hydratedKeys]) if (k.endsWith(suffix)) hydratedKeys.delete(k);\n for (const k of [...pendingWrites.keys()]) if (k.endsWith(suffix)) pendingWrites.delete(k);\n for (const k of [...recordCounts.keys()]) if (k.endsWith(suffix)) recordCounts.delete(k);\n}\n\n/**\n * Erases the agent's module bookkeeping and returns how many entries were removed.\n *\n * M95 — `invalidateSessionCache` used to clear **two** of the four maps (`sessions`, `hydratedKeys`);\n * `pendingWrites` and `recordCounts` were never touched by id, so they grew for the life of the\n * process. Neither is large per entry — the leak is in count, not volume — but a cache with no owner\n * for removal is a cache that only grows.\n *\n * Returns the count so the caller can prove the removal; a second discard returns 0, which is what\n * makes the idempotency test possible without exposing the maps.\n */\nexport function discardSession(cwd: string, agentId: string): number {\n const key = transcriptKey(cwd, agentId);\n let removed = 0;\n // `sessions` is NOT erased here — and the distinction is measured, not aesthetic. It holds the\n // readable conversation, and there is a legitimate reader AFTER dispose: the golden\n // `two-concurrent-sends-serialize` calls `getSessionMessages(agentId)` after `agent.dispose()`.\n // Erasing it here returned an empty list and broke two goldens. What bounds it is the LRU ceiling\n // above; the three below are pure bookkeeping, with no post-dispose reader.\n //\n // The key is `transcriptKey(cwd, agentId)` in ALL THREE — not the raw `agentId`. The first version\n // erased two of them by `agentId` and therefore **never erased anything**; the test did not catch\n // it because it only asserted that the SECOND call returns 0, which is true either way.\n if (hydratedKeys.delete(key)) removed++;\n if (pendingWrites.delete(key)) removed++;\n if (recordCounts.delete(key)) removed++;\n return removed;\n}\n\nexport function getSessionMessages(agentId: string): SessionMessage[] {\n return sessions.get(agentId) ?? [];\n}\n\n/**\n * Persist a full conversation turn (user + assistant + tool blocks) to the native\n * transcript. Chained per-(agent, transcript) so on-disk order matches send order,\n * and fire-and-forget so `send()` is not blocked by disk I/O. Every\n * M50 — when the caller supplies `turn.autoCompact`, size-driven auto-compaction (usage real vs\n * the model's context window) runs in this same chain, surfaced via the optional `onCompact` observer.\n *\n * @internal\n */\nexport function persistTurnToTranscript(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n onCompact?: () => void,\n): void {\n const key = transcriptKey(loc.cwd, loc.agentId);\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\n const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {\n try {\n await persistTurn(store, loc, sessionId, turn);\n const count = (recordCounts.get(key) ?? 0) + 1;\n recordCounts.set(key, count);\n // M50 — the 50-turn no-summary boundary stub is GONE (it silently amnesia'd the session).\n // Auto-compaction is now size-driven with a real summary: see `maybeAutoCompact` below,\n // invoked in this same write chain by the post-run lifecycle when usage is known.\n if (turn.autoCompact !== undefined) {\n const { autoCompactIfNeeded } = await import(\"./compact-session.js\");\n const fired = await autoCompactIfNeeded({\n store,\n loc,\n sessionId,\n usageTotal: turn.autoCompact.usageTotal,\n contextWindow: turn.autoCompact.contextWindow,\n turnCount: count,\n summarize: turn.autoCompact.summarize,\n });\n if (fired) onCompact?.();\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}\\n`);\n }\n });\n pendingWrites.set(\n key,\n chained.then(\n () => undefined,\n () => undefined,\n ),\n );\n}\n\n/**\n * Load the persisted transcript into the in-memory cache. Idempotent per\n * (baseDir, cwd, agentId). Call once per agent lifecycle before the first read.\n *\n * @internal\n */\nexport async function hydrateSession(\n agentId: string,\n loc: { store: SessionStore; cwd: string },\n): Promise<void> {\n const key = transcriptKey(loc.cwd, agentId);\n if (hydratedKeys.has(key)) return;\n hydratedKeys.add(key);\n\n const persisted = await readSessionMessages(loc.store, agentId);\n if (persisted.length === 0) return;\n // M51 review F4 — the DISK is the source of truth at hydration time: after an invalidation\n // (compact/inject), an in-flight turn may have repopulated the cache with a SINGLE message before\n // this hydrate ran; the old \"skip when non-empty\" guard then pinned the parent to a 1-message\n // context (history + injected pair lost until restart). The persist chain serializes writes, so\n // the disk already contains that in-flight turn — replacing is always correct.\n sessions.set(agentId, persisted);\n}\n\n/**\n * Wait for all pending transcript writes to settle. Used by tests and by the\n * agent dispose path so on-disk state matches in-memory before the caller proceeds.\n *\n * @internal\n */\nexport async function flushSessionWrites(): Promise<void> {\n while (pendingWrites.size > 0) {\n const all = Array.from(pendingWrites.values());\n pendingWrites.clear();\n await Promise.all(all);\n }\n}\n\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\n\n/**\n * M50 review F1 — drop BOTH the message cache and the hydration marker so the NEXT send re-hydrates\n * from disk. Without this, a compaction only helps after a process restart: the live process keeps\n * sending the full pre-compact history (the cache is read synchronously by every send).\n */\n/**\n * M50 review F5 — run `fn` serialized on the SAME per-(cwd,agentId) write chain the per-turn\n * persistence uses, so a manual `Agent.compact` can never interleave with an in-flight turn's\n * writes (boundary landing mid-turn would orphan the turn from the replay).\n */\nexport function enqueueSessionWrite<T>(\n cwd: string,\n agentId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = transcriptKey(cwd, agentId);\n const prior = pendingWrites.get(key) ?? Promise.resolve();\n const result = prior.then(fn);\n pendingWrites.set(\n key,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n return result;\n}\n\n/** Test-only: drop every cached session and hydration marker. @internal */\nexport function clearAllSessions(): void {\n sessions.clear();\n hydratedKeys.clear();\n recordCounts.clear();\n // M50 review F11 — the auto-compact attempt marks live on globalThis; tests reset them here.\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n g[sym]?.clear();\n}\n"]}
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunkYPEPCZHF_cjs = require('./chunk-YPEPCZHF.cjs');
|
|
4
|
+
var os = require('os');
|
|
5
|
+
var path = require('path');
|
|
6
|
+
var promises = require('fs/promises');
|
|
7
|
+
var fs = require('fs');
|
|
8
|
+
var zod = require('zod');
|
|
9
|
+
|
|
10
|
+
var HEAD_RATIO = 0.7;
|
|
11
|
+
var TAIL_RATIO = 0.2;
|
|
12
|
+
var MARKER = "\n\n\u2026[truncated by theokit]\n\n";
|
|
13
|
+
var DEFAULT_MAX_BYTES_PER_FILE = 4e4;
|
|
14
|
+
function truncateWithMarker(content, max) {
|
|
15
|
+
if (content.length <= max) {
|
|
16
|
+
return { truncated: false, finalContent: content };
|
|
17
|
+
}
|
|
18
|
+
if (max <= MARKER.length) {
|
|
19
|
+
return { truncated: true, finalContent: content.slice(0, max) };
|
|
20
|
+
}
|
|
21
|
+
const budget = max - MARKER.length;
|
|
22
|
+
const headBytes = Math.floor(budget * (HEAD_RATIO / (HEAD_RATIO + TAIL_RATIO)));
|
|
23
|
+
const tailBytes = budget - headBytes;
|
|
24
|
+
return {
|
|
25
|
+
truncated: true,
|
|
26
|
+
finalContent: content.slice(0, headBytes) + MARKER + content.slice(-tailBytes)
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
async function loadPlainMarkdown(absPath, opts = {}) {
|
|
30
|
+
const max = opts.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE;
|
|
31
|
+
let content;
|
|
32
|
+
try {
|
|
33
|
+
content = await promises.readFile(absPath, "utf8");
|
|
34
|
+
} catch {
|
|
35
|
+
return void 0;
|
|
36
|
+
}
|
|
37
|
+
const { truncated, finalContent } = truncateWithMarker(content, max);
|
|
38
|
+
if (truncated) {
|
|
39
|
+
emitTruncationCounter(absPath);
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
source: absPath,
|
|
43
|
+
content: finalContent,
|
|
44
|
+
originalBytes: content.length,
|
|
45
|
+
truncated
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function emitTruncationCounter(source) {
|
|
49
|
+
const tracer = globalThis.__theokit_tracer;
|
|
50
|
+
if (tracer?.inc === void 0) return;
|
|
51
|
+
try {
|
|
52
|
+
tracer.inc("context_files_truncated", { file: source });
|
|
53
|
+
} catch {
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function realOrResolved(path) {
|
|
57
|
+
try {
|
|
58
|
+
return fs.realpathSync(path);
|
|
59
|
+
} catch {
|
|
60
|
+
return path;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function insideRoot(target, root) {
|
|
64
|
+
const rel = path.relative(realOrResolved(root), realOrResolved(target));
|
|
65
|
+
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// src/internal/runtime/context/context-import-resolver.ts
|
|
69
|
+
var IMPORT_RE = /^@(\S+)\s*$/gm;
|
|
70
|
+
var MAX_HOPS = 5;
|
|
71
|
+
async function resolveImports(content, basePath, opts) {
|
|
72
|
+
if (opts.depth >= MAX_HOPS) {
|
|
73
|
+
return `${content}
|
|
74
|
+
|
|
75
|
+
\u2026[@import depth limit ${MAX_HOPS} reached]
|
|
76
|
+
|
|
77
|
+
`;
|
|
78
|
+
}
|
|
79
|
+
const baseDir = path.dirname(basePath);
|
|
80
|
+
return replaceAsync(content, IMPORT_RE, async (raw) => {
|
|
81
|
+
const absolute = resolveImportPath(raw, baseDir);
|
|
82
|
+
if (opts.projectRoot !== void 0 && !insideRoot(absolute, opts.projectRoot)) {
|
|
83
|
+
return `[@import outside the project root, refused: ${raw}]`;
|
|
84
|
+
}
|
|
85
|
+
if (opts.visited.has(absolute)) {
|
|
86
|
+
return `[@import cycle detected: ${raw}]`;
|
|
87
|
+
}
|
|
88
|
+
opts.visited.add(absolute);
|
|
89
|
+
const loaded = await loadPlainMarkdown(absolute, { maxBytesPerFile: opts.maxBytesPerFile });
|
|
90
|
+
if (loaded === void 0) {
|
|
91
|
+
return `[@import not found: ${raw}]`;
|
|
92
|
+
}
|
|
93
|
+
return resolveImports(loaded.content, absolute, {
|
|
94
|
+
visited: opts.visited,
|
|
95
|
+
depth: opts.depth + 1,
|
|
96
|
+
maxBytesPerFile: opts.maxBytesPerFile,
|
|
97
|
+
...opts.projectRoot === void 0 ? {} : { projectRoot: opts.projectRoot }
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
function resolveImportPath(raw, baseDir) {
|
|
102
|
+
if (raw.startsWith("~/")) {
|
|
103
|
+
return path.resolve(path.join(os.homedir(), raw.slice(2)));
|
|
104
|
+
}
|
|
105
|
+
if (path.isAbsolute(raw)) {
|
|
106
|
+
return path.resolve(raw);
|
|
107
|
+
}
|
|
108
|
+
return path.resolve(path.join(baseDir, raw));
|
|
109
|
+
}
|
|
110
|
+
async function replaceAsync(content, re, replacer) {
|
|
111
|
+
const matches = [];
|
|
112
|
+
const localRe = new RegExp(re.source, re.flags);
|
|
113
|
+
let m;
|
|
114
|
+
while ((m = localRe.exec(content)) !== null) {
|
|
115
|
+
matches.push({ match: m[0], raw: m[1] ?? "", index: m.index });
|
|
116
|
+
if (m.index === localRe.lastIndex) localRe.lastIndex += 1;
|
|
117
|
+
}
|
|
118
|
+
if (matches.length === 0) return content;
|
|
119
|
+
let result = "";
|
|
120
|
+
let cursor = 0;
|
|
121
|
+
for (const entry of matches) {
|
|
122
|
+
result += content.slice(cursor, entry.index);
|
|
123
|
+
result += await replacer(entry.raw);
|
|
124
|
+
cursor = entry.index + entry.match.length;
|
|
125
|
+
}
|
|
126
|
+
result += content.slice(cursor);
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/internal/runtime/context/context-glob.ts
|
|
131
|
+
function globToRegex(glob) {
|
|
132
|
+
const compiled = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*\//g, "::GLOBSTAR_SLASH::").replace(/\*\*/g, "::GLOBSTAR::").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/::GLOBSTAR_SLASH::/g, "(?:.*/)?").replace(/::GLOBSTAR::/g, ".*");
|
|
133
|
+
return new RegExp(`^${compiled}$`);
|
|
134
|
+
}
|
|
135
|
+
function anyGlobMatches(patterns, paths) {
|
|
136
|
+
if (patterns.length === 0 || paths.length === 0) return false;
|
|
137
|
+
const res = patterns.map(globToRegex);
|
|
138
|
+
return paths.some((p) => res.some((re) => re.test(p)));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// src/internal/runtime/context/context-yaml-lite.ts
|
|
142
|
+
var FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/;
|
|
143
|
+
function splitFrontmatter(content) {
|
|
144
|
+
const m = FRONTMATTER_RE.exec(content);
|
|
145
|
+
if (m === null) return { yaml: void 0, body: content };
|
|
146
|
+
return { yaml: m[1] ?? "", body: m[2] ?? "" };
|
|
147
|
+
}
|
|
148
|
+
function parseSimpleYaml(yaml) {
|
|
149
|
+
const out = {};
|
|
150
|
+
const lines = yaml.split(/\r?\n/);
|
|
151
|
+
let i = 0;
|
|
152
|
+
while (i < lines.length) {
|
|
153
|
+
const line = lines[i];
|
|
154
|
+
i += 1;
|
|
155
|
+
if (line === void 0) continue;
|
|
156
|
+
const trimmed = line.trim();
|
|
157
|
+
if (trimmed === "" || trimmed.startsWith("#")) continue;
|
|
158
|
+
const colon = trimmed.indexOf(":");
|
|
159
|
+
if (colon === -1) throw new Error(`Invalid YAML line: ${trimmed}`);
|
|
160
|
+
const key = trimmed.slice(0, colon).trim();
|
|
161
|
+
const rest = trimmed.slice(colon + 1).trim();
|
|
162
|
+
if (rest === "") {
|
|
163
|
+
const items = [];
|
|
164
|
+
while (i < lines.length) {
|
|
165
|
+
const next = lines[i];
|
|
166
|
+
if (next === void 0) break;
|
|
167
|
+
const nextTrim = next.trim();
|
|
168
|
+
if (nextTrim.startsWith("- ")) {
|
|
169
|
+
items.push(parseScalar(nextTrim.slice(2).trim()));
|
|
170
|
+
i += 1;
|
|
171
|
+
} else if (nextTrim === "") {
|
|
172
|
+
i += 1;
|
|
173
|
+
} else {
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
out[key] = items;
|
|
178
|
+
} else if (rest.startsWith("[") && rest.endsWith("]")) {
|
|
179
|
+
const inner = rest.slice(1, -1).trim();
|
|
180
|
+
out[key] = inner === "" ? [] : inner.split(",").map((s) => parseScalar(s.trim().replace(/^["']|["']$/g, "")));
|
|
181
|
+
} else {
|
|
182
|
+
out[key] = parseScalar(rest);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
function parseScalar(s) {
|
|
188
|
+
if (s === "true") return true;
|
|
189
|
+
if (s === "false") return false;
|
|
190
|
+
if (/^-?\d+$/.test(s)) return parseInt(s, 10);
|
|
191
|
+
return s.replace(/^["']|["']$/g, "");
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// src/internal/runtime/context/context-rules-frontmatter.ts
|
|
195
|
+
var RulesFrontmatterSchema = zod.z.object({
|
|
196
|
+
description: zod.z.string().optional(),
|
|
197
|
+
paths: zod.z.array(zod.z.string()).optional(),
|
|
198
|
+
globs: zod.z.array(zod.z.string()).optional(),
|
|
199
|
+
alwaysApply: zod.z.boolean().optional(),
|
|
200
|
+
enabled: zod.z.boolean().optional()
|
|
201
|
+
});
|
|
202
|
+
function parseRules(content) {
|
|
203
|
+
const { yaml, body } = splitFrontmatter(content);
|
|
204
|
+
if (yaml === void 0) {
|
|
205
|
+
return { frontmatter: { alwaysApply: true }, body: content };
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
const parsed = parseSimpleYaml(yaml);
|
|
209
|
+
const validated = RulesFrontmatterSchema.safeParse(parsed);
|
|
210
|
+
if (!validated.success) return void 0;
|
|
211
|
+
return { frontmatter: validated.data, body };
|
|
212
|
+
} catch {
|
|
213
|
+
return void 0;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function shouldActivateRule(fm, inScopePaths) {
|
|
217
|
+
if (fm.enabled === false) return false;
|
|
218
|
+
if (fm.alwaysApply === true) return true;
|
|
219
|
+
const patterns = [...fm.paths ?? [], ...fm.globs ?? []];
|
|
220
|
+
if (patterns.length === 0) return false;
|
|
221
|
+
return anyGlobMatches(patterns, inScopePaths);
|
|
222
|
+
}
|
|
223
|
+
var McdFrontmatterSchema = zod.z.object({
|
|
224
|
+
description: zod.z.string().optional(),
|
|
225
|
+
globs: zod.z.array(zod.z.string()).optional(),
|
|
226
|
+
alwaysApply: zod.z.boolean().optional()
|
|
227
|
+
});
|
|
228
|
+
function parseMdc(content) {
|
|
229
|
+
const { yaml, body } = splitFrontmatter(content);
|
|
230
|
+
if (yaml === void 0) {
|
|
231
|
+
return { frontmatter: { alwaysApply: true }, body: content };
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
const parsed = parseSimpleYaml(yaml);
|
|
235
|
+
const validated = McdFrontmatterSchema.safeParse(parsed);
|
|
236
|
+
if (!validated.success) return void 0;
|
|
237
|
+
return { frontmatter: validated.data, body };
|
|
238
|
+
} catch {
|
|
239
|
+
return void 0;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
function shouldActivate(fm, touchedFiles) {
|
|
243
|
+
if (fm.alwaysApply === true) return true;
|
|
244
|
+
if (fm.globs === void 0 || fm.globs.length === 0) return false;
|
|
245
|
+
return anyGlobMatches(fm.globs, touchedFiles);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// src/internal/runtime/context/context-discovery-runner.ts
|
|
249
|
+
async function runDiscovery(opts) {
|
|
250
|
+
const gitRoot = chunkYPEPCZHF_cjs.findGitRoot(opts.cwd);
|
|
251
|
+
const specs = opts.specs ?? chunkYPEPCZHF_cjs.DEFAULT_DISCOVERY_SPECS;
|
|
252
|
+
const out = [];
|
|
253
|
+
const seenReal = /* @__PURE__ */ new Set();
|
|
254
|
+
for (const spec of specs) {
|
|
255
|
+
if (opts.skipLegacyTheokitContext && spec.id === "theokit-context") continue;
|
|
256
|
+
const paths = await resolvePathsForSpec(spec, opts.cwd, gitRoot);
|
|
257
|
+
for (const path of paths) {
|
|
258
|
+
if (seenReal.has(path)) continue;
|
|
259
|
+
seenReal.add(path);
|
|
260
|
+
const source = await loadOneSource(spec, path, opts, gitRoot);
|
|
261
|
+
if (source !== void 0) out.push(source);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return out;
|
|
265
|
+
}
|
|
266
|
+
async function resolvePathsForSpec(spec, cwd, gitRoot) {
|
|
267
|
+
if (spec.scope === "cwd-only") {
|
|
268
|
+
return chunkYPEPCZHF_cjs.walkUpForFile(cwd, spec.pattern, cwd);
|
|
269
|
+
}
|
|
270
|
+
if (spec.scope === "git-root-walk") {
|
|
271
|
+
return chunkYPEPCZHF_cjs.walkUpForFile(cwd, spec.pattern, gitRoot ?? cwd);
|
|
272
|
+
}
|
|
273
|
+
return chunkYPEPCZHF_cjs.walkUpForGlob(cwd, spec.pattern);
|
|
274
|
+
}
|
|
275
|
+
async function loadOneSource(spec, path$1, opts, gitRoot) {
|
|
276
|
+
const relPath = path.relative(gitRoot ?? opts.cwd, path.dirname(path$1));
|
|
277
|
+
const needsSuffix = spec.scope !== "cwd-only" && relPath !== "" && relPath !== ".";
|
|
278
|
+
const id = needsSuffix ? `${spec.id}@${relPath}` : spec.id;
|
|
279
|
+
if (spec.parser === "mdc") {
|
|
280
|
+
return loadMdcSource(spec, path$1, id, opts);
|
|
281
|
+
}
|
|
282
|
+
if (spec.parser === "rules-frontmatter") {
|
|
283
|
+
return loadRulesSource(spec, path$1, id, opts);
|
|
284
|
+
}
|
|
285
|
+
if (spec.parser === "frontmatter-zod") {
|
|
286
|
+
return void 0;
|
|
287
|
+
}
|
|
288
|
+
return loadPlainMarkdownSource(spec, path$1, id, opts, gitRoot);
|
|
289
|
+
}
|
|
290
|
+
async function loadParsedSource(spec, path, id, parse, isActive) {
|
|
291
|
+
let raw;
|
|
292
|
+
try {
|
|
293
|
+
raw = await promises.readFile(path, "utf8");
|
|
294
|
+
} catch {
|
|
295
|
+
return void 0;
|
|
296
|
+
}
|
|
297
|
+
const parsed = parse(raw);
|
|
298
|
+
if (parsed === void 0 || !isActive(parsed.frontmatter)) return void 0;
|
|
299
|
+
return { id, source: path, content: parsed.body, priority: spec.priority, truncated: false };
|
|
300
|
+
}
|
|
301
|
+
function loadMdcSource(spec, path, id, opts) {
|
|
302
|
+
return loadParsedSource(
|
|
303
|
+
spec,
|
|
304
|
+
path,
|
|
305
|
+
id,
|
|
306
|
+
parseMdc,
|
|
307
|
+
(fm) => shouldActivate(fm, opts.touchedFiles ?? [])
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
function loadRulesSource(spec, path, id, opts) {
|
|
311
|
+
return loadParsedSource(
|
|
312
|
+
spec,
|
|
313
|
+
path,
|
|
314
|
+
id,
|
|
315
|
+
parseRules,
|
|
316
|
+
(fm) => shouldActivateRule(fm, opts.touchedFiles ?? [])
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
async function loadPlainMarkdownSource(spec, path, id, opts, gitRoot) {
|
|
320
|
+
const loaded = await loadPlainMarkdown(path, { maxBytesPerFile: opts.maxBytesPerFile });
|
|
321
|
+
if (loaded === void 0) return void 0;
|
|
322
|
+
let content = loaded.content;
|
|
323
|
+
if (spec.followImports) {
|
|
324
|
+
content = await resolveImports(content, path, {
|
|
325
|
+
visited: /* @__PURE__ */ new Set([path]),
|
|
326
|
+
depth: 0,
|
|
327
|
+
maxBytesPerFile: opts.maxBytesPerFile,
|
|
328
|
+
// The document carrying the import is repository-controlled, so the repository is the
|
|
329
|
+
// boundary it may not cross. Without this, `CLAUDE.md` / `GEMINI.md` — the two specs
|
|
330
|
+
// with `followImports: true` — could name any absolute or `~/` path and have it
|
|
331
|
+
// inlined into the system prompt.
|
|
332
|
+
projectRoot: opts.importRoot ?? gitRoot ?? opts.cwd
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
return {
|
|
336
|
+
id,
|
|
337
|
+
source: path,
|
|
338
|
+
content,
|
|
339
|
+
priority: spec.priority,
|
|
340
|
+
truncated: loaded.truncated
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
exports.DEFAULT_MAX_BYTES_PER_FILE = DEFAULT_MAX_BYTES_PER_FILE;
|
|
345
|
+
exports.insideRoot = insideRoot;
|
|
346
|
+
exports.parseRules = parseRules;
|
|
347
|
+
exports.resolveImports = resolveImports;
|
|
348
|
+
exports.runDiscovery = runDiscovery;
|
|
349
|
+
exports.shouldActivateRule = shouldActivateRule;
|
|
350
|
+
exports.truncateWithMarker = truncateWithMarker;
|
|
351
|
+
//# sourceMappingURL=chunk-GAXYZXYY.cjs.map
|
|
352
|
+
//# sourceMappingURL=chunk-GAXYZXYY.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/context/context-loaders.ts","../src/internal/runtime/context/path-containment.ts","../src/internal/runtime/context/context-import-resolver.ts","../src/internal/runtime/context/context-glob.ts","../src/internal/runtime/context/context-yaml-lite.ts","../src/internal/runtime/context/context-rules-frontmatter.ts","../src/internal/runtime/context/context-mdc-parser.ts","../src/internal/runtime/context/context-discovery-runner.ts"],"names":["readFile","realpathSync","relative","isAbsolute","dirname","resolvePath","join","homedir","z","findGitRoot","DEFAULT_DISCOVERY_SPECS","walkUpForFile","walkUpForGlob","path"],"mappings":";;;;;;;;;AAaA,IAAM,UAAA,GAAa,GAAA;AACnB,IAAM,UAAA,GAAa,GAAA;AACnB,IAAM,MAAA,GAAS,sCAAA;AAGR,IAAM,0BAAA,GAA6B;AAiCnC,SAAS,kBAAA,CAAmB,SAAiB,GAAA,EAA6B;AAC/E,EAAA,IAAI,OAAA,CAAQ,UAAU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chunk-GAXYZXYY.cjs","sourcesContent":["/**\n * Context file loaders + truncation (T1.2, ADRs D154 / D155 / D159).\n *\n * Reads context source files from disk, applies the per-file size cap\n * with 70%/20% head/tail truncation, and emits the\n * `context_files_truncated` telemetry counter when the cap fires.\n * Pure (no I/O) for `truncateWithMarker` — testable in isolation.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\n\nconst HEAD_RATIO = 0.7;\nconst TAIL_RATIO = 0.2;\nconst MARKER = \"\\n\\n…[truncated by theokit]\\n\\n\";\n\n/** Default per-file cap (40k chars ≈ 10k tokens). D155. */\nexport const DEFAULT_MAX_BYTES_PER_FILE = 40_000;\n\nexport interface LoadedSource {\n /** Absolute path the content came from. */\n readonly source: string;\n readonly content: string;\n readonly originalBytes: number;\n readonly truncated: boolean;\n}\n\nexport interface TruncateResult {\n readonly truncated: boolean;\n readonly finalContent: string;\n}\n\n/**\n * Cap `content` at `max` characters with 70%/20% head/tail truncation\n * and an explicit marker. Pure — no I/O, no telemetry.\n *\n * EC-C: when `max <= MARKER.length`, skip the marker entirely and\n * return a head-only slice. Without this guard, `budget = max -\n * MARKER.length` would go negative and `content.slice(-tailBytes)`\n * would slice from the END of the string rather than truncating.\n *\n * EC-H: codepoint integrity — `String.slice()` operates on UTF-16\n * code units, which can split surrogate pairs. We accept that\n * trailing/leading replacement chars (U+FFFD) may appear at boundaries.\n * Modern LLMs tolerate them; byte-exact safety would require Buffer\n * slicing + TextDecoder with `fatal: true` retry, which adds complexity\n * without value.\n *\n * @public\n */\nexport function truncateWithMarker(content: string, max: number): TruncateResult {\n if (content.length <= max) {\n return { truncated: false, finalContent: content };\n }\n // EC-C: max too small to fit even the marker — return head-only slice.\n if (max <= MARKER.length) {\n return { truncated: true, finalContent: content.slice(0, max) };\n }\n const budget = max - MARKER.length;\n const headBytes = Math.floor(budget * (HEAD_RATIO / (HEAD_RATIO + TAIL_RATIO)));\n const tailBytes = budget - headBytes;\n return {\n truncated: true,\n finalContent: content.slice(0, headBytes) + MARKER + content.slice(-tailBytes),\n };\n}\n\n/**\n * Read a file from disk and apply the per-file cap. Emits telemetry\n * counter when truncation fires.\n *\n * EC-G: file deleted between discovery and read (FS race) → returns\n * `undefined`, never throws.\n *\n * @internal\n */\nexport async function loadPlainMarkdown(\n absPath: string,\n opts: { maxBytesPerFile?: number } = {},\n): Promise<LoadedSource | undefined> {\n const max = opts.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE;\n let content: string;\n try {\n content = await readFile(absPath, \"utf8\");\n } catch {\n // EC-G: ENOENT / EACCES / etc → caller treats as missing.\n return undefined;\n }\n const { truncated, finalContent } = truncateWithMarker(content, max);\n if (truncated) {\n emitTruncationCounter(absPath);\n }\n return {\n source: absPath,\n content: finalContent,\n originalBytes: content.length,\n truncated,\n };\n}\n\n/**\n * EC-L: telemetry no-op when OTel is not imported. We import the tracer\n * lazily and use `safeCall` so the lookup never throws and never pulls\n * OTel into the import graph for users without `@opentelemetry/api`\n * installed.\n *\n * @internal\n */\nfunction emitTruncationCounter(source: string): void {\n // Lazy resolution via globalThis avoids static import of telemetry/tracer.\n // Tests can spy via the same path; production users without OTel see no-op.\n const tracer = (\n globalThis as { __theokit_tracer?: { inc?: (k: string, attrs: unknown) => void } }\n ).__theokit_tracer;\n if (tracer?.inc === undefined) return;\n try {\n tracer.inc(\"context_files_truncated\", { file: source });\n } catch {\n // Telemetry must never break the loader.\n }\n}\n","/**\n * The one rule for \"is this resolved path inside that root\".\n *\n * Extracted because the package held it twice, at different strengths, for the same question. The\n * correct version lived as a private function in `context-import-resolver.ts`, written for the\n * 4.41.1 patch; the context manager had its own `absolute.startsWith(resolvePath(cwd))`, which\n * admits two escapes:\n *\n * - **No separator boundary.** With `root = /home/user/proj`, the path `/home/user/proj-evil/x`\n * starts with the root string and is NOT inside it. A sibling directory whose name merely\n * extends the project's is enough; no `..` past the parent is needed.\n * - **Lexical, not real.** A symlink whose name sits inside the root and whose target does not\n * passes any comparison made before symlink resolution.\n *\n * The obvious escapes (`../../etc/passwd`, an absolute path) ARE refused by a prefix test, which is\n * why the weaker version survived review: it looks like it works on the inputs a reader tries.\n *\n * Both readers of repository-supplied paths now share this module. That is DRY about the RULE\n * rather than about line count — one piece of knowledge, one representation, so the two cannot\n * drift apart again.\n *\n * @internal\n */\n\nimport { realpathSync } from \"node:fs\";\nimport { isAbsolute, relative } from \"node:path\";\n\n/**\n * The real path, or the lexical one when it cannot be resolved.\n *\n * The fallback is load-bearing rather than defensive: the context manager checks containment BEFORE\n * it stats the file, so a source that is legitimately absent must still be judged on its declared\n * location instead of being refused for the wrong reason.\n *\n * @internal\n */\nexport function realOrResolved(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\n/**\n * Whether `target` is inside `root`, compared AFTER symlink resolution.\n *\n * `relative()` supplies the separator boundary that a prefix test lacks: it answers `..` for a\n * sibling, `''` for the root itself, and an absolute path when the two are on different roots.\n *\n * @internal\n */\nexport function insideRoot(target: string, root: string): boolean {\n const rel = relative(realOrResolved(root), realOrResolved(target));\n return rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel);\n}\n","/**\n * `@path/to/file` import resolver (T2.1, ADR D156).\n *\n * Anthropic/Gemini convention: lines that are EXACTLY `@path` get\n * replaced with the imported file's content, recursively (5-hop cap),\n * with cycle detection. Inline `see @x.md, also @y.md` references are\n * NOT resolved (EC-Q — own-line only, mirrors Anthropic's actual\n * behavior).\n *\n * EC-D fix: every imported file is itself capped at `maxBytesPerFile`\n * via `loadPlainMarkdown` BEFORE concatenation. Prevents a CLAUDE.md\n * with 5 imports of 30k each from ballooning to 150k of imported\n * content before the outer cap fires.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, resolve as resolvePath } from \"node:path\";\n\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\nimport { insideRoot } from \"./path-containment.js\";\n\n/** EC-Q: line-anchored. `@path` must be alone on its line. */\nconst IMPORT_RE = /^@(\\S+)\\s*$/gm;\nconst MAX_HOPS = 5;\n\nexport interface ResolveImportsOptions {\n /** Absolute paths already resolved (cycle detection). */\n readonly visited: Set<string>;\n /** Current recursion depth — caps at MAX_HOPS. */\n readonly depth: number;\n /** Per-import file cap (EC-D). Forwarded to loadPlainMarkdown. */\n readonly maxBytesPerFile: number;\n /**\n * The directory an import may not escape. When set, a target resolving outside it is\n * refused and replaced with a placeholder.\n *\n * The file carrying the import is REPOSITORY-CONTROLLED — `CLAUDE.md` and `GEMINI.md`\n * are the two default specs with `followImports: true`, and both are found by\n * `git-root-walk` inside the tree the agent was pointed at. Without a root, a cloned\n * repository could name `@~/.ssh/id_rsa` or any absolute path and have its contents\n * inlined into the system prompt, and from there sent to the model provider. The\n * traversal guard that already existed (`isSafePattern`) guards the discovery PATTERN,\n * not the import TARGET, so it never saw this.\n *\n * OPTIONAL, so a caller outside the discovery path keeps the previous behaviour rather\n * than breaking on an upgrade. `runDiscovery` always supplies `gitRoot ?? cwd` — the\n * same value it already uses to keep absolute paths out of `<source name=\"\">`.\n */\n readonly projectRoot?: string;\n}\n\n/**\n * Resolve `@path` directives in `content`. Each match is replaced with\n * the imported file content (already cap-truncated per EC-D), and\n * recursion continues on the resolved content until MAX_HOPS or cycle.\n *\n * Failure modes (placeholders, never throws):\n * - file not found → `[@import not found: <path>]`\n * - cycle detected → `[@import cycle detected: <path>]`\n * - depth exceeded → trailing `\\n\\n…[@import depth limit 5 reached]\\n\\n`\n *\n * @internal\n */\nexport async function resolveImports(\n content: string,\n basePath: string,\n opts: ResolveImportsOptions,\n): Promise<string> {\n if (opts.depth >= MAX_HOPS) {\n return `${content}\\n\\n…[@import depth limit ${MAX_HOPS} reached]\\n\\n`;\n }\n const baseDir = dirname(basePath);\n return replaceAsync(content, IMPORT_RE, async (raw) => {\n const absolute = resolveImportPath(raw, baseDir);\n // Containment BEFORE the read. Reporting the refusal after loading the file would\n // already have put the bytes in memory, and the placeholder names the path the author\n // wrote rather than the resolved one — echoing `/home/<user>/.ssh/id_rsa` back into the\n // prompt would leak the layout of the machine to the same untrusted document.\n if (opts.projectRoot !== undefined && !insideRoot(absolute, opts.projectRoot)) {\n return `[@import outside the project root, refused: ${raw}]`;\n }\n if (opts.visited.has(absolute)) {\n return `[@import cycle detected: ${raw}]`;\n }\n opts.visited.add(absolute);\n const loaded = await loadPlainMarkdown(absolute, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) {\n return `[@import not found: ${raw}]`;\n }\n // Recurse with same visited set + incremented depth. `projectRoot` is FORWARDED: an\n // imported file is repository-controlled too, so a root that applied only at depth 0\n // would be escapable in one extra hop.\n return resolveImports(loaded.content, absolute, {\n visited: opts.visited,\n depth: opts.depth + 1,\n maxBytesPerFile: opts.maxBytesPerFile,\n ...(opts.projectRoot === undefined ? {} : { projectRoot: opts.projectRoot }),\n });\n });\n}\n\nfunction resolveImportPath(raw: string, baseDir: string): string {\n if (raw.startsWith(\"~/\")) {\n return resolvePath(join(homedir(), raw.slice(2)));\n }\n if (isAbsolute(raw)) {\n return resolvePath(raw);\n }\n return resolvePath(join(baseDir, raw));\n}\n\n/**\n * Async equivalent of `String.prototype.replace` — sequential. Returns\n * `content` with every `re` match replaced by `await replacer(match)`.\n *\n * @internal\n */\nasync function replaceAsync(\n content: string,\n re: RegExp,\n replacer: (raw: string) => Promise<string>,\n): Promise<string> {\n const matches: Array<{ match: string; raw: string; index: number }> = [];\n // Reset lastIndex; clone the regex to avoid stateful traps.\n const localRe = new RegExp(re.source, re.flags);\n let m: RegExpExecArray | null;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic regex loop\n while ((m = localRe.exec(content)) !== null) {\n matches.push({ match: m[0], raw: m[1] ?? \"\", index: m.index });\n if (m.index === localRe.lastIndex) localRe.lastIndex += 1;\n }\n if (matches.length === 0) return content;\n let result = \"\";\n let cursor = 0;\n for (const entry of matches) {\n result += content.slice(cursor, entry.index);\n result += await replacer(entry.raw);\n cursor = entry.index + entry.match.length;\n }\n result += content.slice(cursor);\n return result;\n}\n","/**\n * Shared glob → RegExp compiler for context discovery (extracted from the\n * MDC parser so the `.cursor/rules/*.mdc` and `.theokit/rules/*.md` parsers\n * share ONE implementation — DRY, no new dependency).\n *\n * Supports `**` (any depth), `*` (single path segment, no `/`), `?` (single\n * non-separator char). Sufficient for the patterns Cursor and Claude Code\n * themselves recommend.\n *\n * @internal\n */\nexport function globToRegex(glob: string): RegExp {\n // Support **/ (zero-or-more path segments), ** (any depth), * (single\n // segment), ? (single non-separator char). `**/` collapses so `src/**/*.ts`\n // matches `src/foo.ts` AND `src/a/b/foo.ts` — the semantics Cursor and Claude\n // Code document (\"src/**/* → all files under src/\"). `*` and `?` never cross a\n // `/` (strict glob segment semantics). Escape other regex metas.\n const compiled = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*\\//g, \"::GLOBSTAR_SLASH::\")\n .replace(/\\*\\*/g, \"::GLOBSTAR::\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\?/g, \"[^/]\")\n .replace(/::GLOBSTAR_SLASH::/g, \"(?:.*/)?\")\n .replace(/::GLOBSTAR::/g, \".*\");\n return new RegExp(`^${compiled}$`);\n}\n\n/**\n * True when any of `patterns` glob-matches any of `paths`. Central helper so\n * both rule parsers agree on activation semantics.\n *\n * @internal\n */\nexport function anyGlobMatches(\n patterns: ReadonlyArray<string>,\n paths: ReadonlyArray<string>,\n): boolean {\n if (patterns.length === 0 || paths.length === 0) return false;\n const res = patterns.map(globToRegex);\n return paths.some((p) => res.some((re) => re.test(p)));\n}\n","/**\n * Minimal YAML-subset frontmatter parsing shared by the `.cursor/rules/*.mdc`\n * and `.theokit/rules/*.md` parsers (extracted for DRY — one parser, one set\n * of edge-case behaviours, no new dependency).\n *\n * Handles `key: value` lines (string scalars, booleans, integers) and `key:`\n * followed by indented `- item` arrays or inline `[a, b]` arrays. Sufficient\n * for the small, fixed frontmatter field sets these rule files use. Throws on\n * a truly malformed line (no colon).\n *\n * NOTE — distinct from the sibling `yaml-frontmatter.ts` `parseSimpleYaml` on\n * purpose: that one parses INLINE arrays only (`key: [a, b]`), whereas rule\n * files (`.cursor/rules/*.mdc`, `.theokit/rules/*.md`) use MULTI-LINE `- item`\n * lists (`paths:` / `globs:`), which this parser adds. Unifying onto the inline\n * parser would drop multi-line list support; unifying the other way would touch\n * the skills/subagents/persistence loaders that depend on the inline one. The\n * two intentionally coexist until a shared parser handles both shapes.\n *\n * @internal\n */\n\nconst FRONTMATTER_RE = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/;\n\nexport interface FrontmatterSplit {\n /** Raw YAML block between the `---` fences, or undefined when absent. */\n readonly yaml: string | undefined;\n /** The markdown body after the frontmatter (or the whole content). */\n readonly body: string;\n}\n\n/**\n * Split `---`-fenced frontmatter from the body. When no frontmatter fence is\n * present, `yaml` is undefined and `body` is the whole content.\n *\n * @internal\n */\nexport function splitFrontmatter(content: string): FrontmatterSplit {\n const m = FRONTMATTER_RE.exec(content);\n if (m === null) return { yaml: undefined, body: content };\n return { yaml: m[1] ?? \"\", body: m[2] ?? \"\" };\n}\n\n/**\n * Parse the minimal YAML subset. Throws on a line without a colon (malformed).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: YAML-subset parser handles scalars + multi-line arrays + inline arrays in a single pass; extracting helpers fragments the line-state machine.\nexport function parseSimpleYaml(yaml: string): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const lines = yaml.split(/\\r?\\n/);\n let i = 0;\n while (i < lines.length) {\n const line = lines[i];\n i += 1;\n if (line === undefined) continue;\n const trimmed = line.trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) continue;\n const colon = trimmed.indexOf(\":\");\n if (colon === -1) throw new Error(`Invalid YAML line: ${trimmed}`);\n const key = trimmed.slice(0, colon).trim();\n const rest = trimmed.slice(colon + 1).trim();\n if (rest === \"\") {\n // Possible array; collect indented `- item` lines.\n const items: string[] = [];\n while (i < lines.length) {\n const next = lines[i];\n if (next === undefined) break;\n const nextTrim = next.trim();\n if (nextTrim.startsWith(\"- \")) {\n items.push(parseScalar(nextTrim.slice(2).trim()) as string);\n i += 1;\n } else if (nextTrim === \"\") {\n i += 1;\n } else {\n break;\n }\n }\n out[key] = items;\n } else if (rest.startsWith(\"[\") && rest.endsWith(\"]\")) {\n // Inline array `globs: [\"**/*.ts\", \"**/*.tsx\"]`\n const inner = rest.slice(1, -1).trim();\n out[key] =\n inner === \"\"\n ? []\n : inner.split(\",\").map((s) => parseScalar(s.trim().replace(/^[\"']|[\"']$/g, \"\")));\n } else {\n out[key] = parseScalar(rest);\n }\n }\n return out;\n}\n\nfunction parseScalar(s: string): string | boolean | number {\n if (s === \"true\") return true;\n if (s === \"false\") return false;\n if (/^-?\\d+$/.test(s)) return parseInt(s, 10);\n // Strip surrounding quotes if present.\n return s.replace(/^[\"']|[\"']$/g, \"\");\n}\n","/**\n * Parser for `.theokit/rules/*.md` — theokit-native path-scoped rules,\n * mirroring Claude Code's `.claude/rules/`.\n *\n * Frontmatter fields:\n * - `paths` — glob-pattern array (Claude Code parity: `.claude/rules` uses `paths:`).\n * - `globs` — glob-pattern array (Cursor-compatible alias; unioned with `paths`).\n * - `alwaysApply` — activate unconditionally (no scope needed).\n * - `enabled` — set `false` to disable the rule entirely (wins over everything).\n * - `description` — human note; not used for activation in v1.\n *\n * Activation (`shouldActivateRule`):\n * - `enabled: false` → never activates.\n * - `alwaysApply: true` → always activates.\n * - otherwise → activates iff a `paths`/`globs` pattern matches an in-scope\n * file (the caller's `agent.send(..., { contextPaths })`). With no in-scope\n * files, a scoped rule stays dormant (parity with Cursor `.mdc`).\n *\n * A file with no `---` frontmatter is treated as an unconditional rule\n * (`alwaysApply: true`). Malformed YAML → `undefined` (caller drops + counts).\n *\n * Glob + YAML subset are shared with the MDC parser (DRY, no new dependency).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/** YAML frontmatter schema for `.theokit/rules/*.md` files. @internal */\nexport const RulesFrontmatterSchema = z.object({\n description: z.string().optional(),\n paths: z.array(z.string()).optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n enabled: z.boolean().optional(),\n});\n\nexport type RulesFrontmatter = z.infer<typeof RulesFrontmatterSchema>;\n\nexport interface RulesParseResult {\n readonly frontmatter: RulesFrontmatter;\n readonly body: string;\n}\n\n/**\n * Parse `.theokit/rules/*.md` content into frontmatter + body. No frontmatter\n * fence → unconditional rule. Malformed YAML → `undefined`.\n *\n * @internal\n */\nexport function parseRules(content: string): RulesParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = RulesFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether a rule activates given the in-scope files. `paths` and\n * `globs` are unioned; both are glob patterns matched against the caller's\n * declared scope.\n *\n * @internal\n */\nexport function shouldActivateRule(\n fm: RulesFrontmatter,\n inScopePaths: ReadonlyArray<string>,\n): boolean {\n if (fm.enabled === false) return false;\n if (fm.alwaysApply === true) return true;\n const patterns = [...(fm.paths ?? []), ...(fm.globs ?? [])];\n if (patterns.length === 0) return false;\n return anyGlobMatches(patterns, inScopePaths);\n}\n","/**\n * MDC (Markdown Cursor) parser for `.cursor/rules/*.mdc` (T3.1, ADR D154).\n *\n * Parses YAML frontmatter with `description` / `globs` / `alwaysApply`\n * fields. Honors activation per Cursor's docs:\n * - `alwaysApply: true` → activates unconditionally.\n * - `alwaysApply: false` + matching glob in `touchedFiles` → activates.\n * - `alwaysApply: false` + no glob match → skipped.\n *\n * **EC-I (v1 semantic):** at `agent.send()` time, `touchedFiles` is empty\n * UNLESS the caller passes `contextPaths` (the in-scope file set). When\n * `contextPaths` is provided, per-glob activation fires; otherwise only\n * `alwaysApply: true` rules activate. Description-based \"agent requested\"\n * classification is out of scope.\n *\n * Glob matching + the YAML subset are shared with the `.theokit/rules/*.md`\n * parser via `context-glob.ts` / `context-yaml-lite.ts` (DRY, no new dep).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/** YAML frontmatter schema for MDC files. @internal */\nexport const McdFrontmatterSchema = z.object({\n description: z.string().optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n});\n\nexport type McdFrontmatter = z.infer<typeof McdFrontmatterSchema>;\n\nexport interface McdParseResult {\n readonly frontmatter: McdFrontmatter;\n readonly body: string;\n}\n\n/**\n * Parse `.mdc` content. Returns frontmatter + body. EC-18: when the\n * file has no `---` frontmatter, returns `frontmatter: {alwaysApply:\n * true}` so the body is treated as an unconditional rule.\n *\n * On YAML parse error, returns `undefined` and the caller emits a\n * telemetry counter (EC-21).\n *\n * @internal\n */\nexport function parseMdc(content: string): McdParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n // EC-18: no frontmatter — treat as alwaysApply\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = McdFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether an MDC rule activates given the currently-touched\n * files. EC-I: empty `touchedFiles` → only `alwaysApply: true`\n * activates.\n *\n * @internal\n */\nexport function shouldActivate(fm: McdFrontmatter, touchedFiles: ReadonlyArray<string>): boolean {\n if (fm.alwaysApply === true) return true;\n if (fm.globs === undefined || fm.globs.length === 0) return false;\n return anyGlobMatches(fm.globs, touchedFiles);\n}\n","/**\n * Multi-format context discovery runner (T5.1, ADRs D150-D156).\n *\n * Walks `DEFAULT_DISCOVERY_SPECS` (or caller override), loads each\n * spec via the appropriate parser, applies `@import` resolution where\n * declared, and returns a flat list of `AggregatorSource[]` ready for\n * the aggregate cap.\n *\n * **EC-E privacy fix:** source disambiguation uses\n * `relative(gitRoot ?? cwd, ...)` — NEVER absolute paths in\n * `<source name=\"\">`.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, relative } from \"node:path\";\n\nimport type { AggregatorSource } from \"./context-aggregator.js\";\nimport {\n DEFAULT_DISCOVERY_SPECS,\n type DiscoverySpec,\n findGitRoot,\n walkUpForFile,\n walkUpForGlob,\n} from \"./context-discovery.js\";\nimport { resolveImports } from \"./context-import-resolver.js\";\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\nimport { parseMdc, shouldActivate } from \"./context-mdc-parser.js\";\nimport { parseRules, shouldActivateRule } from \"./context-rules-frontmatter.js\";\n\nexport interface DiscoveryRunnerOptions {\n /** Workspace root passed to all discovery scopes. */\n readonly cwd: string;\n /** Per-file truncation cap (D155). */\n readonly maxBytesPerFile: number;\n /** Optional override of the default registry. */\n readonly specs?: ReadonlyArray<DiscoverySpec>;\n /** Cursor MDC: file paths the LLM has touched this turn (EC-I: empty at send-time). */\n readonly touchedFiles?: ReadonlyArray<string>;\n /** When true, skip `theokit-context` spec — caller already handles the legacy path. */\n readonly skipLegacyTheokitContext?: boolean;\n /**\n * The root an `@import` may not escape. Defaults to `gitRoot ?? cwd` — the same value\n * this runner already uses to keep absolute paths out of `<source name=\"\">`.\n *\n * Present so an embedder with a trust boundary narrower than the repository can declare\n * it. Absent, the repository IS the boundary, which is the honest default for a document\n * discovered by walking the repository.\n */\n readonly importRoot?: string;\n}\n\n/**\n * Run discovery + loading across all specs. Returns sources ready for\n * the aggregator (priority + content fields populated).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: per-spec dispatch ladder + cross-spec dedup is a flat orchestrator; splitting would obscure the priority-merge invariant.\nexport async function runDiscovery(opts: DiscoveryRunnerOptions): Promise<AggregatorSource[]> {\n const gitRoot = findGitRoot(opts.cwd);\n const specs = opts.specs ?? DEFAULT_DISCOVERY_SPECS;\n const out: AggregatorSource[] = [];\n const seenReal = new Set<string>();\n\n for (const spec of specs) {\n if (opts.skipLegacyTheokitContext && spec.id === \"theokit-context\") continue;\n const paths = await resolvePathsForSpec(spec, opts.cwd, gitRoot);\n for (const path of paths) {\n if (seenReal.has(path)) continue;\n seenReal.add(path);\n const source = await loadOneSource(spec, path, opts, gitRoot);\n if (source !== undefined) out.push(source);\n }\n }\n return out;\n}\n\nasync function resolvePathsForSpec(\n spec: DiscoverySpec,\n cwd: string,\n gitRoot: string | undefined,\n): Promise<string[]> {\n if (spec.scope === \"cwd-only\") {\n return walkUpForFile(cwd, spec.pattern, cwd);\n }\n if (spec.scope === \"git-root-walk\") {\n return walkUpForFile(cwd, spec.pattern, gitRoot ?? cwd);\n }\n // globbed\n return walkUpForGlob(cwd, spec.pattern);\n}\n\nasync function loadOneSource(\n spec: DiscoverySpec,\n path: string,\n opts: DiscoveryRunnerOptions,\n gitRoot: string | undefined,\n): Promise<AggregatorSource | undefined> {\n // EC-E privacy: name uses relative-to-git-root for disambiguation;\n // NEVER absolute paths in the public `<source name=\"\">` attribute.\n // For cwd-only specs (THEO.md), no disambiguation is needed because\n // the scope can only ever match a single file.\n const relPath = relative(gitRoot ?? opts.cwd, dirname(path));\n const needsSuffix = spec.scope !== \"cwd-only\" && relPath !== \"\" && relPath !== \".\";\n const id = needsSuffix ? `${spec.id}@${relPath}` : spec.id;\n\n if (spec.parser === \"mdc\") {\n return loadMdcSource(spec, path, id, opts);\n }\n if (spec.parser === \"rules-frontmatter\") {\n return loadRulesSource(spec, path, id, opts);\n }\n if (spec.parser === \"frontmatter-zod\") {\n // Legacy `.theokit/context/*.md` — handled by `loadContextConfig` in\n // `context-manager.ts` for backward compat. We skip here unless caller\n // explicitly wants us to load it (currently always skipped).\n return undefined;\n }\n // plain-markdown\n return loadPlainMarkdownSource(spec, path, id, opts, gitRoot);\n}\n\n/**\n * Shared read → parse → activation-gate → source pipeline for the frontmatter\n * discovery parsers (mdc, rules). Binds the parser + the activation predicate so\n * the mdc and rules loaders differ only in those two, not in the surrounding\n * read/guard/shape boilerplate (DRY).\n */\nasync function loadParsedSource<F>(\n spec: DiscoverySpec,\n path: string,\n id: string,\n parse: (raw: string) => { frontmatter: F; body: string } | undefined,\n isActive: (frontmatter: F) => boolean,\n): Promise<AggregatorSource | undefined> {\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n return undefined;\n }\n const parsed = parse(raw);\n if (parsed === undefined || !isActive(parsed.frontmatter)) return undefined;\n return { id, source: path, content: parsed.body, priority: spec.priority, truncated: false };\n}\n\nfunction loadMdcSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseMdc, (fm) =>\n shouldActivate(fm, opts.touchedFiles ?? []),\n );\n}\n\nfunction loadRulesSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseRules, (fm) =>\n shouldActivateRule(fm, opts.touchedFiles ?? []),\n );\n}\n\nasync function loadPlainMarkdownSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n gitRoot: string | undefined,\n): Promise<AggregatorSource | undefined> {\n const loaded = await loadPlainMarkdown(path, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) return undefined;\n let content = loaded.content;\n if (spec.followImports) {\n content = await resolveImports(content, path, {\n visited: new Set([path]),\n depth: 0,\n maxBytesPerFile: opts.maxBytesPerFile,\n // The document carrying the import is repository-controlled, so the repository is the\n // boundary it may not cross. Without this, `CLAUDE.md` / `GEMINI.md` — the two specs\n // with `followImports: true` — could name any absolute or `~/` path and have it\n // inlined into the system prompt.\n projectRoot: opts.importRoot ?? gitRoot ?? opts.cwd,\n });\n }\n return {\n id,\n source: path,\n content,\n priority: spec.priority,\n truncated: loaded.truncated,\n };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunk4OQXDCMN_cjs = require('./chunk-4OQXDCMN.cjs');
|
|
4
4
|
var chunkKCQUYQ3V_cjs = require('./chunk-KCQUYQ3V.cjs');
|
|
5
5
|
var chunkNINIJCHU_cjs = require('./chunk-NINIJCHU.cjs');
|
|
6
6
|
var chunkYULF6FPB_cjs = require('./chunk-YULF6FPB.cjs');
|
|
@@ -375,11 +375,11 @@ async function createCronJob(options) {
|
|
|
375
375
|
validateCronExpression(options.cron);
|
|
376
376
|
const timezone = options.timezone ?? "UTC";
|
|
377
377
|
validateTimezone(timezone);
|
|
378
|
-
|
|
378
|
+
chunk4OQXDCMN_cjs.resolveApiKey(options.apiKey);
|
|
379
379
|
const runtime = detectRuntime(options);
|
|
380
380
|
const now = Date.now();
|
|
381
381
|
const job = {
|
|
382
|
-
id:
|
|
382
|
+
id: chunk4OQXDCMN_cjs.generateCronId(),
|
|
383
383
|
cron: options.cron,
|
|
384
384
|
timezone,
|
|
385
385
|
enabled: options.enabled ?? true,
|
|
@@ -456,5 +456,5 @@ async function updateJobStatus(jobId, enabled) {
|
|
|
456
456
|
}
|
|
457
457
|
|
|
458
458
|
exports.Cron = Cron;
|
|
459
|
-
//# sourceMappingURL=chunk-
|
|
460
|
-
//# sourceMappingURL=chunk-
|
|
459
|
+
//# sourceMappingURL=chunk-HLGEXZZP.cjs.map
|
|
460
|
+
//# sourceMappingURL=chunk-HLGEXZZP.cjs.map
|