@theokit/sdk 5.3.3 → 5.4.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.
- package/CHANGELOG.md +60 -0
- package/dist/{agent-KJLAWKZB.cjs → agent-AUVD4TI4.cjs} +9 -9
- package/dist/{agent-KJLAWKZB.cjs.map → agent-AUVD4TI4.cjs.map} +1 -1
- package/dist/{agent-CTbU0O1R.d.ts → agent-Bmy2G_ml.d.ts} +73 -2
- package/dist/{agent-QLwxhXY3.d.cts → agent-C1Efo7PI.d.cts} +73 -2
- package/dist/{agent-PNYJ5S2Y.js → agent-MNINE73R.js} +8 -8
- package/dist/{agent-PNYJ5S2Y.js.map → agent-MNINE73R.js.map} +1 -1
- package/dist/{chunk-AWINL3ZC.js → chunk-2QKV4CGK.js} +3 -3
- package/dist/{chunk-AWINL3ZC.js.map → chunk-2QKV4CGK.js.map} +1 -1
- package/dist/{chunk-65UMH5V3.cjs → chunk-3FDU5JFE.cjs} +5 -5
- package/dist/{chunk-65UMH5V3.cjs.map → chunk-3FDU5JFE.cjs.map} +1 -1
- package/dist/{chunk-DWB3CN46.cjs → chunk-43YXGD3P.cjs} +14 -4
- package/dist/chunk-43YXGD3P.cjs.map +1 -0
- package/dist/{chunk-IQBDR5YZ.cjs → chunk-AYA65JA5.cjs} +5 -5
- package/dist/{chunk-IQBDR5YZ.cjs.map → chunk-AYA65JA5.cjs.map} +1 -1
- package/dist/{chunk-2HPNT6HH.cjs → chunk-C4ZQPWXJ.cjs} +9 -9
- package/dist/chunk-C4ZQPWXJ.cjs.map +1 -0
- package/dist/{chunk-Y2KYR2ED.cjs → chunk-DZG77WU7.cjs} +3 -3
- package/dist/{chunk-Y2KYR2ED.cjs.map → chunk-DZG77WU7.cjs.map} +1 -1
- package/dist/{chunk-363RBGIR.js → chunk-IKBLU7ZS.js} +58 -27
- package/dist/chunk-IKBLU7ZS.js.map +1 -0
- package/dist/{chunk-L4XENLQO.cjs → chunk-J6KZE2ZQ.cjs} +4 -4
- package/dist/{chunk-L4XENLQO.cjs.map → chunk-J6KZE2ZQ.cjs.map} +1 -1
- package/dist/{chunk-ZITYGJOD.js → chunk-KWGSBZ2Q.js} +3 -3
- package/dist/{chunk-ZITYGJOD.js.map → chunk-KWGSBZ2Q.js.map} +1 -1
- package/dist/{chunk-K3NH62DG.js → chunk-KZSKIUXZ.js} +7 -7
- package/dist/chunk-KZSKIUXZ.js.map +1 -0
- package/dist/{chunk-RP3VXJMA.js → chunk-NSLHPAC7.js} +14 -4
- package/dist/chunk-NSLHPAC7.js.map +1 -0
- package/dist/{chunk-DLFWMJE3.js → chunk-O7L7M42F.js} +3 -3
- package/dist/{chunk-DLFWMJE3.js.map → chunk-O7L7M42F.js.map} +1 -1
- package/dist/{chunk-Y46VI73J.cjs → chunk-UALC6Q3J.cjs} +127 -96
- package/dist/chunk-UALC6Q3J.cjs.map +1 -0
- package/dist/{chunk-7L3MIW2F.js → chunk-XD3FS5OI.js} +3 -3
- package/dist/{chunk-7L3MIW2F.js.map → chunk-XD3FS5OI.js.map} +1 -1
- package/dist/{compact-session-BHTPCIHA.cjs → compact-session-7FMYJXQ7.cjs} +11 -11
- package/dist/{compact-session-BHTPCIHA.cjs.map → compact-session-7FMYJXQ7.cjs.map} +1 -1
- package/dist/{compact-session-W4WLJTHA.js → compact-session-YSEK7NQF.js} +3 -3
- package/dist/{compact-session-W4WLJTHA.js.map → compact-session-YSEK7NQF.js.map} +1 -1
- package/dist/{context-FCCJQ3FN.cjs → context-4AIK26QB.cjs} +7 -7
- package/dist/{context-FCCJQ3FN.cjs.map → context-4AIK26QB.cjs.map} +1 -1
- package/dist/context-EGM6CHXD.js +6 -0
- package/dist/{context-BUIE52VH.js.map → context-EGM6CHXD.js.map} +1 -1
- package/dist/{cron-Dz8AOpy3.d.cts → cron-DSMdlhyF.d.cts} +1 -1
- package/dist/{cron-Cl8FrK3D.d.ts → cron-Dcdrdv_T.d.ts} +1 -1
- package/dist/cron.cjs +8 -8
- package/dist/cron.d.cts +2 -2
- package/dist/cron.d.ts +2 -2
- package/dist/cron.js +7 -7
- package/dist/eval.cjs +7 -7
- package/dist/eval.js +6 -6
- package/dist/index.cjs +30 -30
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +9 -9
- package/dist/{inject-session-SUM6TDJF.js → inject-session-J4LBWAPH.js} +3 -3
- package/dist/{inject-session-SUM6TDJF.js.map → inject-session-J4LBWAPH.js.map} +1 -1
- package/dist/{inject-session-W6A46J3E.cjs → inject-session-PC73TMP2.cjs} +4 -4
- package/dist/{inject-session-W6A46J3E.cjs.map → inject-session-PC73TMP2.cjs.map} +1 -1
- package/dist/internal/llm/tool-result-content.d.ts +1 -1
- package/dist/internal/persistence/index.cjs +4 -4
- package/dist/internal/persistence/index.js +1 -1
- package/dist/internal/runtime/hooks/hooks-executor.d.ts +25 -1
- package/dist/subagents-loader-AIVDQ2D5.js +7 -0
- package/dist/{subagents-loader-PAZVOZHI.js.map → subagents-loader-AIVDQ2D5.js.map} +1 -1
- package/dist/subagents-loader-DN4LETGL.cjs +16 -0
- package/dist/{subagents-loader-7G76XOZU.cjs.map → subagents-loader-DN4LETGL.cjs.map} +1 -1
- package/dist/subagents-loader.cjs +3 -3
- package/dist/subagents-loader.d.cts +1 -1
- package/dist/subagents-loader.d.ts +1 -1
- package/dist/subagents-loader.js +2 -2
- package/dist/types/agent.d.ts +25 -2
- package/dist/types/hooks.d.ts +48 -0
- package/package.json +1 -1
- package/dist/chunk-2HPNT6HH.cjs.map +0 -1
- package/dist/chunk-363RBGIR.js.map +0 -1
- package/dist/chunk-DWB3CN46.cjs.map +0 -1
- package/dist/chunk-K3NH62DG.js.map +0 -1
- package/dist/chunk-RP3VXJMA.js.map +0 -1
- package/dist/chunk-Y46VI73J.cjs.map +0 -1
- package/dist/context-BUIE52VH.js +0 -6
- package/dist/subagents-loader-7G76XOZU.cjs +0 -16
- package/dist/subagents-loader-PAZVOZHI.js +0 -7
|
@@ -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-7FMYJXQ7.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-DZG77WU7.cjs.map
|
|
118
|
+
//# sourceMappingURL=chunk-DZG77WU7.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":["sessions","transcriptKey","hydratedKeys","persistTurn","diag","readSessionMessages"],"mappings":";;;;;;;AAyCA,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;AAC9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,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-Y2KYR2ED.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 \"./types.js\";\n\nimport type { SessionMessage } from \"./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 { globalSingleton } from \"../global-singleton.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\n/**\n * Drop the in-memory message cache for `agentId` and NOTHING else — the hydration marker in\n * `hydratedKeys` deliberately stays.\n *\n * That asymmetry is the feature, not an oversight, and it is what separates this from\n * `invalidateSessionCache`, which drops both. The single caller is the personality switch's\n * `reset: true` path (`internal/personality/switch.ts`): leaving the marker set makes\n * `hydrateSession` return early, so the next send starts from an EMPTY context instead of\n * replaying the pre-reset transcript off disk. Clearing the marker here would re-hydrate the\n * conversation the reset was asked to discard.\n *\n * The same shape read as a bug one function up: `forgetBookkeeping` documents an evicted session\n * coming back empty as \"silent amnesia\". The difference is intent — eviction wants the transcript\n * back, a reset does not. Anyone reaching for this to invalidate a cache wants\n * `invalidateSessionCache(cwd, agentId)` instead.\n */\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\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 // Through the helper, with the SAME key compact-session.ts uses: two files hand-rolling one slot is\n // how two copies of a mechanism drift apart.\n globalSingleton(\n \"theokit-sdk.session.auto-compact-attempts\",\n () => new Map<string, number>(),\n ).clear();\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":["sessions","transcriptKey","hydratedKeys","persistTurn","diag","readSessionMessages"],"mappings":";;;;;;;AAyCA,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,CAAS,OAAO,MAAM,CAAA;AACtB,IAAA,iBAAA,CAAkB,MAAM,CAAA;AAAA,EAC1B;AACF;AAeA,SAAS,kBAAkB,OAAA,EAAuB;AAChD,EAAA,MAAM,MAAA,GAASC,gCAAc,EAAA,EAAI,OAAO,EAAE,KAAA,CAAM,CAAA,GAAI,OAAA,CAAQ,MAAA,GAAS,CAAC,CAAA;AACtE,EAAA,KAAA,MAAW,CAAA,IAAK,CAAC,GAAGC,8BAA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a,GAAA,CAAI,GAAG,CAAA,EAAG;AAC3B,EAAAA,8BAAA,CAAa,IAAI,GAAG,CAAA;AAEpB,EAAA,MAAM,SAAA,GAAY,MAAMG,qCAAA,CAAoB,GAAA,CAAI,OAAO,OAAO,CAAA;AAC9D,EAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAM5B,EAAAL,0BAAA,CAAS,GAAA,CAAI,SAAS,SAAS,CAAA;AACjC;AAQA,eAAsB,kBAAA,GAAoC;AACxD,EAAA,OAAO,aAAA,CAAc,OAAO,CAAA,EAAG;AAC7B,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,IAAA,CAAK,aAAA,CAAc,QAAQ,CAAA;AAC7C,IAAA,aAAA,CAAc,KAAA,EAAM;AACpB,IAAA,MAAM,OAAA,CAAQ,IAAI,GAAG,CAAA;AAAA,EACvB;AACF;AAkBO,SAAS,aAAa,OAAA,EAAuB;AAClD,EAAAA,0BAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAOO,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-DZG77WU7.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 \"./types.js\";\n\nimport type { SessionMessage } from \"./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 { globalSingleton } from \"../global-singleton.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\n/**\n * Drop the in-memory message cache for `agentId` and NOTHING else — the hydration marker in\n * `hydratedKeys` deliberately stays.\n *\n * That asymmetry is the feature, not an oversight, and it is what separates this from\n * `invalidateSessionCache`, which drops both. The single caller is the personality switch's\n * `reset: true` path (`internal/personality/switch.ts`): leaving the marker set makes\n * `hydrateSession` return early, so the next send starts from an EMPTY context instead of\n * replaying the pre-reset transcript off disk. Clearing the marker here would re-hydrate the\n * conversation the reset was asked to discard.\n *\n * The same shape read as a bug one function up: `forgetBookkeeping` documents an evicted session\n * coming back empty as \"silent amnesia\". The difference is intent — eviction wants the transcript\n * back, a reset does not. Anyone reaching for this to invalidate a cache wants\n * `invalidateSessionCache(cwd, agentId)` instead.\n */\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\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 // Through the helper, with the SAME key compact-session.ts uses: two files hand-rolling one slot is\n // how two copies of a mechanism drift apart.\n globalSingleton(\n \"theokit-sdk.session.auto-compact-attempts\",\n () => new Map<string, number>(),\n ).clear();\n}\n"]}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { submit, emitRunEvent } from './chunk-K2VMFZQ5.js';
|
|
2
|
-
import { enqueueSessionWrite, hydrateSession, persistTurnToTranscript, flushSessionWrites, appendSessionMessage, getSessionMessages, discardSession, clearSession } from './chunk-
|
|
2
|
+
import { enqueueSessionWrite, hydrateSession, persistTurnToTranscript, flushSessionWrites, appendSessionMessage, getSessionMessages, discardSession, clearSession } from './chunk-2QKV4CGK.js';
|
|
3
3
|
import { IndexManager } from './chunk-7SZAV6QG.js';
|
|
4
|
-
import { loadHookConfig, warnOnce, currentPersonalityContext, warnPersonalitySwitchInsideFork } from './chunk-
|
|
4
|
+
import { loadHookConfig, warnOnce, currentPersonalityContext, warnPersonalitySwitchInsideFork } from './chunk-XD3FS5OI.js';
|
|
5
5
|
import { extractCodePlugins } from './chunk-2SFBB54R.js';
|
|
6
6
|
import { createOpenAiCompatibleRuntime } from './chunk-55GB6JYQ.js';
|
|
7
7
|
import { persistActiveMemoryTranscript } from './chunk-OR6XIWLB.js';
|
|
8
8
|
import { writeSessionSummary, resolveMemoryRoot, MEMORY_KINDS, appendFact, readFacts, legacyMemoryJsonPath, memoryMdPath, appendFactToMarkdown } from './chunk-SADXXGWU.js';
|
|
9
9
|
import { FsSessionStore } from './chunk-AAEZSPTC.js';
|
|
10
|
-
import { discoverProviderPlugins, validateApiKeyShape, getConfiguredBaseUrl, httpRequest, isFixtureApiKey, presentProviderCredentialEnvVars, buildDefaultSummarizer, shouldUseRealLocalRuntime, parseSseStream, CircuitBreaker, resolveRunProvider, mergeExplicitApiKey, resolveProviderChain, abortError, tryFirstEvent, relayStream, renderToolResultContentText } from './chunk-
|
|
10
|
+
import { discoverProviderPlugins, validateApiKeyShape, getConfiguredBaseUrl, httpRequest, isFixtureApiKey, presentProviderCredentialEnvVars, buildDefaultSummarizer, shouldUseRealLocalRuntime, parseSseStream, CircuitBreaker, resolveRunProvider, mergeExplicitApiKey, resolveProviderChain, abortError, tryFirstEvent, relayStream, renderToolResultContentText } from './chunk-KZSKIUXZ.js';
|
|
11
11
|
import { resolveChildEnv } from './chunk-HKCKOAIO.js';
|
|
12
12
|
import { DEFAULT_MAX_BYTES_PER_FILE, runDiscovery, truncateWithMarker } from './chunk-N6OOOYFZ.js';
|
|
13
13
|
import { readVersionedJson, writeVersionedJson } from './chunk-SVQIW5RJ.js';
|
|
@@ -24,8 +24,8 @@ import { expandTilde, defaultBaseDir } from './chunk-JOFVLOFY.js';
|
|
|
24
24
|
import { withFileLock } from './chunk-TA3K7SBK.js';
|
|
25
25
|
import { withCwdMutex } from './chunk-Q5EWJPRY.js';
|
|
26
26
|
import { sweepStaleAtomicTemps, atomicWriteJson } from './chunk-3JHIFQ4I.js';
|
|
27
|
-
import { loadSubagents, pluginBundleDirs } from './chunk-
|
|
28
|
-
import { reportUndeclaredSources, theokitConfigRoot, undefinedVariablesIn, getTheokitHome, adapterForConfigPath, projectConfigRoots, pluginBundleRoots } from './chunk-
|
|
27
|
+
import { loadSubagents, pluginBundleDirs } from './chunk-O7L7M42F.js';
|
|
28
|
+
import { reportUndeclaredSources, theokitConfigRoot, undefinedVariablesIn, getTheokitHome, adapterForConfigPath, projectConfigRoots, pluginBundleRoots } from './chunk-NSLHPAC7.js';
|
|
29
29
|
import { readWorkspaceDir, parseSimpleYaml } from './chunk-JNAA4G4H.js';
|
|
30
30
|
import { resolveEffectiveContextWindow, CONTEXT_WINDOW_FLOOR, CONTEXT_WINDOW_MARGIN } from './chunk-6M2OIS4Y.js';
|
|
31
31
|
import { parseModelId } from './chunk-R7WIIPUR.js';
|
|
@@ -2600,12 +2600,14 @@ function spawnAndCollect(options) {
|
|
|
2600
2600
|
|
|
2601
2601
|
// src/internal/runtime/hooks/hooks-executor.ts
|
|
2602
2602
|
var HooksExecutor = class {
|
|
2603
|
-
constructor(cwd, compatSources = []) {
|
|
2603
|
+
constructor(cwd, compatSources = [], gate = void 0) {
|
|
2604
2604
|
this.cwd = cwd;
|
|
2605
2605
|
this.compatSources = compatSources;
|
|
2606
|
+
this.gate = gate;
|
|
2606
2607
|
}
|
|
2607
2608
|
cwd;
|
|
2608
2609
|
compatSources;
|
|
2610
|
+
gate;
|
|
2609
2611
|
config = {};
|
|
2610
2612
|
async initialize(settingSourcesIncludeProject) {
|
|
2611
2613
|
if (!settingSourcesIncludeProject) {
|
|
@@ -2645,7 +2647,27 @@ var HooksExecutor = class {
|
|
|
2645
2647
|
}
|
|
2646
2648
|
});
|
|
2647
2649
|
}
|
|
2650
|
+
/**
|
|
2651
|
+
* #631 — the consumer's gate, consulted at the ONLY point a hook is spawned.
|
|
2652
|
+
*
|
|
2653
|
+
* Here and not at the caller on purpose: a check anywhere else could be reached around by a
|
|
2654
|
+
* second execution path later, and this one cannot — `spawnAndCollect` is called for a hook from
|
|
2655
|
+
* exactly one place.
|
|
2656
|
+
*
|
|
2657
|
+
* No gate means no refusal, which is what every consumer gets today.
|
|
2658
|
+
*/
|
|
2659
|
+
async refusedByConsumer(command, payload) {
|
|
2660
|
+
if (this.gate?.approve === void 0) return false;
|
|
2661
|
+
const request = {
|
|
2662
|
+
command: command.command,
|
|
2663
|
+
event: payload.event,
|
|
2664
|
+
...command.sourcePath === void 0 ? {} : { sourcePath: command.sourcePath },
|
|
2665
|
+
...command.matcher === void 0 ? {} : { matcher: command.matcher }
|
|
2666
|
+
};
|
|
2667
|
+
return !await this.gate.approve(request);
|
|
2668
|
+
}
|
|
2648
2669
|
async executeOne(command, payload) {
|
|
2670
|
+
if (await this.refusedByConsumer(command, payload)) return { decision: "allow" };
|
|
2649
2671
|
const timeoutMs = command.timeoutMs ?? 3e4;
|
|
2650
2672
|
const env = runtimeEnvFor(command.sourcePath, this.cwd);
|
|
2651
2673
|
const result = await spawnAndCollect({
|
|
@@ -2656,23 +2678,31 @@ var HooksExecutor = class {
|
|
|
2656
2678
|
timeoutMs,
|
|
2657
2679
|
stdin: JSON.stringify(payload)
|
|
2658
2680
|
});
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2681
|
+
const failure = this.decisionFromFailure(result, command, env, timeoutMs);
|
|
2682
|
+
return failure ?? parseDecisionFromStdout(result.stdout);
|
|
2683
|
+
}
|
|
2684
|
+
/**
|
|
2685
|
+
* A run that did not succeed, turned into a decision. `undefined` when it did.
|
|
2686
|
+
*
|
|
2687
|
+
* Extracted from `executeOne` when the approval gate pushed that function past the complexity
|
|
2688
|
+
* gate. The seam is not arbitrary — every branch here answers one question, "the command did not
|
|
2689
|
+
* run cleanly, so what does this hook decide?", and none of them knows how the command was
|
|
2690
|
+
* spawned.
|
|
2691
|
+
*/
|
|
2692
|
+
decisionFromFailure(result, command, env, timeoutMs) {
|
|
2693
|
+
if (result.timedOut) return { decision: "deny", reason: `Hook timed out after ${timeoutMs}ms` };
|
|
2662
2694
|
if (result.spawnError !== void 0) {
|
|
2663
2695
|
return { decision: "deny", reason: `Hook spawn failed: ${result.spawnError.message}` };
|
|
2664
2696
|
}
|
|
2665
|
-
if (result.exitCode
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
}
|
|
2675
|
-
return parseDecisionFromStdout(result.stdout);
|
|
2697
|
+
if (result.exitCode === 0) return void 0;
|
|
2698
|
+
const stderr = result.stderr.trim();
|
|
2699
|
+
const base = stderr.length > 0 ? stderr : `Hook exited with code ${result.exitCode}`;
|
|
2700
|
+
const missing = undefinedVariablesIn(command.command, env);
|
|
2701
|
+
if (missing.length === 0) return { decision: "deny", reason: base };
|
|
2702
|
+
return {
|
|
2703
|
+
decision: "deny",
|
|
2704
|
+
reason: `${base} \u2014 this hook came from ${command.sourcePath ?? "an unrecorded source"} and uses ${missing.map((n) => `$${n}`).join(", ")}, which nothing defines here. A variable this runtime does not supply expands to the empty string, so the error above names a path rather than the cause.`
|
|
2705
|
+
};
|
|
2676
2706
|
}
|
|
2677
2707
|
};
|
|
2678
2708
|
function runtimeEnvFor(sourcePath, cwd) {
|
|
@@ -9122,7 +9152,7 @@ async function* localAgentStreamToCompletion(agent, message, options) {
|
|
|
9122
9152
|
async function localAgentFork(parent, options) {
|
|
9123
9153
|
const { forkAgentImpl } = await import('./fork-agent-S2EPIML7.js');
|
|
9124
9154
|
const { getAgentFacade } = await import('./agent-factory-registry-ZVTABLEY.js');
|
|
9125
|
-
const { withPersonalityContext } = await import('./context-
|
|
9155
|
+
const { withPersonalityContext } = await import('./context-EGM6CHXD.js');
|
|
9126
9156
|
const create = getAgentFacade().create;
|
|
9127
9157
|
return withPersonalityContext(
|
|
9128
9158
|
{ slug: parent.personalitySlugSnapshot, isFork: true },
|
|
@@ -9764,6 +9794,7 @@ var KNOWN_LOCAL_OPTION_KEYS = /* @__PURE__ */ new Set([
|
|
|
9764
9794
|
"cwd",
|
|
9765
9795
|
"settingSources",
|
|
9766
9796
|
"compatSources",
|
|
9797
|
+
"hooks",
|
|
9767
9798
|
"sandboxOptions",
|
|
9768
9799
|
"sessionDir",
|
|
9769
9800
|
"baseDir",
|
|
@@ -9915,7 +9946,7 @@ var LocalAgent = class {
|
|
|
9915
9946
|
reportUnknownLocalOptions(options.local);
|
|
9916
9947
|
const compatSources = resolveCompatSources(options, this.workspaceCwd);
|
|
9917
9948
|
reportUndeclaredSources(this.workspaceCwd, compatSources);
|
|
9918
|
-
this.hooksExecutor = new HooksExecutor(this.workspaceCwd, compatSources);
|
|
9949
|
+
this.hooksExecutor = new HooksExecutor(this.workspaceCwd, compatSources, options.local?.hooks);
|
|
9919
9950
|
this.defaultMemoryProviderForLoop = createLocalAgentMemoryProvider({
|
|
9920
9951
|
agentOptions: options,
|
|
9921
9952
|
workspaceCwd: this.workspaceCwd,
|
|
@@ -10820,7 +10851,7 @@ var Agent = class _Agent {
|
|
|
10820
10851
|
*/
|
|
10821
10852
|
static async compact(agentId, options = {}) {
|
|
10822
10853
|
const reg = await requireLocalAgent(agentId, "compact");
|
|
10823
|
-
const { compactSessionTranscript, buildDefaultSummarizer: buildDefaultSummarizer2 } = await import('./compact-session-
|
|
10854
|
+
const { compactSessionTranscript, buildDefaultSummarizer: buildDefaultSummarizer2 } = await import('./compact-session-YSEK7NQF.js');
|
|
10824
10855
|
const { cwd, model, store } = await openLocalStore(reg);
|
|
10825
10856
|
return enqueueSessionWrite(
|
|
10826
10857
|
cwd,
|
|
@@ -10847,7 +10878,7 @@ var Agent = class _Agent {
|
|
|
10847
10878
|
*/
|
|
10848
10879
|
static async injectSessionTurn(agentId, turn) {
|
|
10849
10880
|
const reg = await requireLocalAgent(agentId, "injectSessionTurn");
|
|
10850
|
-
const { injectSessionTurn } = await import('./inject-session-
|
|
10881
|
+
const { injectSessionTurn } = await import('./inject-session-J4LBWAPH.js');
|
|
10851
10882
|
const { cwd, model, store } = await openLocalStore(reg);
|
|
10852
10883
|
await injectSessionTurn({
|
|
10853
10884
|
store,
|
|
@@ -10898,7 +10929,7 @@ var Agent = class _Agent {
|
|
|
10898
10929
|
*/
|
|
10899
10930
|
static async describe(agentId) {
|
|
10900
10931
|
const agent = await getRegisteredAgentOrThrow(agentId);
|
|
10901
|
-
const { loadSubagents: loadSubagents2 } = await import('./subagents-loader-
|
|
10932
|
+
const { loadSubagents: loadSubagents2 } = await import('./subagents-loader-AIVDQ2D5.js');
|
|
10902
10933
|
const settingSources = agent.options.local?.settingSources;
|
|
10903
10934
|
const subagents = await loadSubagents2(
|
|
10904
10935
|
agent.cwd ?? process.cwd(),
|
|
@@ -11005,5 +11036,5 @@ async function openLocalStore(reg) {
|
|
|
11005
11036
|
}
|
|
11006
11037
|
|
|
11007
11038
|
export { Agent, AgentBuilder, DEFAULT_AGENTIC_MODEL_ID, MEMORY_EMBEDDING_ADAPTERS, Tool, ToolError, UsageAccumulator, computeCost, generateCronId, getPricingEntry, openRouterMemoryEmbeddingProviderAdapter, resolveSessionDir };
|
|
11008
|
-
//# sourceMappingURL=chunk-
|
|
11009
|
-
//# sourceMappingURL=chunk-
|
|
11039
|
+
//# sourceMappingURL=chunk-IKBLU7ZS.js.map
|
|
11040
|
+
//# sourceMappingURL=chunk-IKBLU7ZS.js.map
|