@theokit/sdk 5.3.2 → 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.
Files changed (83) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/{agent-KJLAWKZB.cjs → agent-AUVD4TI4.cjs} +9 -9
  3. package/dist/{agent-KJLAWKZB.cjs.map → agent-AUVD4TI4.cjs.map} +1 -1
  4. package/dist/{agent-CTbU0O1R.d.ts → agent-Bmy2G_ml.d.ts} +73 -2
  5. package/dist/{agent-QLwxhXY3.d.cts → agent-C1Efo7PI.d.cts} +73 -2
  6. package/dist/{agent-PNYJ5S2Y.js → agent-MNINE73R.js} +8 -8
  7. package/dist/{agent-PNYJ5S2Y.js.map → agent-MNINE73R.js.map} +1 -1
  8. package/dist/{chunk-AWINL3ZC.js → chunk-2QKV4CGK.js} +3 -3
  9. package/dist/{chunk-AWINL3ZC.js.map → chunk-2QKV4CGK.js.map} +1 -1
  10. package/dist/{chunk-65UMH5V3.cjs → chunk-3FDU5JFE.cjs} +5 -5
  11. package/dist/{chunk-65UMH5V3.cjs.map → chunk-3FDU5JFE.cjs.map} +1 -1
  12. package/dist/{chunk-DWB3CN46.cjs → chunk-43YXGD3P.cjs} +14 -4
  13. package/dist/chunk-43YXGD3P.cjs.map +1 -0
  14. package/dist/{chunk-IQBDR5YZ.cjs → chunk-AYA65JA5.cjs} +5 -5
  15. package/dist/{chunk-IQBDR5YZ.cjs.map → chunk-AYA65JA5.cjs.map} +1 -1
  16. package/dist/{chunk-2HPNT6HH.cjs → chunk-C4ZQPWXJ.cjs} +9 -9
  17. package/dist/chunk-C4ZQPWXJ.cjs.map +1 -0
  18. package/dist/{chunk-Y2KYR2ED.cjs → chunk-DZG77WU7.cjs} +3 -3
  19. package/dist/{chunk-Y2KYR2ED.cjs.map → chunk-DZG77WU7.cjs.map} +1 -1
  20. package/dist/{chunk-363RBGIR.js → chunk-IKBLU7ZS.js} +58 -27
  21. package/dist/chunk-IKBLU7ZS.js.map +1 -0
  22. package/dist/{chunk-L4XENLQO.cjs → chunk-J6KZE2ZQ.cjs} +4 -4
  23. package/dist/{chunk-L4XENLQO.cjs.map → chunk-J6KZE2ZQ.cjs.map} +1 -1
  24. package/dist/{chunk-ZITYGJOD.js → chunk-KWGSBZ2Q.js} +3 -3
  25. package/dist/{chunk-ZITYGJOD.js.map → chunk-KWGSBZ2Q.js.map} +1 -1
  26. package/dist/{chunk-K3NH62DG.js → chunk-KZSKIUXZ.js} +7 -7
  27. package/dist/chunk-KZSKIUXZ.js.map +1 -0
  28. package/dist/{chunk-RP3VXJMA.js → chunk-NSLHPAC7.js} +14 -4
  29. package/dist/chunk-NSLHPAC7.js.map +1 -0
  30. package/dist/{chunk-DLFWMJE3.js → chunk-O7L7M42F.js} +3 -3
  31. package/dist/{chunk-DLFWMJE3.js.map → chunk-O7L7M42F.js.map} +1 -1
  32. package/dist/{chunk-Y46VI73J.cjs → chunk-UALC6Q3J.cjs} +127 -96
  33. package/dist/chunk-UALC6Q3J.cjs.map +1 -0
  34. package/dist/{chunk-7L3MIW2F.js → chunk-XD3FS5OI.js} +3 -3
  35. package/dist/{chunk-7L3MIW2F.js.map → chunk-XD3FS5OI.js.map} +1 -1
  36. package/dist/{compact-session-BHTPCIHA.cjs → compact-session-7FMYJXQ7.cjs} +11 -11
  37. package/dist/{compact-session-BHTPCIHA.cjs.map → compact-session-7FMYJXQ7.cjs.map} +1 -1
  38. package/dist/{compact-session-W4WLJTHA.js → compact-session-YSEK7NQF.js} +3 -3
  39. package/dist/{compact-session-W4WLJTHA.js.map → compact-session-YSEK7NQF.js.map} +1 -1
  40. package/dist/{context-FCCJQ3FN.cjs → context-4AIK26QB.cjs} +7 -7
  41. package/dist/{context-FCCJQ3FN.cjs.map → context-4AIK26QB.cjs.map} +1 -1
  42. package/dist/context-EGM6CHXD.js +6 -0
  43. package/dist/{context-BUIE52VH.js.map → context-EGM6CHXD.js.map} +1 -1
  44. package/dist/{cron-Dz8AOpy3.d.cts → cron-DSMdlhyF.d.cts} +1 -1
  45. package/dist/{cron-Cl8FrK3D.d.ts → cron-Dcdrdv_T.d.ts} +1 -1
  46. package/dist/cron.cjs +8 -8
  47. package/dist/cron.d.cts +2 -2
  48. package/dist/cron.d.ts +2 -2
  49. package/dist/cron.js +7 -7
  50. package/dist/eval.cjs +7 -7
  51. package/dist/eval.js +6 -6
  52. package/dist/index.cjs +30 -30
  53. package/dist/index.d.cts +3 -3
  54. package/dist/index.d.ts +3 -3
  55. package/dist/index.js +9 -9
  56. package/dist/{inject-session-SUM6TDJF.js → inject-session-J4LBWAPH.js} +3 -3
  57. package/dist/{inject-session-SUM6TDJF.js.map → inject-session-J4LBWAPH.js.map} +1 -1
  58. package/dist/{inject-session-W6A46J3E.cjs → inject-session-PC73TMP2.cjs} +4 -4
  59. package/dist/{inject-session-W6A46J3E.cjs.map → inject-session-PC73TMP2.cjs.map} +1 -1
  60. package/dist/internal/llm/tool-result-content.d.ts +1 -1
  61. package/dist/internal/persistence/index.cjs +4 -4
  62. package/dist/internal/persistence/index.js +1 -1
  63. package/dist/internal/runtime/hooks/hooks-executor.d.ts +25 -1
  64. package/dist/subagents-loader-AIVDQ2D5.js +7 -0
  65. package/dist/{subagents-loader-PAZVOZHI.js.map → subagents-loader-AIVDQ2D5.js.map} +1 -1
  66. package/dist/subagents-loader-DN4LETGL.cjs +16 -0
  67. package/dist/{subagents-loader-7G76XOZU.cjs.map → subagents-loader-DN4LETGL.cjs.map} +1 -1
  68. package/dist/subagents-loader.cjs +3 -3
  69. package/dist/subagents-loader.d.cts +1 -1
  70. package/dist/subagents-loader.d.ts +1 -1
  71. package/dist/subagents-loader.js +2 -2
  72. package/dist/types/agent.d.ts +25 -2
  73. package/dist/types/hooks.d.ts +48 -0
  74. package/package.json +1 -1
  75. package/dist/chunk-2HPNT6HH.cjs.map +0 -1
  76. package/dist/chunk-363RBGIR.js.map +0 -1
  77. package/dist/chunk-DWB3CN46.cjs.map +0 -1
  78. package/dist/chunk-K3NH62DG.js.map +0 -1
  79. package/dist/chunk-RP3VXJMA.js.map +0 -1
  80. package/dist/chunk-Y46VI73J.cjs.map +0 -1
  81. package/dist/context-BUIE52VH.js +0 -6
  82. package/dist/subagents-loader-7G76XOZU.cjs +0 -16
  83. package/dist/subagents-loader-PAZVOZHI.js +0 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,79 @@
1
1
  # Changelog
2
2
 
3
+ ## 5.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#633](https://github.com/usetheokit/theokit-sdk/pull/633) [`ee1e174`](https://github.com/usetheokit/theokit-sdk/commit/ee1e1748f4d0c5f2d4efdacd68a49d2a0b5e09cb) Thanks [@usetheodev](https://github.com/usetheodev)! - The native config root can decline a surface, and a consumer can refuse a hook before it is spawned ([#631](https://github.com/usetheokit/theokit-sdk/issues/631))
8
+
9
+ Two additions, both absent-means-today's-behaviour.
10
+
11
+ ## `{ kind: "theokit", import: [...] }` in `compatSources`
12
+
13
+ `projectConfigRoots` prepended `.theokit/` unconditionally. A **foreign** dialect could already declare which surfaces it contributes; the SDK's own root could declare nothing and contributed all four, always.
14
+
15
+ That asymmetry had a measured cost. `hookConfigCandidates` reads `settings.json` from every root, so a consumer keeping its own configuration in `.theokit/settings.json` had that file's `hooks` key executed by this package — with no gate, and twice when the consumer also ran them. Measured by `usetheoai-lab/TheoCode`: unapproved fired once, approved fired twice.
16
+
17
+ The consumer could not opt out: `settingSources` grants a dialect per SOURCE, not per surface, so dropping `claude-code` to avoid its hooks would also drop its skills, agents and rules — the reason an adopter can use this SDK without migrating anything.
18
+
19
+ ```ts
20
+ local: { compatSources: [{ kind: "theokit", import: ["skills", "subagents"] }] }
21
+ // hooks omitted on purpose — this package will not read them from .theokit/
22
+ ```
23
+
24
+ Declaring nothing keeps every surface, exactly as before. A bare `"theokit"` admits everything, matching the rule foreign kinds already follow. It rides on `compatSources`, which already reaches all four surfaces, so no new parameter is threaded anywhere.
25
+
26
+ **Deliberately not included: renaming the directory.** `theokitConfigRoot` is also the DATA root — `agent-registry-store.ts` builds `registry.json`'s path from it directly — so a `dirName` override would move persisted state. Different change, different blast radius, its own migration question.
27
+
28
+ ## `local.hooks.approve`
29
+
30
+ ```ts
31
+ local: { hooks: { approve: (req) => myFingerprintStore.has(req.command) } }
32
+ ```
33
+
34
+ Consulted at the single point a hook is spawned, for every root — including a foreign dialect's, which the declaration above cannot reach. The request carries the command text, the event, and the file it was declared in, because a consumer's fingerprint is over the command and the source is what separates its own configuration from a dialect it merely imported.
35
+
36
+ Absent means run: a gate defaulting to refusal would disable every hook in the ecosystem on an upgrade.
37
+
38
+ **A refused hook resolves as if it were not configured — it does not deny the operation.** `preRun` and `preToolUse` decisions can block what they attach to, so treating "not approved" as a denial would make an unapproved hook worse than an absent one. The consumer asked for the command not to run, not for the work to stop.
39
+
40
+ ### Patch Changes
41
+
42
+ - [#633](https://github.com/usetheokit/theokit-sdk/pull/633) [`ee1e174`](https://github.com/usetheokit/theokit-sdk/commit/ee1e1748f4d0c5f2d4efdacd68a49d2a0b5e09cb) Thanks [@usetheodev](https://github.com/usetheodev)! - The image-in-tool-results refusal names the tool call whose result carried the image ([#629](https://github.com/usetheokit/theokit-sdk/issues/629))
43
+
44
+ Before:
45
+
46
+ ```
47
+ provider "openai-responses" does not support image content in tool results
48
+ ```
49
+
50
+ After:
51
+
52
+ ```
53
+ provider "openai-responses" does not support image content in tool results —
54
+ the result of tool call call_42 carried an image, and this wire carries tool results as text only
55
+ ```
56
+
57
+ Accurate before, and unhelpful. The person who hit it had attached an image and asked a question about it; they never asked for a tool, so a message naming *tool results* pointed at a surface they had not used. Measured downstream (`usetheoai-lab/TheoCode#133`): the turn that failed made two tool calls and the five that succeeded made none — asking for *dimensions and colours* provoked a tool call, asking for *one word* did not, which is why it looked intermittent and was not.
58
+
59
+ The **id** rather than the tool's name, and stated rather than quietly settled for: `LlmToolResultPart` carries `toolUseId` only — the name lives on the matching `LlmToolCallPart` in an earlier message, and the four sites that construct a tool result do not have it either. The id is the correlation key that exists at the call site, it is what a reader can find in a transcript, and it does not pretend to be a name.
60
+
61
+ The parameter is optional, so nothing that calls this helper with two arguments changes.
62
+
63
+ ## 5.3.3
64
+
65
+ ### Patch Changes
66
+
67
+ - [#624](https://github.com/usetheokit/theokit-sdk/pull/624) [`1ef64b0`](https://github.com/usetheokit/theokit-sdk/commit/1ef64b06f418d1194a699c2924286d87d5271b90) Thanks [@usetheodev](https://github.com/usetheodev)! - README: say that `.theokit/settings.json` is read, because it is
68
+
69
+ Docs only. The `## Hooks` section named `.theokit/hooks.json` and nothing else, and the only mention of `settings.json` / `settings.local.json` sat in the Claude Code compatibility table — which reads as being about `.claude/`.
70
+
71
+ So a reader asking *"what does this package read in `.theokit/`?"* got `hooks.json`, full stop. That answer is wrong: `hookConfigCandidates` reads `hooks.json`, `settings.json` and `settings.local.json` from **every** config root, and `theokitConfigRoot` is always one of them.
72
+
73
+ This is not an omission that merely leaves someone uninformed — it returns the wrong answer to the person doing the right thing. Measured in 2026-09: a consumer put its own configuration in `.theokit/settings.json` with a `hooks` array of its own shape, and hit a hard refusal on **every turn**. The file parsed perfectly for the product that wrote it; the collision was one of shape, not of location, and nothing in this README would have warned them.
74
+
75
+ The section now names all three files and states the consequence: `.theokit/` is this package's filebase, so a `hooks` key there is read and validated here, whatever else wrote the file.
76
+
3
77
  ## 5.3.2
4
78
 
5
79
  ### Patch Changes
@@ -1,18 +1,18 @@
1
1
  'use strict';
2
2
 
3
- var chunkY46VI73J_cjs = require('./chunk-Y46VI73J.cjs');
3
+ var chunkUALC6Q3J_cjs = require('./chunk-UALC6Q3J.cjs');
4
4
  require('./chunk-KVSAY6NZ.cjs');
5
- require('./chunk-Y2KYR2ED.cjs');
5
+ require('./chunk-DZG77WU7.cjs');
6
6
  require('./chunk-BUUUWQMB.cjs');
7
7
  require('./chunk-Z2JFX372.cjs');
8
- require('./chunk-65UMH5V3.cjs');
8
+ require('./chunk-3FDU5JFE.cjs');
9
9
  require('./chunk-BV2MWEMV.cjs');
10
10
  require('./chunk-D6POWE7E.cjs');
11
11
  require('./chunk-GHX4P3V2.cjs');
12
12
  require('./chunk-TMKTSYDS.cjs');
13
13
  require('./chunk-NQTNSHSB.cjs');
14
14
  require('./chunk-7FDKWDA2.cjs');
15
- require('./chunk-2HPNT6HH.cjs');
15
+ require('./chunk-C4ZQPWXJ.cjs');
16
16
  require('./chunk-FUSDYC2B.cjs');
17
17
  require('./chunk-YJNYDJ2T.cjs');
18
18
  require('./chunk-24SYBZPL.cjs');
@@ -43,8 +43,8 @@ require('./chunk-BJUJT5ED.cjs');
43
43
  require('./chunk-ZF2LDKQQ.cjs');
44
44
  require('./chunk-HCT4HPCL.cjs');
45
45
  require('./chunk-JLRLCBJ4.cjs');
46
- require('./chunk-IQBDR5YZ.cjs');
47
- require('./chunk-DWB3CN46.cjs');
46
+ require('./chunk-AYA65JA5.cjs');
47
+ require('./chunk-43YXGD3P.cjs');
48
48
  require('./chunk-HW7SEELD.cjs');
49
49
  require('./chunk-ATT276RD.cjs');
50
50
  require('./chunk-3EE6LVWT.cjs');
@@ -61,7 +61,7 @@ require('./chunk-6LHQPOMI.cjs');
61
61
 
62
62
  Object.defineProperty(exports, "Agent", {
63
63
  enumerable: true,
64
- get: function () { return chunkY46VI73J_cjs.Agent; }
64
+ get: function () { return chunkUALC6Q3J_cjs.Agent; }
65
65
  });
66
- //# sourceMappingURL=agent-KJLAWKZB.cjs.map
67
- //# sourceMappingURL=agent-KJLAWKZB.cjs.map
66
+ //# sourceMappingURL=agent-AUVD4TI4.cjs.map
67
+ //# sourceMappingURL=agent-AUVD4TI4.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-KJLAWKZB.cjs"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-AUVD4TI4.cjs"}
@@ -348,6 +348,55 @@ interface BudgetTracker {
348
348
  nextIteration?(): void;
349
349
  }
350
350
 
351
+ /**
352
+ * Hook contract types.
353
+ *
354
+ * Owner: `internal/runtime/hooks/` (2 of 3 importers). Derived from the import graph, not declared —
355
+ * `hooks-executor.ts` re-exports every name here, and `types/agent.ts` reads only the gate.
356
+ *
357
+ * A LEAF: it imports nothing, so anything may depend on it without closing a cycle. That is the
358
+ * whole reason it exists as its own file. The first version of #631 put
359
+ * `import("../internal/runtime/hooks/hooks-executor.js").HookApprovalGate` inline in
360
+ * `types/agent.ts`, which made the public contract depend on an internal module and produced
361
+ * thirteen failing cycle assertions — the exact defect `types/plugin.ts` documents at its own head
362
+ * ("the public contract sits above the DIP boundary").
363
+ *
364
+ * `HookEvent` is DECLARED here and re-exported by `internal/runtime/hooks/hooks-executor.ts`, so
365
+ * that pair has one definition. `internal/runtime/hooks/hooks-source.ts` still carries its own copy;
366
+ * consolidating that third one is the same class of problem as #586 and is deliberately not folded
367
+ * into this change.
368
+ *
369
+ * @public
370
+ */
371
+ /** The five lifecycle events the runtime actually fires. */
372
+ type HookEvent = "preRun" | "postRun" | "preToolUse" | "postToolUse" | "stop";
373
+ /**
374
+ * #631 — what the consumer is shown when asked to approve a hook.
375
+ *
376
+ * The command TEXT and the file it was declared in, because neither alone answers the question. A
377
+ * consumer's fingerprint is over the command; which file it came from is what separates its own
378
+ * configuration from a foreign dialect it merely imported, and those deserve different answers.
379
+ *
380
+ * @public
381
+ */
382
+ interface HookApprovalRequest {
383
+ readonly command: string;
384
+ readonly event: HookEvent;
385
+ readonly sourcePath?: string;
386
+ readonly matcher?: string;
387
+ }
388
+ /**
389
+ * #631 — a consumer's decision point before this package spawns a hook.
390
+ *
391
+ * Absent means run, which is what every consumer gets today: a gate that defaulted to refusing
392
+ * would disable every hook in the ecosystem on an upgrade.
393
+ *
394
+ * @public
395
+ */
396
+ interface HookApprovalGate {
397
+ readonly approve?: (request: HookApprovalRequest) => boolean | Promise<boolean>;
398
+ }
399
+
351
400
  /**
352
401
  * Owner: `internal/memory/storage/` (1 of 2 importers). Derived from the import graph, not
353
402
  * declared — `tests/lint/types-name-their-owner.test.ts` re-derives it.
@@ -971,7 +1020,7 @@ type SettingSource = "project" | "user" | "team" | "mdm" | "plugins" | "all";
971
1020
  *
972
1021
  * @public
973
1022
  */
974
- type CompatSource = "claude-code" | CompatSourceAdapter;
1023
+ type CompatSource = "claude-code" | "theokit" | CompatSourceAdapter;
975
1024
  /**
976
1025
  * A surface a foreign configuration source may be admitted to.
977
1026
  *
@@ -1001,7 +1050,17 @@ type CompatSurface = "hooks" | "plugins" | "skills" | "subagents";
1001
1050
  * @public
1002
1051
  */
1003
1052
  interface CompatSourceAdapter {
1004
- readonly kind: "claude-code";
1053
+ /**
1054
+ * `"theokit"` names THIS package's own root (#631), in the same vocabulary a foreign dialect
1055
+ * uses. Until it was accepted here, `.theokit/` contributed every surface unconditionally while a
1056
+ * foreign one could declare which surfaces it wanted — an asymmetry with a measured cost: a
1057
+ * consumer keeping its own configuration in `.theokit/settings.json` had that file's `hooks` key
1058
+ * executed by this package, and `settingSources` gave it no way to decline, because it grants per
1059
+ * SOURCE and not per surface.
1060
+ *
1061
+ * Declaring nothing keeps today's behaviour exactly: the native root contributes everything.
1062
+ */
1063
+ readonly kind: "claude-code" | "theokit";
1005
1064
  readonly import?: readonly CompatSurface[];
1006
1065
  }
1007
1066
  /**
@@ -1069,6 +1128,18 @@ interface LocalOptions {
1069
1128
  * wrote for this runtime.
1070
1129
  */
1071
1130
  compatSources?: CompatSource[];
1131
+ /**
1132
+ * #631 — the consumer's chance to refuse a hook command before this package spawns it.
1133
+ *
1134
+ * Absent means run, which is what every consumer gets today. It is consulted at the single point
1135
+ * a hook is executed, for every root — including a foreign dialect's, which is the case
1136
+ * {@link CompatSourceAdapter} cannot reach: a consumer that wants `.claude/`'s skills, agents and
1137
+ * rules cannot decline only its hooks, because `settingSources` grants per source.
1138
+ *
1139
+ * A refused hook resolves as if it were not configured. It does NOT deny the operation the hook
1140
+ * attached to — the consumer asked for the command not to run, not for the work to stop.
1141
+ */
1142
+ hooks?: HookApprovalGate;
1072
1143
  sandboxOptions?: {
1073
1144
  enabled: boolean;
1074
1145
  };
@@ -348,6 +348,55 @@ interface BudgetTracker {
348
348
  nextIteration?(): void;
349
349
  }
350
350
 
351
+ /**
352
+ * Hook contract types.
353
+ *
354
+ * Owner: `internal/runtime/hooks/` (2 of 3 importers). Derived from the import graph, not declared —
355
+ * `hooks-executor.ts` re-exports every name here, and `types/agent.ts` reads only the gate.
356
+ *
357
+ * A LEAF: it imports nothing, so anything may depend on it without closing a cycle. That is the
358
+ * whole reason it exists as its own file. The first version of #631 put
359
+ * `import("../internal/runtime/hooks/hooks-executor.js").HookApprovalGate` inline in
360
+ * `types/agent.ts`, which made the public contract depend on an internal module and produced
361
+ * thirteen failing cycle assertions — the exact defect `types/plugin.ts` documents at its own head
362
+ * ("the public contract sits above the DIP boundary").
363
+ *
364
+ * `HookEvent` is DECLARED here and re-exported by `internal/runtime/hooks/hooks-executor.ts`, so
365
+ * that pair has one definition. `internal/runtime/hooks/hooks-source.ts` still carries its own copy;
366
+ * consolidating that third one is the same class of problem as #586 and is deliberately not folded
367
+ * into this change.
368
+ *
369
+ * @public
370
+ */
371
+ /** The five lifecycle events the runtime actually fires. */
372
+ type HookEvent = "preRun" | "postRun" | "preToolUse" | "postToolUse" | "stop";
373
+ /**
374
+ * #631 — what the consumer is shown when asked to approve a hook.
375
+ *
376
+ * The command TEXT and the file it was declared in, because neither alone answers the question. A
377
+ * consumer's fingerprint is over the command; which file it came from is what separates its own
378
+ * configuration from a foreign dialect it merely imported, and those deserve different answers.
379
+ *
380
+ * @public
381
+ */
382
+ interface HookApprovalRequest {
383
+ readonly command: string;
384
+ readonly event: HookEvent;
385
+ readonly sourcePath?: string;
386
+ readonly matcher?: string;
387
+ }
388
+ /**
389
+ * #631 — a consumer's decision point before this package spawns a hook.
390
+ *
391
+ * Absent means run, which is what every consumer gets today: a gate that defaulted to refusing
392
+ * would disable every hook in the ecosystem on an upgrade.
393
+ *
394
+ * @public
395
+ */
396
+ interface HookApprovalGate {
397
+ readonly approve?: (request: HookApprovalRequest) => boolean | Promise<boolean>;
398
+ }
399
+
351
400
  /**
352
401
  * Owner: `internal/memory/storage/` (1 of 2 importers). Derived from the import graph, not
353
402
  * declared — `tests/lint/types-name-their-owner.test.ts` re-derives it.
@@ -971,7 +1020,7 @@ type SettingSource = "project" | "user" | "team" | "mdm" | "plugins" | "all";
971
1020
  *
972
1021
  * @public
973
1022
  */
974
- type CompatSource = "claude-code" | CompatSourceAdapter;
1023
+ type CompatSource = "claude-code" | "theokit" | CompatSourceAdapter;
975
1024
  /**
976
1025
  * A surface a foreign configuration source may be admitted to.
977
1026
  *
@@ -1001,7 +1050,17 @@ type CompatSurface = "hooks" | "plugins" | "skills" | "subagents";
1001
1050
  * @public
1002
1051
  */
1003
1052
  interface CompatSourceAdapter {
1004
- readonly kind: "claude-code";
1053
+ /**
1054
+ * `"theokit"` names THIS package's own root (#631), in the same vocabulary a foreign dialect
1055
+ * uses. Until it was accepted here, `.theokit/` contributed every surface unconditionally while a
1056
+ * foreign one could declare which surfaces it wanted — an asymmetry with a measured cost: a
1057
+ * consumer keeping its own configuration in `.theokit/settings.json` had that file's `hooks` key
1058
+ * executed by this package, and `settingSources` gave it no way to decline, because it grants per
1059
+ * SOURCE and not per surface.
1060
+ *
1061
+ * Declaring nothing keeps today's behaviour exactly: the native root contributes everything.
1062
+ */
1063
+ readonly kind: "claude-code" | "theokit";
1005
1064
  readonly import?: readonly CompatSurface[];
1006
1065
  }
1007
1066
  /**
@@ -1069,6 +1128,18 @@ interface LocalOptions {
1069
1128
  * wrote for this runtime.
1070
1129
  */
1071
1130
  compatSources?: CompatSource[];
1131
+ /**
1132
+ * #631 — the consumer's chance to refuse a hook command before this package spawns it.
1133
+ *
1134
+ * Absent means run, which is what every consumer gets today. It is consulted at the single point
1135
+ * a hook is executed, for every root — including a foreign dialect's, which is the case
1136
+ * {@link CompatSourceAdapter} cannot reach: a consumer that wants `.claude/`'s skills, agents and
1137
+ * rules cannot decline only its hooks, because `settingSources` grants per source.
1138
+ *
1139
+ * A refused hook resolves as if it were not configured. It does NOT deny the operation the hook
1140
+ * attached to — the consumer asked for the command not to run, not for the work to stop.
1141
+ */
1142
+ hooks?: HookApprovalGate;
1072
1143
  sandboxOptions?: {
1073
1144
  enabled: boolean;
1074
1145
  };
@@ -1,16 +1,16 @@
1
- export { Agent } from './chunk-363RBGIR.js';
1
+ export { Agent } from './chunk-IKBLU7ZS.js';
2
2
  import './chunk-K2VMFZQ5.js';
3
- import './chunk-AWINL3ZC.js';
3
+ import './chunk-2QKV4CGK.js';
4
4
  import './chunk-K2BQQ445.js';
5
5
  import './chunk-7SZAV6QG.js';
6
- import './chunk-7L3MIW2F.js';
6
+ import './chunk-XD3FS5OI.js';
7
7
  import './chunk-2SFBB54R.js';
8
8
  import './chunk-55GB6JYQ.js';
9
9
  import './chunk-H73MEMQB.js';
10
10
  import './chunk-OR6XIWLB.js';
11
11
  import './chunk-SADXXGWU.js';
12
12
  import './chunk-AAEZSPTC.js';
13
- import './chunk-K3NH62DG.js';
13
+ import './chunk-KZSKIUXZ.js';
14
14
  import './chunk-UBR5PWD7.js';
15
15
  import './chunk-2XC6KDJM.js';
16
16
  import './chunk-XB4GI5RZ.js';
@@ -41,8 +41,8 @@ import './chunk-TA3K7SBK.js';
41
41
  import './chunk-Q5EWJPRY.js';
42
42
  import './chunk-EIQFAOFD.js';
43
43
  import './chunk-3JHIFQ4I.js';
44
- import './chunk-DLFWMJE3.js';
45
- import './chunk-RP3VXJMA.js';
44
+ import './chunk-O7L7M42F.js';
45
+ import './chunk-NSLHPAC7.js';
46
46
  import './chunk-JNAA4G4H.js';
47
47
  import './chunk-6M2OIS4Y.js';
48
48
  import './chunk-R7WIIPUR.js';
@@ -54,5 +54,5 @@ import './chunk-V22DZIXO.js';
54
54
  import './chunk-NJWYQWDL.js';
55
55
  import './chunk-ALUN2B4W.js';
56
56
  import './chunk-CZJ6Q7CW.js';
57
- //# sourceMappingURL=agent-PNYJ5S2Y.js.map
58
- //# sourceMappingURL=agent-PNYJ5S2Y.js.map
57
+ //# sourceMappingURL=agent-MNINE73R.js.map
58
+ //# sourceMappingURL=agent-MNINE73R.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-PNYJ5S2Y.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-MNINE73R.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-W4WLJTHA.js');
49
+ const { autoCompactIfNeeded } = await import('./compact-session-YSEK7NQF.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-AWINL3ZC.js.map
109
- //# sourceMappingURL=chunk-AWINL3ZC.js.map
108
+ //# sourceMappingURL=chunk-2QKV4CGK.js.map
109
+ //# sourceMappingURL=chunk-2QKV4CGK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":[],"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,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,CA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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-AWINL3ZC.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 \"./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":[],"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,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,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AG,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;AAkBO,SAAS,aAAa,OAAA,EAAuB;AAClD,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAOO,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-2QKV4CGK.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 \"./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,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkDWB3CN46_cjs = require('./chunk-DWB3CN46.cjs');
3
+ var chunk43YXGD3P_cjs = require('./chunk-43YXGD3P.cjs');
4
4
  var chunkJ7J7J2GN_cjs = require('./chunk-J7J7J2GN.cjs');
5
5
  var chunk6LHQPOMI_cjs = require('./chunk-6LHQPOMI.cjs');
6
6
  var async_hooks = require('async_hooks');
@@ -29,7 +29,7 @@ async function loadHookConfig(cwd, compatSources = []) {
29
29
  sawAny = true;
30
30
  mergeInto(merged, stampSource(await readHookFile(path), path));
31
31
  }
32
- if (!sawAny && fs.existsSync(path.join(chunkDWB3CN46_cjs.theokitConfigRoot(cwd), "hooks"))) {
32
+ if (!sawAny && fs.existsSync(path.join(chunk43YXGD3P_cjs.theokitConfigRoot(cwd), "hooks"))) {
33
33
  warnOnce(
34
34
  "hooks-md-unsupported",
35
35
  "[theokit-sdk] .theokit/hooks/*.md hooks are no longer supported (ADR 0016) \u2014 migrate to a Claude-Code-shaped .theokit/hooks.json"
@@ -38,7 +38,7 @@ async function loadHookConfig(cwd, compatSources = []) {
38
38
  return merged;
39
39
  }
40
40
  function hookConfigCandidates(cwd, compatSources) {
41
- const roots = chunkDWB3CN46_cjs.projectConfigRoots(cwd, compatSources, "hooks");
41
+ const roots = chunk43YXGD3P_cjs.projectConfigRoots(cwd, compatSources, "hooks");
42
42
  return [
43
43
  ...roots.map((root) => path.join(root, "hooks.json")),
44
44
  ...roots.map((root) => path.join(root, "settings.json")),
@@ -170,5 +170,5 @@ exports.loadHookConfig = loadHookConfig;
170
170
  exports.warnOnce = warnOnce;
171
171
  exports.warnPersonalitySwitchInsideFork = warnPersonalitySwitchInsideFork;
172
172
  exports.withPersonalityContext = withPersonalityContext;
173
- //# sourceMappingURL=chunk-65UMH5V3.cjs.map
174
- //# sourceMappingURL=chunk-65UMH5V3.cjs.map
173
+ //# sourceMappingURL=chunk-3FDU5JFE.cjs.map
174
+ //# sourceMappingURL=chunk-3FDU5JFE.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/runtime/hooks/hooks-source.ts","../src/internal/personality/context.ts"],"names":["diag","existsSync","join","theokitConfigRoot","projectConfigRoots","readFile","ConfigurationError","AsyncLocalStorage"],"mappings":";;;;;;;;;;AAkCA,IAAM,qBAAA,GAA6D;AAAA,EACjE,UAAA,EAAY,YAAA;AAAA,EACZ,WAAA,EAAa,aAAA;AAAA,EACb,gBAAA,EAAkB,QAAA;AAAA,E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AAA,EAAA,CAAG,SAAA,GAAY,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,UAAU,GAAI,CAAA;AAAA,EAC9C;AACA,EAAA,OAAO,EAAA;AACT;;;AC/QA,IAAM,OAAA,GAAU,IAAIC,6BAAA,EAA0C;AAQvD,SAAS,sBAAA,CACd,KACA,EAAA,EACY;AACZ,EAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,EAAE,CAAA;AAC5B;AAQO,SAAS,yBAAA,GAAgE;AAC9E,EAAA,OAAO,QAAQ,QAAA,EAAS;AAC1B;AASO,SAAS,gCAAgC,OAAA,EAAuB;AACrE,EAAA,QAAA;AAAA,IACE,8BAA8B,OAAO,CAAA,CAAA;AAAA,IACrC,CAAA,0IAAA;AAAA,GACF;AACF","file":"chunk-65UMH5V3.cjs","sourcesContent":["/**\n * Single source of truth for loading the hooks config (ADR 0016 — reverses\n * D74/D77 for hooks: JSON is canonical again, in the Claude Code shape).\n *\n * `.theokit/hooks.json` (Claude-Code-shaped JSON) is the only supported form.\n * A stray legacy `.theokit/hooks/*.md` dir (no hooks.json) is NOT loaded — it\n * warns to migrate and yields no hooks. Absent both → empty config.\n *\n * Consumed by `hooks-executor.ts` (runtime dispatch).\n *\n * Config shape (identical to Claude Code's `settings.json` hooks):\n * { \"hooks\": { \"PreToolUse\": [ { \"matcher\": \"shell\",\n * \"hooks\": [ { \"type\": \"command\", \"command\": \"…\", \"timeout\": 30 } ] } ] } }\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { diag } from \"../../diagnostics.js\";\nimport { projectConfigRoots, theokitConfigRoot } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\n\n/** The five lifecycle events the SDK runtime actually fires. */\nexport type HookEvent = \"preRun\" | \"postRun\" | \"preToolUse\" | \"postToolUse\" | \"stop\";\n\n/**\n * Claude Code event name → the SDK firing event. Only events the runtime\n * genuinely emits are mapped; a Claude Code event with no SDK firing point\n * (SessionStart / SubagentStop / PreCompact / Notification / SessionEnd) is\n * skipped with a warn rather than silently accepted (it would never run).\n */\nconst CLAUDE_CODE_EVENT_MAP: Readonly<Record<string, HookEvent>> = {\n PreToolUse: \"preToolUse\",\n PostToolUse: \"postToolUse\",\n UserPromptSubmit: \"preRun\",\n Stop: \"stop\",\n};\n\nexport interface HookCommand {\n command: string;\n matcher?: string;\n timeoutMs?: number;\n /**\n * The config file this command was declared in.\n *\n * Carried so the executor can supply the runtime contract the declaring DIALECT presumes — a\n * command from `.claude/settings.json` is written against Claude Code's runtime and expects\n * `$CLAUDE_PROJECT_DIR` to exist (#522). Absent for a command built in memory, which is native by\n * construction.\n */\n sourcePath?: string;\n}\n\nexport interface HookConfig {\n hooks?: Partial<Record<HookEvent, HookCommand[]>>;\n}\n\nconst warned = new Set<string>();\n\n/**\n * Emit a stderr warn once per process per unique key. Helps surface the\n * deprecation path without spamming when the loader is called many times\n * during a session (cron + send + skills all hit this).\n *\n * Note: spawned workers (cron, subagent) start fresh processes — warn\n * re-emits there, by design (1 per process boot, not per call).\n *\n * @internal\n */\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n diag(`${message}\\n`);\n}\n\n/** Reset for tests; not exported via barrel. @internal */\nexport function _resetWarnOnceForTests(): void {\n warned.clear();\n}\n\n/**\n * Load hooks from `.theokit/hooks.json` (Claude-Code-shaped — the only supported\n * form). A stray legacy `.theokit/hooks/*.md` markdown dir (no `hooks.json`) is\n * NOT loaded — it emits a one-time migration warn and yields no hooks.\n *\n * @internal\n */\nexport async function loadHookConfig(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<HookConfig> {\n const merged: HookConfig = {};\n let sawAny = false;\n for (const path of hookConfigCandidates(cwd, compatSources)) {\n if (!existsSync(path)) continue;\n sawAny = true;\n // Stamped at merge, where the file is still known. One line later the commands are pooled per\n // event and every trace of which dialect declared them is gone — which is how a Claude Code\n // command came to be run without Claude Code's runtime (#522).\n mergeInto(merged, stampSource(await readHookFile(path), path));\n }\n if (!sawAny && existsSync(join(theokitConfigRoot(cwd), \"hooks\"))) {\n warnOnce(\n \"hooks-md-unsupported\",\n \"[theokit-sdk] .theokit/hooks/*.md hooks are no longer supported (ADR 0016) — migrate to a Claude-Code-shaped .theokit/hooks.json\",\n );\n }\n return merged;\n}\n\n/**\n * Every file that may declare hooks, in precedence order.\n *\n * `hooks.json` under each project config root, then the Claude Code CLI's own settings files — which\n * is where the CLI actually keeps hooks, so a repository set up for it presents its hooks here\n * without being converted. `settings.local.json` is the CLI's personal-override file and sits beside\n * the shared one rather than replacing it.\n *\n * The shape never needed translating: `parseClaudeCodeConfig` reads the `hooks` key off whatever\n * object it is given, and a settings file is that same object with other keys alongside.\n */\nfunction hookConfigCandidates(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[],\n): string[] {\n const roots = projectConfigRoots(cwd, compatSources, \"hooks\");\n return [\n ...roots.map((root) => join(root, \"hooks.json\")),\n ...roots.map((root) => join(root, \"settings.json\")),\n ...roots.map((root) => join(root, \"settings.local.json\")),\n ];\n}\n\n/**\n * Record which file each command came from.\n *\n * A command already carrying a `sourcePath` keeps it: nothing produces that today, and a nested\n * config that declared its own origin would be describing something this function cannot see.\n */\nfunction stampSource(config: HookConfig, sourcePath: string): HookConfig {\n if (config.hooks === undefined) return config;\n const hooks: NonNullable<HookConfig[\"hooks\"]> = {};\n for (const [event, commands] of Object.entries(config.hooks) as [\n HookEvent,\n HookCommand[] | undefined,\n ][]) {\n if (commands === undefined) continue;\n hooks[event] = commands.map((c) => ({ sourcePath, ...c }));\n }\n return { hooks };\n}\n\n/**\n * Append one source's commands onto the accumulator, per event.\n *\n * MERGED, not first-wins, and the distinction is deliberate. An agent or a skill is a NAMED\n * declaration: two files claiming one name collide, and the explicit namespace should win. Hooks are\n * unnamed lists — two files declaring `PreToolUse` are two sets of commands an operator wrote, and\n * keeping only one drops the other in silence, which is the failure class this package guards\n * against everywhere else.\n */\nfunction mergeInto(target: HookConfig, source: HookConfig): void {\n for (const [event, commands] of Object.entries(source.hooks ?? {}) as [\n HookEvent,\n HookCommand[] | undefined,\n ][]) {\n if (commands === undefined || commands.length === 0) continue;\n target.hooks ??= {};\n target.hooks[event] = [...(target.hooks[event] ?? []), ...commands];\n }\n}\n\nasync function readHookFile(jsonPath: string): Promise<HookConfig> {\n let raw: string;\n try {\n raw = await readFile(jsonPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {\n code: \"hooks_read_error\",\n cause,\n });\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {\n code: \"hooks_json_invalid\",\n cause,\n });\n }\n return parseClaudeCodeConfig(parsed, jsonPath);\n}\n\n/**\n * Narrow an unknown to a record, or throw a typed config error.\n *\n * `hint` names the shape that WOULD be accepted, and exists because the message without it names\n * only the validator's expectation. Measured on a consumer in 2026-09: a flat `hooks` array in a\n * `.theokit/settings.json` made this throw on every turn, and `expected an object at \"hooks\"` gave\n * the operator nothing to act on — the file parses fine for the product that wrote it, and it is\n * this independent read of the same path that fails. An error on a refusal path should carry the\n * fix, not the diagnosis.\n */\nfunction asRecord(\n value: unknown,\n path: string,\n where: string,\n hint?: string,\n): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigurationError(\n `hooks: expected an object at ${where} in ${path}${hint === undefined ? \"\" : ` — ${hint}`}`,\n { code: \"hooks_json_invalid\" },\n );\n }\n return value as Record<string, unknown>;\n}\n\n/**\n * The shape this loader accepts, quoted back on the one refusal an operator is most likely to hit:\n * `hooks` keyed by event, each event an array of matcher groups.\n */\nconst HOOKS_SHAPE_HINT =\n 'hooks are keyed by event, e.g. { \"hooks\": { \"PreToolUse\": [ { \"hooks\": ' +\n '[ { \"type\": \"command\", \"command\": \"…\" } ] } ] } }';\n\n/** Narrow an unknown to an array, or throw a typed config error. */\nfunction asArray(value: unknown, path: string, where: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value;\n}\n\n/**\n * Parse Claude Code's nested hooks config into the SDK's flat internal shape:\n * `{ hooks: { PreToolUse: [{ matcher?, hooks: [{ type:\"command\", command, timeout? }] }] } }`\n * → `{ hooks: { preToolUse: [{ command, matcher?, timeoutMs? }] } }`. Each group's\n * `matcher` applies to every command it wraps; `timeout` (seconds) → `timeoutMs`.\n */\nfunction parseClaudeCodeConfig(raw: unknown, path: string): HookConfig {\n const root = asRecord(raw, path, \"the root\");\n if (root.hooks === undefined) return {};\n const hooksRec = asRecord(root.hooks, path, `\"hooks\"`, HOOKS_SHAPE_HINT);\n const grouped: Partial<Record<HookEvent, HookCommand[]>> = {};\n\n for (const [ccEvent, groups] of Object.entries(hooksRec)) {\n const event = CLAUDE_CODE_EVENT_MAP[ccEvent];\n if (event === undefined) {\n warnOnce(\n `hooks-event-${ccEvent}`,\n `[theokit-sdk] hooks: event \"${ccEvent}\" is not fired by the SDK runtime (supported: ${Object.keys(CLAUDE_CODE_EVENT_MAP).join(\", \")}) — skipping`,\n );\n continue;\n }\n grouped[event] = [...(grouped[event] ?? []), ...flattenEventGroups(groups, path, ccEvent)];\n }\n return { hooks: grouped };\n}\n\n/** Flatten one Claude Code event's matcher-groups into internal HookCommands. */\nfunction flattenEventGroups(groups: unknown, path: string, ccEvent: string): HookCommand[] {\n const commands: HookCommand[] = [];\n for (const rawGroup of asArray(groups, path, `hooks.${ccEvent}`)) {\n const group = asRecord(rawGroup, path, `hooks.${ccEvent}[]`);\n const matcher = group.matcher === undefined ? undefined : String(group.matcher);\n for (const rawCmd of asArray(group.hooks, path, `hooks.${ccEvent}[].hooks`)) {\n commands.push(parseClaudeCodeCommand(rawCmd, matcher, path, ccEvent));\n }\n }\n return commands;\n}\n\n/** One `{ type:\"command\", command, timeout? }` entry → an internal HookCommand. */\nfunction parseClaudeCodeCommand(\n raw: unknown,\n matcher: string | undefined,\n path: string,\n ccEvent: string,\n): HookCommand {\n const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);\n if (cmd.type !== \"command\") {\n throw new ConfigurationError(\n `hooks: only { \"type\": \"command\" } is supported (got ${JSON.stringify(cmd.type)}) in ${path}`,\n { code: \"hooks_unsupported_type\" },\n );\n }\n if (typeof cmd.command !== \"string\" || cmd.command.length === 0) {\n throw new ConfigurationError(`hooks: \"command\" must be a non-empty string in ${path}`, {\n code: \"hooks_invalid_command\",\n });\n }\n const hc: HookCommand = { command: cmd.command };\n if (matcher !== undefined) hc.matcher = matcher;\n if (typeof cmd.timeout === \"number\" && cmd.timeout > 0) {\n hc.timeoutMs = Math.round(cmd.timeout * 1000);\n }\n return hc;\n}\n","/**\n * Personality fork-context (ADR D168 + EC-A snapshot semantic).\n *\n * Uses Node's `AsyncLocalStorage` so a fork's execution chain can know\n * that it is running inside a fork AND can see the slug that was active\n * on the parent **at fork-construction time**.\n *\n * **EC-A:** The slug stored here is captured ONCE at the wrap site\n * (`localAgentFork`) — passing `parentStore.active(parentAgentId)`\n * returns a primitive `string | undefined`, which is then frozen\n * inside the ALS context object. Subsequent `usePersonality` calls on\n * the parent do NOT mutate the fork's view, because the fork reads from\n * its own ALS frame, not from the parent's store.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\n\n/**\n * Snapshot data carried into a fork's async context.\n *\n * @internal\n */\nexport interface PersonalityForkContext {\n /** Parent's active personality slug at fork-construction time. */\n readonly slug: string | undefined;\n /** Always `true` inside this scope (used by guards). */\n readonly isFork: true;\n}\n\nconst storage = new AsyncLocalStorage<PersonalityForkContext>();\n\n/**\n * Run `fn` with `ctx` bound as the active fork context. Nested calls\n * shadow the outer context (EC-22).\n *\n * @internal\n */\nexport function withPersonalityContext<T>(\n ctx: PersonalityForkContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return storage.run(ctx, fn);\n}\n\n/**\n * Return the active fork context, or `undefined` when called outside a\n * fork scope.\n *\n * @internal\n */\nexport function currentPersonalityContext(): PersonalityForkContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Emit one warning per agentId stating that personality switches inside\n * a fork are no-ops. The fork inherits the parent snapshot — runtime\n * mutation is intentionally rejected to keep fork voice deterministic.\n *\n * @internal\n */\nexport function warnPersonalitySwitchInsideFork(agentId: string): void {\n warnOnce(\n `personality-switch-in-fork-${agentId}`,\n `[theokit-sdk] usePersonality is a no-op inside a fork (D168). Subagents inherit the parent's active personality at fork-construction time.`,\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/runtime/hooks/hooks-source.ts","../src/internal/personality/context.ts"],"names":["diag","existsSync","join","theokitConfigRoot","projectConfigRoots","readFile","ConfigurationError","AsyncLocalStorage"],"mappings":";;;;;;;;;;AAkCA,IAAM,qBAAA,GAA6D;AAAA,EACjE,UAAA,EAAY,YAAA;AAAA,EACZ,WAAA,EAAa,aAAA;AAAA,EACb,gBAAA,EAAkB,QAAA;AAAA,EAClB,IAAA,EAAM;AACR,CAAA;AAqBA,IAAM,MAAA,uBAAa,GAAA,EAAY;AAYxB,SAAS,QAAA,CAAS,KAAa,OAAA,EAAuB;AAC3D,EAAA,IAAI,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA,EAAG;AACrB,EAAA,MAAA,CAAO,IAAI,GAAG,CAAA;AACd,EAAAA,sBAAA,CAAK,GAAG,OAAO;AAAA,CAAI,CAAA;AACrB;AAcA,eAAsB,cAAA,CACpB,GAAA,EACA,aAAA,GAAoD,EAAC,EAChC;AACrB,EAAA,MAAM,SAAqB,EAAC;AAC5B,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,MAAW,IAAA,IAAQ,o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CAAA;AAAA,IACrC,CAAA,0IAAA;AAAA,GACF;AACF","file":"chunk-3FDU5JFE.cjs","sourcesContent":["/**\n * Single source of truth for loading the hooks config (ADR 0016 — reverses\n * D74/D77 for hooks: JSON is canonical again, in the Claude Code shape).\n *\n * `.theokit/hooks.json` (Claude-Code-shaped JSON) is the only supported form.\n * A stray legacy `.theokit/hooks/*.md` dir (no hooks.json) is NOT loaded — it\n * warns to migrate and yields no hooks. Absent both → empty config.\n *\n * Consumed by `hooks-executor.ts` (runtime dispatch).\n *\n * Config shape (identical to Claude Code's `settings.json` hooks):\n * { \"hooks\": { \"PreToolUse\": [ { \"matcher\": \"shell\",\n * \"hooks\": [ { \"type\": \"command\", \"command\": \"…\", \"timeout\": 30 } ] } ] } }\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { diag } from \"../../diagnostics.js\";\nimport { projectConfigRoots, theokitConfigRoot } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\n\n/** The five lifecycle events the SDK runtime actually fires. */\nexport type HookEvent = \"preRun\" | \"postRun\" | \"preToolUse\" | \"postToolUse\" | \"stop\";\n\n/**\n * Claude Code event name → the SDK firing event. Only events the runtime\n * genuinely emits are mapped; a Claude Code event with no SDK firing point\n * (SessionStart / SubagentStop / PreCompact / Notification / SessionEnd) is\n * skipped with a warn rather than silently accepted (it would never run).\n */\nconst CLAUDE_CODE_EVENT_MAP: Readonly<Record<string, HookEvent>> = {\n PreToolUse: \"preToolUse\",\n PostToolUse: \"postToolUse\",\n UserPromptSubmit: \"preRun\",\n Stop: \"stop\",\n};\n\nexport interface HookCommand {\n command: string;\n matcher?: string;\n timeoutMs?: number;\n /**\n * The config file this command was declared in.\n *\n * Carried so the executor can supply the runtime contract the declaring DIALECT presumes — a\n * command from `.claude/settings.json` is written against Claude Code's runtime and expects\n * `$CLAUDE_PROJECT_DIR` to exist (#522). Absent for a command built in memory, which is native by\n * construction.\n */\n sourcePath?: string;\n}\n\nexport interface HookConfig {\n hooks?: Partial<Record<HookEvent, HookCommand[]>>;\n}\n\nconst warned = new Set<string>();\n\n/**\n * Emit a stderr warn once per process per unique key. Helps surface the\n * deprecation path without spamming when the loader is called many times\n * during a session (cron + send + skills all hit this).\n *\n * Note: spawned workers (cron, subagent) start fresh processes — warn\n * re-emits there, by design (1 per process boot, not per call).\n *\n * @internal\n */\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n diag(`${message}\\n`);\n}\n\n/** Reset for tests; not exported via barrel. @internal */\nexport function _resetWarnOnceForTests(): void {\n warned.clear();\n}\n\n/**\n * Load hooks from `.theokit/hooks.json` (Claude-Code-shaped — the only supported\n * form). A stray legacy `.theokit/hooks/*.md` markdown dir (no `hooks.json`) is\n * NOT loaded — it emits a one-time migration warn and yields no hooks.\n *\n * @internal\n */\nexport async function loadHookConfig(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<HookConfig> {\n const merged: HookConfig = {};\n let sawAny = false;\n for (const path of hookConfigCandidates(cwd, compatSources)) {\n if (!existsSync(path)) continue;\n sawAny = true;\n // Stamped at merge, where the file is still known. One line later the commands are pooled per\n // event and every trace of which dialect declared them is gone — which is how a Claude Code\n // command came to be run without Claude Code's runtime (#522).\n mergeInto(merged, stampSource(await readHookFile(path), path));\n }\n if (!sawAny && existsSync(join(theokitConfigRoot(cwd), \"hooks\"))) {\n warnOnce(\n \"hooks-md-unsupported\",\n \"[theokit-sdk] .theokit/hooks/*.md hooks are no longer supported (ADR 0016) — migrate to a Claude-Code-shaped .theokit/hooks.json\",\n );\n }\n return merged;\n}\n\n/**\n * Every file that may declare hooks, in precedence order.\n *\n * `hooks.json` under each project config root, then the Claude Code CLI's own settings files — which\n * is where the CLI actually keeps hooks, so a repository set up for it presents its hooks here\n * without being converted. `settings.local.json` is the CLI's personal-override file and sits beside\n * the shared one rather than replacing it.\n *\n * The shape never needed translating: `parseClaudeCodeConfig` reads the `hooks` key off whatever\n * object it is given, and a settings file is that same object with other keys alongside.\n */\nfunction hookConfigCandidates(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[],\n): string[] {\n const roots = projectConfigRoots(cwd, compatSources, \"hooks\");\n return [\n ...roots.map((root) => join(root, \"hooks.json\")),\n ...roots.map((root) => join(root, \"settings.json\")),\n ...roots.map((root) => join(root, \"settings.local.json\")),\n ];\n}\n\n/**\n * Record which file each command came from.\n *\n * A command already carrying a `sourcePath` keeps it: nothing produces that today, and a nested\n * config that declared its own origin would be describing something this function cannot see.\n */\nfunction stampSource(config: HookConfig, sourcePath: string): HookConfig {\n if (config.hooks === undefined) return config;\n const hooks: NonNullable<HookConfig[\"hooks\"]> = {};\n for (const [event, commands] of Object.entries(config.hooks) as [\n HookEvent,\n HookCommand[] | undefined,\n ][]) {\n if (commands === undefined) continue;\n hooks[event] = commands.map((c) => ({ sourcePath, ...c }));\n }\n return { hooks };\n}\n\n/**\n * Append one source's commands onto the accumulator, per event.\n *\n * MERGED, not first-wins, and the distinction is deliberate. An agent or a skill is a NAMED\n * declaration: two files claiming one name collide, and the explicit namespace should win. Hooks are\n * unnamed lists — two files declaring `PreToolUse` are two sets of commands an operator wrote, and\n * keeping only one drops the other in silence, which is the failure class this package guards\n * against everywhere else.\n */\nfunction mergeInto(target: HookConfig, source: HookConfig): void {\n for (const [event, commands] of Object.entries(source.hooks ?? {}) as [\n HookEvent,\n HookCommand[] | undefined,\n ][]) {\n if (commands === undefined || commands.length === 0) continue;\n target.hooks ??= {};\n target.hooks[event] = [...(target.hooks[event] ?? []), ...commands];\n }\n}\n\nasync function readHookFile(jsonPath: string): Promise<HookConfig> {\n let raw: string;\n try {\n raw = await readFile(jsonPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {\n code: \"hooks_read_error\",\n cause,\n });\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {\n code: \"hooks_json_invalid\",\n cause,\n });\n }\n return parseClaudeCodeConfig(parsed, jsonPath);\n}\n\n/**\n * Narrow an unknown to a record, or throw a typed config error.\n *\n * `hint` names the shape that WOULD be accepted, and exists because the message without it names\n * only the validator's expectation. Measured on a consumer in 2026-09: a flat `hooks` array in a\n * `.theokit/settings.json` made this throw on every turn, and `expected an object at \"hooks\"` gave\n * the operator nothing to act on — the file parses fine for the product that wrote it, and it is\n * this independent read of the same path that fails. An error on a refusal path should carry the\n * fix, not the diagnosis.\n */\nfunction asRecord(\n value: unknown,\n path: string,\n where: string,\n hint?: string,\n): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigurationError(\n `hooks: expected an object at ${where} in ${path}${hint === undefined ? \"\" : ` — ${hint}`}`,\n { code: \"hooks_json_invalid\" },\n );\n }\n return value as Record<string, unknown>;\n}\n\n/**\n * The shape this loader accepts, quoted back on the one refusal an operator is most likely to hit:\n * `hooks` keyed by event, each event an array of matcher groups.\n */\nconst HOOKS_SHAPE_HINT =\n 'hooks are keyed by event, e.g. { \"hooks\": { \"PreToolUse\": [ { \"hooks\": ' +\n '[ { \"type\": \"command\", \"command\": \"…\" } ] } ] } }';\n\n/** Narrow an unknown to an array, or throw a typed config error. */\nfunction asArray(value: unknown, path: string, where: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value;\n}\n\n/**\n * Parse Claude Code's nested hooks config into the SDK's flat internal shape:\n * `{ hooks: { PreToolUse: [{ matcher?, hooks: [{ type:\"command\", command, timeout? }] }] } }`\n * → `{ hooks: { preToolUse: [{ command, matcher?, timeoutMs? }] } }`. Each group's\n * `matcher` applies to every command it wraps; `timeout` (seconds) → `timeoutMs`.\n */\nfunction parseClaudeCodeConfig(raw: unknown, path: string): HookConfig {\n const root = asRecord(raw, path, \"the root\");\n if (root.hooks === undefined) return {};\n const hooksRec = asRecord(root.hooks, path, `\"hooks\"`, HOOKS_SHAPE_HINT);\n const grouped: Partial<Record<HookEvent, HookCommand[]>> = {};\n\n for (const [ccEvent, groups] of Object.entries(hooksRec)) {\n const event = CLAUDE_CODE_EVENT_MAP[ccEvent];\n if (event === undefined) {\n warnOnce(\n `hooks-event-${ccEvent}`,\n `[theokit-sdk] hooks: event \"${ccEvent}\" is not fired by the SDK runtime (supported: ${Object.keys(CLAUDE_CODE_EVENT_MAP).join(\", \")}) — skipping`,\n );\n continue;\n }\n grouped[event] = [...(grouped[event] ?? []), ...flattenEventGroups(groups, path, ccEvent)];\n }\n return { hooks: grouped };\n}\n\n/** Flatten one Claude Code event's matcher-groups into internal HookCommands. */\nfunction flattenEventGroups(groups: unknown, path: string, ccEvent: string): HookCommand[] {\n const commands: HookCommand[] = [];\n for (const rawGroup of asArray(groups, path, `hooks.${ccEvent}`)) {\n const group = asRecord(rawGroup, path, `hooks.${ccEvent}[]`);\n const matcher = group.matcher === undefined ? undefined : String(group.matcher);\n for (const rawCmd of asArray(group.hooks, path, `hooks.${ccEvent}[].hooks`)) {\n commands.push(parseClaudeCodeCommand(rawCmd, matcher, path, ccEvent));\n }\n }\n return commands;\n}\n\n/** One `{ type:\"command\", command, timeout? }` entry → an internal HookCommand. */\nfunction parseClaudeCodeCommand(\n raw: unknown,\n matcher: string | undefined,\n path: string,\n ccEvent: string,\n): HookCommand {\n const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);\n if (cmd.type !== \"command\") {\n throw new ConfigurationError(\n `hooks: only { \"type\": \"command\" } is supported (got ${JSON.stringify(cmd.type)}) in ${path}`,\n { code: \"hooks_unsupported_type\" },\n );\n }\n if (typeof cmd.command !== \"string\" || cmd.command.length === 0) {\n throw new ConfigurationError(`hooks: \"command\" must be a non-empty string in ${path}`, {\n code: \"hooks_invalid_command\",\n });\n }\n const hc: HookCommand = { command: cmd.command };\n if (matcher !== undefined) hc.matcher = matcher;\n if (typeof cmd.timeout === \"number\" && cmd.timeout > 0) {\n hc.timeoutMs = Math.round(cmd.timeout * 1000);\n }\n return hc;\n}\n","/**\n * Personality fork-context (ADR D168 + EC-A snapshot semantic).\n *\n * Uses Node's `AsyncLocalStorage` so a fork's execution chain can know\n * that it is running inside a fork AND can see the slug that was active\n * on the parent **at fork-construction time**.\n *\n * **EC-A:** The slug stored here is captured ONCE at the wrap site\n * (`localAgentFork`) — passing `parentStore.active(parentAgentId)`\n * returns a primitive `string | undefined`, which is then frozen\n * inside the ALS context object. Subsequent `usePersonality` calls on\n * the parent do NOT mutate the fork's view, because the fork reads from\n * its own ALS frame, not from the parent's store.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\n\n/**\n * Snapshot data carried into a fork's async context.\n *\n * @internal\n */\nexport interface PersonalityForkContext {\n /** Parent's active personality slug at fork-construction time. */\n readonly slug: string | undefined;\n /** Always `true` inside this scope (used by guards). */\n readonly isFork: true;\n}\n\nconst storage = new AsyncLocalStorage<PersonalityForkContext>();\n\n/**\n * Run `fn` with `ctx` bound as the active fork context. Nested calls\n * shadow the outer context (EC-22).\n *\n * @internal\n */\nexport function withPersonalityContext<T>(\n ctx: PersonalityForkContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return storage.run(ctx, fn);\n}\n\n/**\n * Return the active fork context, or `undefined` when called outside a\n * fork scope.\n *\n * @internal\n */\nexport function currentPersonalityContext(): PersonalityForkContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Emit one warning per agentId stating that personality switches inside\n * a fork are no-ops. The fork inherits the parent snapshot — runtime\n * mutation is intentionally rejected to keep fork voice deterministic.\n *\n * @internal\n */\nexport function warnPersonalitySwitchInsideFork(agentId: string): void {\n warnOnce(\n `personality-switch-in-fork-${agentId}`,\n `[theokit-sdk] usePersonality is a no-op inside a fork (D168). Subagents inherit the parent's active personality at fork-construction time.`,\n );\n}\n"]}