@theokit/sdk 4.52.0 → 4.52.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +35 -17
  2. package/dist/{agent-HYQGJTIN.js → agent-RDHK6MVT.js} +6 -6
  3. package/dist/{agent-HYQGJTIN.js.map → agent-RDHK6MVT.js.map} +1 -1
  4. package/dist/{agent-C66BEJGO.cjs → agent-U2R2R5JP.cjs} +7 -7
  5. package/dist/{agent-C66BEJGO.cjs.map → agent-U2R2R5JP.cjs.map} +1 -1
  6. package/dist/auth/index.cjs +2 -2
  7. package/dist/auth/index.d.cts +15 -0
  8. package/dist/auth/index.d.ts +15 -0
  9. package/dist/auth/index.js +1 -1
  10. package/dist/{chunk-SPZZSAHV.js → chunk-42PLABFU.js} +3 -3
  11. package/dist/{chunk-SPZZSAHV.js.map → chunk-42PLABFU.js.map} +1 -1
  12. package/dist/{chunk-LLK2RS6I.cjs → chunk-6GS7JI64.cjs} +43 -43
  13. package/dist/{chunk-LLK2RS6I.cjs.map → chunk-6GS7JI64.cjs.map} +1 -1
  14. package/dist/{chunk-YARJG3GV.cjs → chunk-CY7MIMI4.cjs} +3 -3
  15. package/dist/{chunk-YARJG3GV.cjs.map → chunk-CY7MIMI4.cjs.map} +1 -1
  16. package/dist/{chunk-WVDH34LK.cjs → chunk-FRITRLZQ.cjs} +2 -2
  17. package/dist/chunk-FRITRLZQ.cjs.map +1 -0
  18. package/dist/{chunk-DU7PBCAM.js → chunk-GNPI5IWZ.js} +3 -3
  19. package/dist/{chunk-DU7PBCAM.js.map → chunk-GNPI5IWZ.js.map} +1 -1
  20. package/dist/{chunk-ZFARZBOX.js → chunk-KELIQH7K.js} +6 -6
  21. package/dist/{chunk-ZFARZBOX.js.map → chunk-KELIQH7K.js.map} +1 -1
  22. package/dist/{chunk-YBB66SZZ.js → chunk-M5EK7N6R.js} +3 -3
  23. package/dist/{chunk-YBB66SZZ.js.map → chunk-M5EK7N6R.js.map} +1 -1
  24. package/dist/{chunk-U3PAW4PL.js → chunk-NAF4L3T6.js} +2 -2
  25. package/dist/chunk-NAF4L3T6.js.map +1 -0
  26. package/dist/{chunk-ZNEYQ56O.cjs → chunk-WLESQ3ZQ.cjs} +6 -6
  27. package/dist/{chunk-ZNEYQ56O.cjs.map → chunk-WLESQ3ZQ.cjs.map} +1 -1
  28. package/dist/{chunk-2CD5XUAG.cjs → chunk-ZNEE4WWQ.cjs} +5 -5
  29. package/dist/{chunk-2CD5XUAG.cjs.map → chunk-ZNEE4WWQ.cjs.map} +1 -1
  30. package/dist/{compact-session-AXKDB6FC.cjs → compact-session-FBVWO6B3.cjs} +12 -12
  31. package/dist/{compact-session-AXKDB6FC.cjs.map → compact-session-FBVWO6B3.cjs.map} +1 -1
  32. package/dist/{compact-session-DUAUEFRR.js → compact-session-XLXC2CZN.js} +4 -4
  33. package/dist/{compact-session-DUAUEFRR.js.map → compact-session-XLXC2CZN.js.map} +1 -1
  34. package/dist/cron.cjs +6 -6
  35. package/dist/cron.js +5 -5
  36. package/dist/eval.cjs +5 -5
  37. package/dist/eval.js +4 -4
  38. package/dist/index.cjs +28 -28
  39. package/dist/index.js +7 -7
  40. package/dist/{inject-session-TASLP5FA.cjs → inject-session-UBAQ7I3G.cjs} +4 -4
  41. package/dist/{inject-session-TASLP5FA.cjs.map → inject-session-UBAQ7I3G.cjs.map} +1 -1
  42. package/dist/{inject-session-RBGOGACE.js → inject-session-UEH5MAKU.js} +3 -3
  43. package/dist/{inject-session-RBGOGACE.js.map → inject-session-UEH5MAKU.js.map} +1 -1
  44. package/dist/internal/auth/api-key-prefix.d.ts +7 -1
  45. package/package.json +1 -1
  46. package/dist/chunk-U3PAW4PL.js.map +0 -1
  47. package/dist/chunk-WVDH34LK.cjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,30 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.52.1
4
+
5
+ ### Patch Changes
6
+
7
+ - **`providerFromApiKeyPrefix` now appears in `dist/auth/index.d.ts`.** Fixes #283.
8
+
9
+ It shipped at runtime and was absent from the type declaration, so a TypeScript consumer could not
10
+ import it: `TS2305`. The same defect the export existed to close, one layer down.
11
+
12
+ Root cause, and it is worth naming precisely: `tsconfig.base.json` sets `stripInternal: true`, and
13
+ TypeScript matches that tag **anywhere in an attached JSDoc — prose included**. The docblock above
14
+ the export explained the fix by describing the module as having been marked internal, and naming the
15
+ tag deleted the very line it documented.
16
+
17
+ Guarded by outcome rather than by word: a test asserts that every runtime export of
18
+ `@theokit/sdk/auth` appears in the emitted `.d.ts`. A grep for the tag would forbid the word instead
19
+ of the failure, and would not catch the next way a declaration goes missing.
20
+
3
21
  ## 4.52.0
4
22
 
5
23
  ### Minor Changes
6
24
 
7
- - 40125a5: **`providerFromApiKeyPrefix` fica alcancavel a partir de `@theokit/sdk/auth`.**
25
+ - 40125a5: **`providerFromApiKeyPrefix` becomes reachable from `@theokit/sdk/auth`.**
8
26
 
9
- A pergunta "de qual provider e esta chave?" ja era respondida aquiem
10
- `internal/local-agent/real-local-run-provider.ts`, marcada `@internal` e exportada por
11
- nenhuma entry. Um consumidor medido precisa dela no login (`opts.provider ?? inferProvider(key)`),
12
- nao conseguiu importar, e escreveu a propria copia. Uma capacidade que existe e nao se alcanca
13
- custa exatamente o que uma ausente custa.
27
+ "Which provider issued this key?" was already answered herein
28
+ `internal/local-agent/real-local-run-provider.ts`, marked internal and exported from no entry
29
+ point. A measured consumer needs it at login (`opts.provider ?? inferProvider(key)`), could not
30
+ import it, and wrote its own copy. A capability that exists and cannot be reached costs exactly
31
+ what an absent one costs.
14
32
 
15
- Duas coisas separam isto de um re-export:
33
+ Two things separate this from a re-export:
16
34
 
17
- 1. **O prefixo mais longo vence, por construcao.** A versao interna percorria um array escrito a
18
- mao e so estava correta porque `sk-or-` e `sk-ant-` calharam de vir antes de `sk-`. Ordem como
19
- convencao quebra na primeira vez que alguem acrescenta um prefixo mais longo ou ordena a lista
20
- por legibilidade em silencio, resolvendo uma chave Anthropic como OpenAI. A ordenacao agora e
21
- derivada do comprimento.
22
- 2. **Sem o gate de perfil de provider.** Esse gate pertence ao caminho de local-run, que nao vai
23
- nomear um provider que nao consegue construir. Quem pergunta "de quem e esta chave?" no login
24
- ainda nao tem perfil registrado, e devolver `undefined` ali responderia outra pergunta.
35
+ 1. **The longest prefix wins, by construction.** The internal version walked a hand-ordered array
36
+ and was correct only because `sk-or-` and `sk-ant-` happened to precede `sk-`. Order-as-
37
+ convention breaks the first time somebody appends a longer prefix or sorts the list for
38
+ readabilitysilently, resolving an Anthropic key as OpenAI. The ordering is now derived from
39
+ prefix length.
40
+ 2. **No provider-profile gate.** That gate belongs to the local-run path, which will not name a
41
+ provider it cannot construct. A caller asking "whose key is this?" at login has no profile
42
+ registered yet, and returning `undefined` there would answer a different question.
25
43
 
26
- A tabela de prefixos deixa de existir em duas copias: `inferProviderFromApiKey` passa a delegar e
27
- mantem so o que e politica dele.
44
+ The prefix table no longer exists in two copies: `inferProviderFromApiKey` delegates and keeps only
45
+ what is its own policy.
28
46
 
29
47
  ## 4.51.1
30
48
 
@@ -1,10 +1,10 @@
1
- export { Agent } from './chunk-ZFARZBOX.js';
2
- import './chunk-SPZZSAHV.js';
1
+ export { Agent } from './chunk-KELIQH7K.js';
2
+ import './chunk-42PLABFU.js';
3
3
  import './chunk-2SFBB54R.js';
4
4
  import './chunk-7TB5U7RK.js';
5
5
  import './chunk-K2BQQ445.js';
6
6
  import './chunk-J4RY5DTI.js';
7
- import './chunk-YBB66SZZ.js';
7
+ import './chunk-M5EK7N6R.js';
8
8
  import './chunk-4QEC4CCS.js';
9
9
  import './chunk-DHVNJYTO.js';
10
10
  import './chunk-UJ3SXRZZ.js';
@@ -18,7 +18,7 @@ import './chunk-OZXPA3ME.js';
18
18
  import './chunk-OXNYIMZZ.js';
19
19
  import './chunk-FD2UT76F.js';
20
20
  import './chunk-U54XCYG3.js';
21
- import './chunk-U3PAW4PL.js';
21
+ import './chunk-NAF4L3T6.js';
22
22
  import './chunk-RP5HQVLD.js';
23
23
  import './chunk-6X6ID4MO.js';
24
24
  import './chunk-4NAKHID5.js';
@@ -45,5 +45,5 @@ import './chunk-RIAM53CP.js';
45
45
  import './chunk-5XXUYU3M.js';
46
46
  import './chunk-HI4ZW62S.js';
47
47
  import './chunk-4X3SBHPK.js';
48
- //# sourceMappingURL=agent-HYQGJTIN.js.map
49
- //# sourceMappingURL=agent-HYQGJTIN.js.map
48
+ //# sourceMappingURL=agent-RDHK6MVT.js.map
49
+ //# sourceMappingURL=agent-RDHK6MVT.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-HYQGJTIN.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-RDHK6MVT.js"}
@@ -1,12 +1,12 @@
1
1
  'use strict';
2
2
 
3
- var chunkLLK2RS6I_cjs = require('./chunk-LLK2RS6I.cjs');
4
- require('./chunk-YARJG3GV.cjs');
3
+ var chunk6GS7JI64_cjs = require('./chunk-6GS7JI64.cjs');
4
+ require('./chunk-CY7MIMI4.cjs');
5
5
  require('./chunk-BV2MWEMV.cjs');
6
6
  require('./chunk-6DCTL32L.cjs');
7
7
  require('./chunk-BUUUWQMB.cjs');
8
8
  require('./chunk-OI6RHLGC.cjs');
9
- require('./chunk-ZNEYQ56O.cjs');
9
+ require('./chunk-WLESQ3ZQ.cjs');
10
10
  require('./chunk-4JBHSLQO.cjs');
11
11
  require('./chunk-RAACTJ7C.cjs');
12
12
  require('./chunk-3R4ZCQAZ.cjs');
@@ -20,7 +20,7 @@ require('./chunk-E3OCRJU6.cjs');
20
20
  require('./chunk-2RW7K6FN.cjs');
21
21
  require('./chunk-MUUQ2WFJ.cjs');
22
22
  require('./chunk-6JSIEDKL.cjs');
23
- require('./chunk-WVDH34LK.cjs');
23
+ require('./chunk-FRITRLZQ.cjs');
24
24
  require('./chunk-B4YA6BRS.cjs');
25
25
  require('./chunk-NINIJCHU.cjs');
26
26
  require('./chunk-L5YO6PWL.cjs');
@@ -52,7 +52,7 @@ require('./chunk-SXSPMRSV.cjs');
52
52
 
53
53
  Object.defineProperty(exports, "Agent", {
54
54
  enumerable: true,
55
- get: function () { return chunkLLK2RS6I_cjs.Agent; }
55
+ get: function () { return chunk6GS7JI64_cjs.Agent; }
56
56
  });
57
- //# sourceMappingURL=agent-C66BEJGO.cjs.map
58
- //# sourceMappingURL=agent-C66BEJGO.cjs.map
57
+ //# sourceMappingURL=agent-U2R2R5JP.cjs.map
58
+ //# sourceMappingURL=agent-U2R2R5JP.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-C66BEJGO.cjs"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-U2R2R5JP.cjs"}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkWVDH34LK_cjs = require('../chunk-WVDH34LK.cjs');
3
+ var chunkFRITRLZQ_cjs = require('../chunk-FRITRLZQ.cjs');
4
4
  var chunkXK54DTRF_cjs = require('../chunk-XK54DTRF.cjs');
5
5
  var chunkC6Y6CWYD_cjs = require('../chunk-C6Y6CWYD.cjs');
6
6
  require('../chunk-2YGIBOUH.cjs');
@@ -228,7 +228,7 @@ function extractAccountId(tokens) {
228
228
 
229
229
  Object.defineProperty(exports, "providerFromApiKeyPrefix", {
230
230
  enumerable: true,
231
- get: function () { return chunkWVDH34LK_cjs.providerFromApiKeyPrefix; }
231
+ get: function () { return chunkFRITRLZQ_cjs.providerFromApiKeyPrefix; }
232
232
  });
233
233
  Object.defineProperty(exports, "CredentialError", {
234
234
  enumerable: true,
@@ -12,6 +12,21 @@
12
12
  *
13
13
  * @packageDocumentation
14
14
  */
15
+ /**
16
+ * "Which provider issued this key?" — the question a login flow asks before any profile exists.
17
+ *
18
+ * Made REACHABLE rather than written: the SDK already answered it, from a module no entry point
19
+ * exported, and a measured consumer wrote its own copy because it could not import ours. The lookup
20
+ * now derives its longest-first ordering instead of depending on the order the table happens to be
21
+ * typed in.
22
+ *
23
+ * NOTE — do not name the internal-visibility tag in this docblock. `tsconfig.base.json` sets
24
+ * `stripInternal: true`, and TypeScript matches the tag anywhere in an attached JSDoc, prose
25
+ * included. Mentioning it here deleted this very line from `dist/auth/index.d.ts`: the symbol
26
+ * shipped at runtime and could not be imported with types — the exact defect this export exists to
27
+ * fix, reintroduced by the comment explaining the fix (usetheodev/theokit-sdk#283).
28
+ */
29
+ export { providerFromApiKeyPrefix } from "../internal/auth/api-key-prefix.js";
15
30
  export type { CredentialStoreConfig, DeviceCodeGrant, DeviceDeps, DeviceOAuthConfig, HttpDeps, OAuthProviderConfig, OAuthTokens, OpenAIDeviceConfig, ResolvedCredential, StoredApiCredential, StoredCredential, StoredOAuthCredential, } from "../internal/auth/auth-types.js";
16
31
  export { assertSecureModes, authFilePath, CredentialError, credentialHome, readAuthFile, readStoredOAuth, writeCredential, } from "../internal/auth/credential-store.js";
17
32
  export { deviceLogin, extractAccountId, openaiDeviceLogin, parseJwtClaims, pollDeviceToken, requestDeviceCode, requestOpenAIUsercode, } from "../internal/auth/oauth-device.js";
@@ -12,6 +12,21 @@
12
12
  *
13
13
  * @packageDocumentation
14
14
  */
15
+ /**
16
+ * "Which provider issued this key?" — the question a login flow asks before any profile exists.
17
+ *
18
+ * Made REACHABLE rather than written: the SDK already answered it, from a module no entry point
19
+ * exported, and a measured consumer wrote its own copy because it could not import ours. The lookup
20
+ * now derives its longest-first ordering instead of depending on the order the table happens to be
21
+ * typed in.
22
+ *
23
+ * NOTE — do not name the internal-visibility tag in this docblock. `tsconfig.base.json` sets
24
+ * `stripInternal: true`, and TypeScript matches the tag anywhere in an attached JSDoc, prose
25
+ * included. Mentioning it here deleted this very line from `dist/auth/index.d.ts`: the symbol
26
+ * shipped at runtime and could not be imported with types — the exact defect this export exists to
27
+ * fix, reintroduced by the comment explaining the fix (usetheodev/theokit-sdk#283).
28
+ */
29
+ export { providerFromApiKeyPrefix } from "../internal/auth/api-key-prefix.js";
15
30
  export type { CredentialStoreConfig, DeviceCodeGrant, DeviceDeps, DeviceOAuthConfig, HttpDeps, OAuthProviderConfig, OAuthTokens, OpenAIDeviceConfig, ResolvedCredential, StoredApiCredential, StoredCredential, StoredOAuthCredential, } from "../internal/auth/auth-types.js";
16
31
  export { assertSecureModes, authFilePath, CredentialError, credentialHome, readAuthFile, readStoredOAuth, writeCredential, } from "../internal/auth/credential-store.js";
17
32
  export { deviceLogin, extractAccountId, openaiDeviceLogin, parseJwtClaims, pollDeviceToken, requestDeviceCode, requestOpenAIUsercode, } from "../internal/auth/oauth-device.js";
@@ -1,4 +1,4 @@
1
- export { providerFromApiKeyPrefix } from '../chunk-U3PAW4PL.js';
1
+ export { providerFromApiKeyPrefix } from '../chunk-NAF4L3T6.js';
2
2
  import { exchangeCode } from '../chunk-BKRTYDVN.js';
3
3
  export { CredentialError, assertSecureModes, authFilePath, credentialHome, ensureFreshCredential, exchangeCode, persistOAuthTokens, readAuthFile, readStoredOAuth, refreshOAuthTokens, resolveCredential, writeCredential } from '../chunk-BKRTYDVN.js';
4
4
  import { AuthCallbackError } from '../chunk-5NBUH3NO.js';
@@ -46,7 +46,7 @@ function persistTurnToTranscript(store, loc, sessionId, turn, onCompact) {
46
46
  const count = (recordCounts.get(key) ?? 0) + 1;
47
47
  recordCounts.set(key, count);
48
48
  if (turn.autoCompact !== void 0) {
49
- const { autoCompactIfNeeded } = await import('./compact-session-DUAUEFRR.js');
49
+ const { autoCompactIfNeeded } = await import('./compact-session-XLXC2CZN.js');
50
50
  const fired = await autoCompactIfNeeded({
51
51
  store,
52
52
  loc,
@@ -105,5 +105,5 @@ function enqueueSessionWrite(cwd, agentId, fn) {
105
105
  }
106
106
 
107
107
  export { appendSessionMessage, clearSession, discardSession, enqueueSessionWrite, flushSessionWrites, getSessionMessages, hydrateSession, persistTurnToTranscript };
108
- //# sourceMappingURL=chunk-SPZZSAHV.js.map
109
- //# sourceMappingURL=chunk-SPZZSAHV.js.map
108
+ //# sourceMappingURL=chunk-42PLABFU.js.map
109
+ //# sourceMappingURL=chunk-42PLABFU.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":[],"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,GAAW,QAAA,CAAS,GAAA,CAAI,OAAO,KAAK,EAAC;AAC3C,EAAA,QAAA,CAAS,KAAK,OAAO,CAAA;AAIrB,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACvB,EAAA,QAAA,CAAS,GAAA,CAAI,SAAS,QAAQ,CAAA;AAC9B,EAAA,cAAA,EAAe;AACjB;AAWO,IAAM,mBAAA,GAAsB,EAAA;AAEnC,SAAS,cAAA,GAAuB;AAC9B,EAAA,OAAO,QAAA,CAAS,OAAO,mBAAA,EAAqB;AAC1C,IAAA,MAAM,MAAA,GAAS,QAAA,CAAS,IAAA,EAAK,CAAE,MAAK,CAAE,KAAA;AACtC,IAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,IAAA,QAAA,CAAS,OAAO,MAAM,CAAA;AACtB,IAAA,iBAAA,CAAkB,MAAM,CAAA;AAAA,EAC1B;AACF;AAeA,SAAS,kBAAkB,OAAA,EAAuB;AAChD,EAAA,MAAM,MAAA,GAAS,cAAc,EAAA,EAAI,OAAO,EAAE,KAAA,CAAM,CAAA,GAAI,OAAA,CAAQ,MAAA,GAAS,CAAC,CAAA;AACtE,EAAA,KAAA,MAAW,CAAA,IAAK,CAAC,GAAG,YAAY,CAAA,EAAG,IAAI,CAAA,CAAE,QAAA,CAAS,MAAM,CAAA,EAAG,YAAA,CAAa,MAAA,CAAO,CAAC,CAAA;AAChF,EAAA,KAAA,MAAW,CAAA,IAAK,CAAC,GAAG,aAAA,CAAc,MAAM,CAAA,E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W,CAAA,EAAG;AAM5B,EAAA,QAAA,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;AAEO,SAAS,aAAa,OAAA,EAAuB;AAClD,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAYO,SAAS,mBAAA,CACd,GAAA,EACA,OAAA,EACA,EAAA,EACY;AACZ,EAAA,MAAM,GAAA,GAAM,aAAA,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-SPZZSAHV.js","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":[],"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,GAAW,QAAA,CAAS,GAAA,CAAI,OAAO,KAAK,EAAC;AAC3C,EAAA,QAAA,CAAS,KAAK,OAAO,CAAA;AAIrB,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACvB,EAAA,QAAA,CAAS,GAAA,CAAI,SAAS,QAAQ,CAAA;AAC9B,EAAA,cAAA,EAAe;AACjB;AAWO,IAAM,mBAAA,GAAsB,EAAA;AAEnC,SAAS,cAAA,GAAuB;AAC9B,EAAA,OAAO,QAAA,CAAS,OAAO,mBAAA,EAAqB;AAC1C,IAAA,MAAM,MAAA,GAAS,QAAA,CAAS,IAAA,EAAK,CAAE,MAAK,CAAE,KAAA;AACtC,IAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,IAAA,QAAA,CAAS,OAAO,MAAM,CAAA;AACtB,IAAA,iBAAA,CAAkB,MAAM,CAAA;AAAA,EAC1B;AACF;AAeA,SAAS,kBAAkB,OAAA,EAAuB;AAChD,EAAA,MAAM,MAAA,GAAS,cAAc,EAAA,EAAI,OAAO,EAAE,KAAA,CAAM,CAAA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AAA,CAAc,GAAA,CAAI,GAAA,EAAK,OAAO,CAAA;AAC1C,EAAA,IAAI,YAAA,CAAa,GAAA,CAAI,GAAG,CAAA,EAAG;AAC3B,EAAA,YAAA,CAAa,IAAI,GAAG,CAAA;AAEpB,EAAA,MAAM,SAAA,GAAY,MAAM,mBAAA,CAAoB,GAAA,CAAI,OAAO,OAAO,CAAA;AAC9D,EAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAM5B,EAAA,QAAA,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;AAEO,SAAS,aAAa,OAAA,EAAuB;AAClD,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAYO,SAAS,mBAAA,CACd,GAAA,EACA,OAAA,EACA,EAAA,EACY;AACZ,EAAA,MAAM,GAAA,GAAM,aAAA,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-42PLABFU.js","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,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunkYARJG3GV_cjs = require('./chunk-YARJG3GV.cjs');
3
+ var chunkCY7MIMI4_cjs = require('./chunk-CY7MIMI4.cjs');
4
4
  var chunkBV2MWEMV_cjs = require('./chunk-BV2MWEMV.cjs');
5
5
  var chunk6DCTL32L_cjs = require('./chunk-6DCTL32L.cjs');
6
6
  var chunkOI6RHLGC_cjs = require('./chunk-OI6RHLGC.cjs');
7
- var chunkZNEYQ56O_cjs = require('./chunk-ZNEYQ56O.cjs');
7
+ var chunkWLESQ3ZQ_cjs = require('./chunk-WLESQ3ZQ.cjs');
8
8
  var chunkEQMLJ52C_cjs = require('./chunk-EQMLJ52C.cjs');
9
9
  var chunk3YYDHUNH_cjs = require('./chunk-3YYDHUNH.cjs');
10
10
  var chunkBBZYXVLZ_cjs = require('./chunk-BBZYXVLZ.cjs');
@@ -1617,7 +1617,7 @@ function createRealCloudRun(options) {
1617
1617
  conversation: []
1618
1618
  };
1619
1619
  const apiKey = resolveApiKey(options.agentOptions.apiKey);
1620
- const baseUrl = chunkZNEYQ56O_cjs.getConfiguredBaseUrl();
1620
+ const baseUrl = chunkWLESQ3ZQ_cjs.getConfiguredBaseUrl();
1621
1621
  const handle = new RealCloudRun(
1622
1622
  {
1623
1623
  id,
@@ -1700,7 +1700,7 @@ var RealCloudRun = class extends FixtureRunBase {
1700
1700
  async consumeStream(response) {
1701
1701
  let finalStatus = "finished";
1702
1702
  let finalText = "";
1703
- for await (const record of chunkZNEYQ56O_cjs.parseSseStream(response.body, this.controller.signal)) {
1703
+ for await (const record of chunkWLESQ3ZQ_cjs.parseSseStream(response.body, this.controller.signal)) {
1704
1704
  const parsed = safeParse(record.data);
1705
1705
  if (parsed === void 0) continue;
1706
1706
  const update = this.applyRecord(record.event, parsed);
@@ -1809,7 +1809,7 @@ var CloudAgent = class {
1809
1809
  */
1810
1810
  isFixtureMode() {
1811
1811
  const apiKey = resolveApiKey(this.options.apiKey);
1812
- return chunkZNEYQ56O_cjs.isFixtureApiKey(apiKey) && chunkZNEYQ56O_cjs.getConfiguredBaseUrl() === void 0;
1812
+ return chunkWLESQ3ZQ_cjs.isFixtureApiKey(apiKey) && chunkWLESQ3ZQ_cjs.getConfiguredBaseUrl() === void 0;
1813
1813
  }
1814
1814
  // SE9 — integrated structured output; delegates to the shared helper.
1815
1815
  generate(message, options) {
@@ -1860,7 +1860,7 @@ var CloudAgent = class {
1860
1860
  const userText = typeof message === "string" ? message : message.text;
1861
1861
  const systemPrompt = await this.resolveSystemPromptForSend(userText, options);
1862
1862
  const apiKey = resolveApiKey(this.options.apiKey);
1863
- const useRealRuntime = apiKey !== void 0 && !chunkZNEYQ56O_cjs.isFixtureApiKey(apiKey) && chunkZNEYQ56O_cjs.getConfiguredBaseUrl() !== void 0;
1863
+ const useRealRuntime = apiKey !== void 0 && !chunkWLESQ3ZQ_cjs.isFixtureApiKey(apiKey) && chunkWLESQ3ZQ_cjs.getConfiguredBaseUrl() !== void 0;
1864
1864
  return useRealRuntime ? createRealCloudRun({
1865
1865
  agentId: this.agentId,
1866
1866
  model: this.model ?? { id: DEFAULT_AGENTIC_MODEL_ID },
@@ -2680,7 +2680,7 @@ async function runPostRunLifecycle(inputs) {
2680
2680
  try {
2681
2681
  const partial = await safeConversation(run);
2682
2682
  if (partial !== void 0) {
2683
- chunkYARJG3GV_cjs.persistTurnToTranscript(sessionStore, { cwd: workspaceCwd, agentId, model }, agentId, {
2683
+ chunkCY7MIMI4_cjs.persistTurnToTranscript(sessionStore, { cwd: workspaceCwd, agentId, model }, agentId, {
2684
2684
  userText,
2685
2685
  conversation: partial
2686
2686
  });
@@ -2690,11 +2690,11 @@ async function runPostRunLifecycle(inputs) {
2690
2690
  chunkSXSPMRSV_cjs.diag(`[theokit-sdk] partial transcript write failed (${agentId}): ${msg}
2691
2691
  `);
2692
2692
  }
2693
- await chunkYARJG3GV_cjs.flushSessionWrites();
2693
+ await chunkCY7MIMI4_cjs.flushSessionWrites();
2694
2694
  return;
2695
2695
  }
2696
2696
  if (result.result !== void 0) {
2697
- chunkYARJG3GV_cjs.appendSessionMessage(agentId, { role: "assistant", text: result.result });
2697
+ chunkCY7MIMI4_cjs.appendSessionMessage(agentId, { role: "assistant", text: result.result });
2698
2698
  }
2699
2699
  const conversation = await safeConversation(run);
2700
2700
  const resolvedWindow = resolveWindowForRun(model, contextWindow);
@@ -2705,7 +2705,7 @@ async function runPostRunLifecycle(inputs) {
2705
2705
  }
2706
2706
  const lastRequestUsage = result.usage?.requests?.at(-1)?.totalTokens;
2707
2707
  const usageForTrigger = lastRequestUsage ?? result.usage?.totalTokens;
2708
- chunkYARJG3GV_cjs.persistTurnToTranscript(
2708
+ chunkCY7MIMI4_cjs.persistTurnToTranscript(
2709
2709
  sessionStore,
2710
2710
  { cwd: workspaceCwd, agentId, model },
2711
2711
  agentId,
@@ -2717,7 +2717,7 @@ async function runPostRunLifecycle(inputs) {
2717
2717
  // The EFFECTIVE window (after override, clamp and margin) — not the declared one. Swapping for
2718
2718
  // `contextWindow` here would budget against a number the clamp already rejected.
2719
2719
  contextWindow: effectiveWindow,
2720
- summarize: chunkZNEYQ56O_cjs.buildDefaultSummarizer({
2720
+ summarize: chunkWLESQ3ZQ_cjs.buildDefaultSummarizer({
2721
2721
  agentModel: model,
2722
2722
  ...inputs.apiKey !== void 0 ? { apiKey: inputs.apiKey } : {}
2723
2723
  })
@@ -2759,7 +2759,7 @@ async function runPostRunLifecycle(inputs) {
2759
2759
  agentId,
2760
2760
  runId: result.id
2761
2761
  });
2762
- await chunkYARJG3GV_cjs.flushSessionWrites();
2762
+ await chunkCY7MIMI4_cjs.flushSessionWrites();
2763
2763
  }
2764
2764
  async function safeConversation(run) {
2765
2765
  try {
@@ -3346,7 +3346,7 @@ var HISTOGRAM_NAMES = {
3346
3346
  };
3347
3347
  function safeRequire(moduleName) {
3348
3348
  try {
3349
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-LLK2RS6I.cjs', document.baseURI).href)));
3349
+ const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-6GS7JI64.cjs', document.baseURI).href)));
3350
3350
  return r(moduleName);
3351
3351
  } catch {
3352
3352
  return void 0;
@@ -3571,7 +3571,7 @@ var cachedOtel;
3571
3571
  function loadOtel() {
3572
3572
  if (cachedOtel === void 0) {
3573
3573
  try {
3574
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-LLK2RS6I.cjs', document.baseURI).href)));
3574
+ const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-6GS7JI64.cjs', document.baseURI).href)));
3575
3575
  const mod = r("@opentelemetry/api");
3576
3576
  cachedOtel = mod;
3577
3577
  } catch {
@@ -5770,7 +5770,7 @@ function applyToolResultGuard(parts, opts) {
5770
5770
  (p) => (
5771
5771
  // SE7 — guard the TEXT of a tool result (string or the text blocks of a
5772
5772
  // structured content); image blocks pass through untouched.
5773
- p.type === "tool_result" ? { ...p, content: chunkZNEYQ56O_cjs.renderToolResultContentText(p.content, (t) => guardText(t, opts)) } : p
5773
+ p.type === "tool_result" ? { ...p, content: chunkWLESQ3ZQ_cjs.renderToolResultContentText(p.content, (t) => guardText(t, opts)) } : p
5774
5774
  )
5775
5775
  );
5776
5776
  }
@@ -6430,12 +6430,12 @@ var FallbackLlmClient = class {
6430
6430
  let lastError;
6431
6431
  for (const client of this.clients) {
6432
6432
  if (signal.aborted) throw abortError(signal);
6433
- const attempt = await chunkZNEYQ56O_cjs.tryFirstEvent(client, request, signal, true);
6433
+ const attempt = await chunkWLESQ3ZQ_cjs.tryFirstEvent(client, request, signal, true);
6434
6434
  if (attempt.kind === "handshake_error") {
6435
6435
  lastError = attempt.error;
6436
6436
  continue;
6437
6437
  }
6438
- return yield* chunkZNEYQ56O_cjs.relayStream(attempt.generator, attempt.firstResult);
6438
+ return yield* chunkWLESQ3ZQ_cjs.relayStream(attempt.generator, attempt.firstResult);
6439
6439
  }
6440
6440
  if (lastError !== void 0) throw lastError;
6441
6441
  throw new chunk2YGIBOUH_cjs.NetworkError("FallbackLlmClient has no providers configured", {
@@ -7016,14 +7016,14 @@ function resolveRunProvider(options) {
7016
7016
  }
7017
7017
  const parsedModel = chunkVYHJZVL5_cjs.parseModelId(options.model?.id);
7018
7018
  const modelInferredProvider = parsedModel.provider !== void 0 && chunkT6ZCG5AP_cjs.getProviderProfile(parsedModel.provider) !== void 0 ? parsedModel.provider : void 0;
7019
- const keyInferredProvider = chunkZNEYQ56O_cjs.inferProviderFromApiKey(options.agentOptions.apiKey);
7020
- const primary = options.agentOptions.providers?.routes?.[0]?.provider ?? keyInferredProvider ?? modelInferredProvider ?? chunkZNEYQ56O_cjs.detectPrimaryProvider();
7019
+ const keyInferredProvider = chunkWLESQ3ZQ_cjs.inferProviderFromApiKey(options.agentOptions.apiKey);
7020
+ const primary = options.agentOptions.providers?.routes?.[0]?.provider ?? keyInferredProvider ?? modelInferredProvider ?? chunkWLESQ3ZQ_cjs.detectPrimaryProvider();
7021
7021
  const effectiveModelId = modelInferredProvider !== void 0 && modelInferredProvider === primary ? parsedModel.name : options.model?.id ?? "claude-sonnet-4-6";
7022
7022
  return { primary, effectiveModelId };
7023
7023
  }
7024
7024
  function mergeExplicitApiKey(pools, primary, apiKey) {
7025
7025
  if (apiKey === void 0 || apiKey.length === 0) return pools;
7026
- if (chunkZNEYQ56O_cjs.isFixtureApiKey(apiKey) || apiKey === LOCAL_RUNTIME_MOCK_KEY) return pools;
7026
+ if (chunkWLESQ3ZQ_cjs.isFixtureApiKey(apiKey) || apiKey === LOCAL_RUNTIME_MOCK_KEY) return pools;
7027
7027
  const existing = pools?.[primary];
7028
7028
  if (existing !== void 0 && existing.length > 0) return pools;
7029
7029
  return { ...pools ?? {}, [primary]: [apiKey] };
@@ -7046,7 +7046,7 @@ function buildLoopInputs(options, runId, userText, userImages) {
7046
7046
  const credentialPoolStrategy = options.agentOptions.providers?.credentialPoolStrategy;
7047
7047
  const extractToolCallsFromContent = options.agentOptions.providers?.routes?.[0]?.extractToolCallsFromContent;
7048
7048
  const rateLimitSink = options.sendOptions.onRunEvent;
7049
- const chain = chunkZNEYQ56O_cjs.resolveProviderChain({
7049
+ const chain = chunkWLESQ3ZQ_cjs.resolveProviderChain({
7050
7050
  primary,
7051
7051
  ...fallback !== void 0 ? { fallback } : {},
7052
7052
  ...apiKeys !== void 0 ? { apiKeys } : {},
@@ -7328,7 +7328,7 @@ function buildRealRunOptions(args) {
7328
7328
  };
7329
7329
  }
7330
7330
  async function createFixtureRunHelper(args) {
7331
- const sessionMessages = chunkYARJG3GV_cjs.getSessionMessages(args.inputs.agentId);
7331
+ const sessionMessages = chunkCY7MIMI4_cjs.getSessionMessages(args.inputs.agentId);
7332
7332
  const projectMcpServers = args.inputs.settingSourcesIncludeProject ? await readProjectMcpServers(args.inputs.workspaceCwd) : {};
7333
7333
  return createLocalRun({
7334
7334
  agentId: args.inputs.agentId,
@@ -7347,7 +7347,7 @@ async function createFixtureRunHelper(args) {
7347
7347
  }
7348
7348
  async function dispatchLocalRun(args) {
7349
7349
  const apiKey = resolveApiKey(args.inputs.options.apiKey);
7350
- if (chunkZNEYQ56O_cjs.shouldUseRealLocalRuntime(apiKey)) {
7350
+ if (chunkWLESQ3ZQ_cjs.shouldUseRealLocalRuntime(apiKey)) {
7351
7351
  return createRealLocalRun(
7352
7352
  buildRealRunOptions({
7353
7353
  inputs: args.inputs,
@@ -7603,10 +7603,10 @@ async function disposeLocalAgentSession(agent) {
7603
7603
  agent.lifecycleAbortController.abort();
7604
7604
  await chunkYLQQX5W2_cjs.withCwdMutex(`agent-send:${agent.agentId}`, () => Promise.resolve());
7605
7605
  disposeSessionMcpClients(agent.agentId);
7606
- await chunkYARJG3GV_cjs.flushSessionWrites();
7606
+ await chunkCY7MIMI4_cjs.flushSessionWrites();
7607
7607
  await flushRegistrySaves(agent.workspaceCwd);
7608
7608
  await disposeSessionStore(agent.sessionStore);
7609
- chunkYARJG3GV_cjs.discardSession(agent.workspaceCwd, agent.agentId);
7609
+ chunkCY7MIMI4_cjs.discardSession(agent.workspaceCwd, agent.agentId);
7610
7610
  }
7611
7611
  async function reloadLocalAgent(agent) {
7612
7612
  if (agent.context !== void 0) await agent.context.refresh();
@@ -8380,7 +8380,7 @@ var LocalAgentMemory = class {
8380
8380
  async runActiveMemoryIfEnabled(userText, priorMessages, telemetry) {
8381
8381
  const cfg = this.options.memory?.activeRecall;
8382
8382
  if (cfg?.enabled !== true || this.index === void 0) return void 0;
8383
- if (this.breaker === void 0) this.breaker = new chunkZNEYQ56O_cjs.CircuitBreaker();
8383
+ if (this.breaker === void 0) this.breaker = new chunkWLESQ3ZQ_cjs.CircuitBreaker();
8384
8384
  if (this.cache === void 0) this.cache = new ActiveMemoryCache();
8385
8385
  const result = await runActiveMemory({
8386
8386
  userText,
@@ -8782,8 +8782,8 @@ async function localAgentUsePersonality(args) {
8782
8782
  registry,
8783
8783
  store: args.personalityStore,
8784
8784
  invalidateCache: (reason) => args.invalidateCache(reason),
8785
- appendSessionMessage: (msg) => chunkYARJG3GV_cjs.appendSessionMessage(args.agentId, msg),
8786
- clearSession: () => chunkYARJG3GV_cjs.clearSession(args.agentId),
8785
+ appendSessionMessage: (msg) => chunkCY7MIMI4_cjs.appendSessionMessage(args.agentId, msg),
8786
+ clearSession: () => chunkCY7MIMI4_cjs.clearSession(args.agentId),
8787
8787
  opts: args.opts ?? {}
8788
8788
  })
8789
8789
  );
@@ -9137,7 +9137,7 @@ async function executeSendLocked(inputs, message, options) {
9137
9137
  if (inputs.options.onBeforeSend !== void 0) {
9138
9138
  await inputs.options.onBeforeSend({
9139
9139
  conversationId: inputs.agentId,
9140
- previousMessageCount: chunkYARJG3GV_cjs.getSessionMessages(inputs.agentId).length
9140
+ previousMessageCount: chunkCY7MIMI4_cjs.getSessionMessages(inputs.agentId).length
9141
9141
  });
9142
9142
  }
9143
9143
  await inputs.runPreHook(userText);
@@ -9149,8 +9149,8 @@ async function executeSendLocked(inputs, message, options) {
9149
9149
  userText,
9150
9150
  sendOptions: options
9151
9151
  });
9152
- const priorMessages = [...chunkYARJG3GV_cjs.getSessionMessages(inputs.agentId)];
9153
- chunkYARJG3GV_cjs.appendSessionMessage(inputs.agentId, { role: "user", text: userText });
9152
+ const priorMessages = [...chunkCY7MIMI4_cjs.getSessionMessages(inputs.agentId)];
9153
+ chunkCY7MIMI4_cjs.appendSessionMessage(inputs.agentId, { role: "user", text: userText });
9154
9154
  await persistMemoryFactIfWritePrompt(inputs.workspaceCwd, inputs.options.memory, userText);
9155
9155
  const memoryFacts = await readMemoryForSend(inputs.workspaceCwd, inputs.options.memory);
9156
9156
  const portPathActive = shouldUsePortMemoryPath();
@@ -9362,7 +9362,7 @@ var LocalAgent = class {
9362
9362
  );
9363
9363
  await acquireLeaseIfPossible(this.sessionStore, this.agentId);
9364
9364
  try {
9365
- await chunkYARJG3GV_cjs.hydrateSession(this.agentId, { store: this.sessionStore, cwd: this.workspaceCwd });
9365
+ await chunkCY7MIMI4_cjs.hydrateSession(this.agentId, { store: this.sessionStore, cwd: this.workspaceCwd });
9366
9366
  await this.personalityStore.hydrate(this.agentId);
9367
9367
  } catch (err) {
9368
9368
  await releaseLeaseIfPossible(this.sessionStore, this.agentId);
@@ -9695,7 +9695,7 @@ async function createLocalAgent(options) {
9695
9695
  if (apiKey === void 0) {
9696
9696
  throw new chunk2YGIBOUH_cjs.AuthenticationError("Missing API key", { code: "missing_api_key" });
9697
9697
  }
9698
- const willFlowToProvider = !chunkZNEYQ56O_cjs.isFixtureApiKey(apiKey) && !chunkZNEYQ56O_cjs.shouldUseRealLocalRuntime(apiKey);
9698
+ const willFlowToProvider = !chunkWLESQ3ZQ_cjs.isFixtureApiKey(apiKey) && !chunkWLESQ3ZQ_cjs.shouldUseRealLocalRuntime(apiKey);
9699
9699
  const shape = validateApiKeyShape(apiKey, {
9700
9700
  strict: willFlowToProvider,
9701
9701
  // `options.model` is already normalized by `runCreateUnderSpan`; `normalizeModel`
@@ -9706,7 +9706,7 @@ async function createLocalAgent(options) {
9706
9706
  if (shape.malformed) {
9707
9707
  throw new chunk2YGIBOUH_cjs.AuthenticationError(shape.message, { code: "malformed_api_key" });
9708
9708
  }
9709
- if (!chunkZNEYQ56O_cjs.isFixtureApiKey(apiKey) && chunkZNEYQ56O_cjs.getConfiguredBaseUrl() === void 0 && !chunkZNEYQ56O_cjs.shouldUseRealLocalRuntime(apiKey)) {
9709
+ if (!chunkWLESQ3ZQ_cjs.isFixtureApiKey(apiKey) && chunkWLESQ3ZQ_cjs.getConfiguredBaseUrl() === void 0 && !chunkWLESQ3ZQ_cjs.shouldUseRealLocalRuntime(apiKey)) {
9710
9710
  throw new chunk2YGIBOUH_cjs.AuthenticationError("Invalid API key", {
9711
9711
  code: "authentication_error"
9712
9712
  });
@@ -9726,11 +9726,11 @@ async function createCloudAgent(options) {
9726
9726
  if (shape.malformed) {
9727
9727
  throw new chunk2YGIBOUH_cjs.AuthenticationError(shape.message, { code: "malformed_api_key" });
9728
9728
  }
9729
- const baseUrl = chunkZNEYQ56O_cjs.getConfiguredBaseUrl();
9729
+ const baseUrl = chunkWLESQ3ZQ_cjs.getConfiguredBaseUrl();
9730
9730
  if (baseUrl === void 0) {
9731
9731
  return new CloudAgent(options);
9732
9732
  }
9733
- const response = await chunkZNEYQ56O_cjs.httpRequest("/v1/agents", {
9733
+ const response = await chunkWLESQ3ZQ_cjs.httpRequest("/v1/agents", {
9734
9734
  apiKey,
9735
9735
  method: "POST",
9736
9736
  body: {
@@ -9755,7 +9755,7 @@ function resolveAgentPersistenceCwd(options) {
9755
9755
  return process.cwd();
9756
9756
  }
9757
9757
  async function rehydrateExistingAgent(agentId, existing, options) {
9758
- await chunkZNEYQ56O_cjs.discoverProviderPlugins();
9758
+ await chunkWLESQ3ZQ_cjs.discoverProviderPlugins();
9759
9759
  await validateRehydratedAgent(agentId, existing);
9760
9760
  const mergedLocal = options.local !== void 0 && existing.options.local !== void 0 ? { ...existing.options.local, ...options.local } : options.local ?? existing.options.local;
9761
9761
  const mergedOptions = {
@@ -9883,7 +9883,7 @@ var Agent = class _Agent {
9883
9883
  pluginCount: enabledPluginNames(options.plugins).length
9884
9884
  });
9885
9885
  try {
9886
- await chunkZNEYQ56O_cjs.discoverProviderPlugins();
9886
+ await chunkWLESQ3ZQ_cjs.discoverProviderPlugins();
9887
9887
  const agent = await runCreateUnderSpan(options, span);
9888
9888
  return agent;
9889
9889
  } catch (err) {
@@ -10152,9 +10152,9 @@ var Agent = class _Agent {
10152
10152
  `No local agent "${agentId}" registered \u2014 compact targets local sessions.`
10153
10153
  );
10154
10154
  }
10155
- const { compactSessionTranscript, buildDefaultSummarizer: buildDefaultSummarizer2 } = await import('./compact-session-AXKDB6FC.cjs');
10155
+ const { compactSessionTranscript, buildDefaultSummarizer: buildDefaultSummarizer2 } = await import('./compact-session-FBVWO6B3.cjs');
10156
10156
  const { cwd, model, store } = await openLocalStore(reg);
10157
- return chunkYARJG3GV_cjs.enqueueSessionWrite(
10157
+ return chunkCY7MIMI4_cjs.enqueueSessionWrite(
10158
10158
  cwd,
10159
10159
  agentId,
10160
10160
  () => compactSessionTranscript({
@@ -10188,7 +10188,7 @@ var Agent = class _Agent {
10188
10188
  `No local agent "${agentId}" registered \u2014 injectSessionTurn targets local sessions.`
10189
10189
  );
10190
10190
  }
10191
- const { injectSessionTurn } = await import('./inject-session-TASLP5FA.cjs');
10191
+ const { injectSessionTurn } = await import('./inject-session-UBAQ7I3G.cjs');
10192
10192
  const { cwd, model, store } = await openLocalStore(reg);
10193
10193
  await injectSessionTurn({
10194
10194
  store,
@@ -10333,5 +10333,5 @@ exports.generateCronId = generateCronId;
10333
10333
  exports.getPricingEntry = getPricingEntry;
10334
10334
  exports.openRouterMemoryEmbeddingProviderAdapter = openRouterMemoryEmbeddingProviderAdapter;
10335
10335
  exports.resolveApiKey = resolveApiKey;
10336
- //# sourceMappingURL=chunk-LLK2RS6I.cjs.map
10337
- //# sourceMappingURL=chunk-LLK2RS6I.cjs.map
10336
+ //# sourceMappingURL=chunk-6GS7JI64.cjs.map
10337
+ //# sourceMappingURL=chunk-6GS7JI64.cjs.map