@namzu/sdk 72.0.0 → 73.0.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 (228) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/agents/examples/SupervisorAgent.d.ts.map +1 -1
  3. package/dist/agents/examples/SupervisorAgent.js +5 -0
  4. package/dist/agents/examples/SupervisorAgent.js.map +1 -1
  5. package/dist/authorization/protected-paths.d.ts.map +1 -1
  6. package/dist/authorization/protected-paths.js +4 -0
  7. package/dist/authorization/protected-paths.js.map +1 -1
  8. package/dist/compaction/manual.d.ts +16 -1
  9. package/dist/compaction/manual.d.ts.map +1 -1
  10. package/dist/compaction/manual.js +63 -8
  11. package/dist/compaction/manual.js.map +1 -1
  12. package/dist/compaction/precompute.d.ts +179 -0
  13. package/dist/compaction/precompute.d.ts.map +1 -0
  14. package/dist/compaction/precompute.js +274 -0
  15. package/dist/compaction/precompute.js.map +1 -0
  16. package/dist/config/runtime.d.ts +4 -0
  17. package/dist/config/runtime.d.ts.map +1 -1
  18. package/dist/config/runtime.js +17 -0
  19. package/dist/config/runtime.js.map +1 -1
  20. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  21. package/dist/manager/agent/lifecycle.js +8 -0
  22. package/dist/manager/agent/lifecycle.js.map +1 -1
  23. package/dist/manager/session/turn-recorder.d.ts +26 -0
  24. package/dist/manager/session/turn-recorder.d.ts.map +1 -1
  25. package/dist/manager/session/turn-recorder.js +72 -5
  26. package/dist/manager/session/turn-recorder.js.map +1 -1
  27. package/dist/peers/protocol.d.ts +9 -0
  28. package/dist/peers/protocol.d.ts.map +1 -1
  29. package/dist/peers/protocol.js +4 -0
  30. package/dist/peers/protocol.js.map +1 -1
  31. package/dist/peers/record.d.ts +6 -0
  32. package/dist/peers/record.d.ts.map +1 -1
  33. package/dist/peers/record.js +4 -0
  34. package/dist/peers/record.js.map +1 -1
  35. package/dist/plugin/index.d.ts +2 -2
  36. package/dist/plugin/index.d.ts.map +1 -1
  37. package/dist/plugin/index.js +1 -1
  38. package/dist/plugin/index.js.map +1 -1
  39. package/dist/plugin/shell-hook.d.ts +30 -0
  40. package/dist/plugin/shell-hook.d.ts.map +1 -1
  41. package/dist/plugin/shell-hook.js +35 -0
  42. package/dist/plugin/shell-hook.js.map +1 -1
  43. package/dist/public-runtime.d.ts +5 -3
  44. package/dist/public-runtime.d.ts.map +1 -1
  45. package/dist/public-runtime.js +5 -3
  46. package/dist/public-runtime.js.map +1 -1
  47. package/dist/public-tools.d.ts +1 -1
  48. package/dist/public-tools.d.ts.map +1 -1
  49. package/dist/public-tools.js +1 -1
  50. package/dist/public-tools.js.map +1 -1
  51. package/dist/public-types.d.ts +3 -2
  52. package/dist/public-types.d.ts.map +1 -1
  53. package/dist/registry/command/kernel-commands.d.ts +7 -1
  54. package/dist/registry/command/kernel-commands.d.ts.map +1 -1
  55. package/dist/registry/command/kernel-commands.js +40 -2
  56. package/dist/registry/command/kernel-commands.js.map +1 -1
  57. package/dist/registry/tool/execute.d.ts +8 -0
  58. package/dist/registry/tool/execute.d.ts.map +1 -1
  59. package/dist/registry/tool/execute.js +12 -0
  60. package/dist/registry/tool/execute.js.map +1 -1
  61. package/dist/runtime/query/budget-nudge.d.ts +27 -0
  62. package/dist/runtime/query/budget-nudge.d.ts.map +1 -0
  63. package/dist/runtime/query/budget-nudge.js +66 -0
  64. package/dist/runtime/query/budget-nudge.js.map +1 -0
  65. package/dist/runtime/query/compact-session.d.ts +9 -0
  66. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  67. package/dist/runtime/query/compact-session.js +157 -80
  68. package/dist/runtime/query/compact-session.js.map +1 -1
  69. package/dist/runtime/query/guard.d.ts +8 -0
  70. package/dist/runtime/query/guard.d.ts.map +1 -1
  71. package/dist/runtime/query/guard.js +20 -0
  72. package/dist/runtime/query/guard.js.map +1 -1
  73. package/dist/runtime/query/iteration/index.d.ts +2 -0
  74. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  75. package/dist/runtime/query/iteration/index.js +27 -1
  76. package/dist/runtime/query/iteration/index.js.map +1 -1
  77. package/dist/runtime/query/iteration/phases/compaction.d.ts +1 -0
  78. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  79. package/dist/runtime/query/iteration/phases/compaction.js +143 -40
  80. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  81. package/dist/runtime/query/iteration/phases/precompute.d.ts +60 -0
  82. package/dist/runtime/query/iteration/phases/precompute.d.ts.map +1 -0
  83. package/dist/runtime/query/iteration/phases/precompute.js +240 -0
  84. package/dist/runtime/query/iteration/phases/precompute.js.map +1 -0
  85. package/dist/runtime/query/turn/outcome-ledger.d.ts +14 -0
  86. package/dist/runtime/query/turn/outcome-ledger.d.ts.map +1 -1
  87. package/dist/runtime/query/turn/outcome-ledger.js +28 -0
  88. package/dist/runtime/query/turn/outcome-ledger.js.map +1 -1
  89. package/dist/store/goal/gates.d.ts +53 -0
  90. package/dist/store/goal/gates.d.ts.map +1 -0
  91. package/dist/store/goal/gates.js +664 -0
  92. package/dist/store/goal/gates.js.map +1 -0
  93. package/dist/store/goal/index.d.ts +16 -1
  94. package/dist/store/goal/index.d.ts.map +1 -1
  95. package/dist/store/goal/index.js +74 -0
  96. package/dist/store/goal/index.js.map +1 -1
  97. package/dist/tools/builtins/bash.js +1 -1
  98. package/dist/tools/builtins/bash.js.map +1 -1
  99. package/dist/tools/builtins/browser.d.ts.map +1 -1
  100. package/dist/tools/builtins/browser.js +2 -0
  101. package/dist/tools/builtins/browser.js.map +1 -1
  102. package/dist/tools/builtins/monitor.d.ts.map +1 -1
  103. package/dist/tools/builtins/monitor.js +1 -0
  104. package/dist/tools/builtins/monitor.js.map +1 -1
  105. package/dist/tools/builtins/search-tools.js +2 -2
  106. package/dist/tools/builtins/search-tools.js.map +1 -1
  107. package/dist/tools/builtins/sleep-guard.js +1 -1
  108. package/dist/tools/builtins/sleep-guard.js.map +1 -1
  109. package/dist/tools/builtins/wait-for-job.js +1 -1
  110. package/dist/tools/builtins/wait-for-job.js.map +1 -1
  111. package/dist/tools/coordinator/ask-user-question.d.ts.map +1 -1
  112. package/dist/tools/coordinator/ask-user-question.js +25 -0
  113. package/dist/tools/coordinator/ask-user-question.js.map +1 -1
  114. package/dist/tools/coordinator/index.d.ts.map +1 -1
  115. package/dist/tools/coordinator/index.js +3 -0
  116. package/dist/tools/coordinator/index.js.map +1 -1
  117. package/dist/tools/defineTool.d.ts +2 -0
  118. package/dist/tools/defineTool.d.ts.map +1 -1
  119. package/dist/tools/defineTool.js +3 -0
  120. package/dist/tools/defineTool.js.map +1 -1
  121. package/dist/tools/goal/confirmation.d.ts +40 -2
  122. package/dist/tools/goal/confirmation.d.ts.map +1 -1
  123. package/dist/tools/goal/confirmation.js +117 -0
  124. package/dist/tools/goal/confirmation.js.map +1 -1
  125. package/dist/tools/goal/index.d.ts.map +1 -1
  126. package/dist/tools/goal/index.js +14 -2
  127. package/dist/tools/goal/index.js.map +1 -1
  128. package/dist/tools/memory/save.d.ts.map +1 -1
  129. package/dist/tools/memory/save.js +1 -0
  130. package/dist/tools/memory/save.js.map +1 -1
  131. package/dist/tools/schedules/index.d.ts +1 -0
  132. package/dist/tools/schedules/index.d.ts.map +1 -1
  133. package/dist/tools/schedules/index.js +1 -0
  134. package/dist/tools/schedules/index.js.map +1 -1
  135. package/dist/tools/schedules/loop-tool.d.ts.map +1 -1
  136. package/dist/tools/schedules/loop-tool.js +1 -0
  137. package/dist/tools/schedules/loop-tool.js.map +1 -1
  138. package/dist/tools/schedules/present.d.ts.map +1 -1
  139. package/dist/tools/schedules/present.js +2 -0
  140. package/dist/tools/schedules/present.js.map +1 -1
  141. package/dist/tools/schedules/schedule-tool.d.ts.map +1 -1
  142. package/dist/tools/schedules/schedule-tool.js +79 -9
  143. package/dist/tools/schedules/schedule-tool.js.map +1 -1
  144. package/dist/tools/schedules/self-tool.d.ts +16 -0
  145. package/dist/tools/schedules/self-tool.d.ts.map +1 -0
  146. package/dist/tools/schedules/self-tool.js +140 -0
  147. package/dist/tools/schedules/self-tool.js.map +1 -0
  148. package/dist/tools/schedules/timer-tools.d.ts.map +1 -1
  149. package/dist/tools/schedules/timer-tools.js +1 -0
  150. package/dist/tools/schedules/timer-tools.js.map +1 -1
  151. package/dist/tools/schedules/types.d.ts +63 -0
  152. package/dist/tools/schedules/types.d.ts.map +1 -1
  153. package/dist/toolsets/manager.d.ts +10 -0
  154. package/dist/toolsets/manager.d.ts.map +1 -1
  155. package/dist/toolsets/manager.js +56 -7
  156. package/dist/toolsets/manager.js.map +1 -1
  157. package/dist/types/agent/supervisor.d.ts +10 -0
  158. package/dist/types/agent/supervisor.d.ts.map +1 -1
  159. package/dist/types/agent/task.d.ts +6 -0
  160. package/dist/types/agent/task.d.ts.map +1 -1
  161. package/dist/types/goal/index.d.ts +66 -0
  162. package/dist/types/goal/index.d.ts.map +1 -1
  163. package/dist/types/session/events.d.ts +7 -0
  164. package/dist/types/session/events.d.ts.map +1 -1
  165. package/dist/types/session/events.js.map +1 -1
  166. package/dist/types/session/outcome.d.ts +12 -0
  167. package/dist/types/session/outcome.d.ts.map +1 -1
  168. package/dist/types/session/outcome.js.map +1 -1
  169. package/dist/types/session/records.d.ts +79 -1
  170. package/dist/types/session/records.d.ts.map +1 -1
  171. package/dist/types/session/records.js +24 -0
  172. package/dist/types/session/records.js.map +1 -1
  173. package/dist/types/tool/index.d.ts +7 -0
  174. package/dist/types/tool/index.d.ts.map +1 -1
  175. package/dist/types/tool/index.js.map +1 -1
  176. package/package.json +1 -1
  177. package/src/agents/examples/SupervisorAgent.ts +5 -0
  178. package/src/authorization/protected-paths.ts +4 -0
  179. package/src/compaction/manual.ts +83 -12
  180. package/src/compaction/precompute.ts +390 -0
  181. package/src/config/runtime.ts +17 -0
  182. package/src/manager/agent/lifecycle.ts +9 -0
  183. package/src/manager/session/turn-recorder.ts +92 -5
  184. package/src/peers/protocol.ts +4 -0
  185. package/src/peers/record.ts +4 -0
  186. package/src/plugin/index.ts +2 -0
  187. package/src/plugin/shell-hook.ts +60 -0
  188. package/src/public-runtime.ts +27 -0
  189. package/src/public-tools.ts +2 -0
  190. package/src/public-types.ts +8 -0
  191. package/src/registry/command/kernel-commands.ts +62 -3
  192. package/src/registry/tool/execute.ts +14 -0
  193. package/src/runtime/query/budget-nudge.ts +92 -0
  194. package/src/runtime/query/compact-session.ts +194 -74
  195. package/src/runtime/query/guard.ts +22 -0
  196. package/src/runtime/query/iteration/index.ts +26 -1
  197. package/src/runtime/query/iteration/phases/compaction.ts +147 -41
  198. package/src/runtime/query/iteration/phases/precompute.ts +277 -0
  199. package/src/runtime/query/turn/outcome-ledger.ts +34 -0
  200. package/src/store/goal/gates.ts +738 -0
  201. package/src/store/goal/index.ts +109 -0
  202. package/src/tools/builtins/bash.ts +1 -1
  203. package/src/tools/builtins/browser.ts +4 -0
  204. package/src/tools/builtins/monitor.ts +2 -0
  205. package/src/tools/builtins/search-tools.ts +2 -2
  206. package/src/tools/builtins/sleep-guard.ts +1 -1
  207. package/src/tools/builtins/wait-for-job.ts +1 -1
  208. package/src/tools/coordinator/ask-user-question.ts +37 -10
  209. package/src/tools/coordinator/index.ts +3 -0
  210. package/src/tools/defineTool.ts +5 -0
  211. package/src/tools/goal/confirmation.ts +171 -3
  212. package/src/tools/goal/index.ts +15 -3
  213. package/src/tools/memory/save.ts +2 -0
  214. package/src/tools/schedules/index.ts +1 -0
  215. package/src/tools/schedules/loop-tool.ts +2 -0
  216. package/src/tools/schedules/present.ts +2 -0
  217. package/src/tools/schedules/schedule-tool.ts +84 -9
  218. package/src/tools/schedules/self-tool.ts +152 -0
  219. package/src/tools/schedules/timer-tools.ts +2 -0
  220. package/src/tools/schedules/types.ts +62 -0
  221. package/src/toolsets/manager.ts +55 -8
  222. package/src/types/agent/supervisor.ts +11 -0
  223. package/src/types/agent/task.ts +7 -0
  224. package/src/types/goal/index.ts +72 -0
  225. package/src/types/session/events.ts +7 -0
  226. package/src/types/session/outcome.ts +16 -1
  227. package/src/types/session/records.ts +27 -0
  228. package/src/types/tool/index.ts +7 -0
@@ -0,0 +1,390 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ import { RECALLED_MEMORY_ENTRY_KEY } from '../turn/memory-recall.js'
4
+ import type { TokenUsage } from '../types/common/index.js'
5
+ import { type Message, turnContextKey } from '../types/message/index.js'
6
+
7
+ /**
8
+ * A compaction summary written before it is needed.
9
+ *
10
+ * When the context nears the trigger, one summary request starts in the
11
+ * background for the span the pass would summarise. At the trigger the pass
12
+ * installs it at once when it is still valid for the conversation as it
13
+ * stands, and writes a fresh one when it is not. Two rules hold everywhere:
14
+ *
15
+ * - A prepared summary only ever replaces the messages it was written from.
16
+ * Anything said after it was armed stays verbatim after the summary, so no
17
+ * message the summary did not see is dropped.
18
+ * - One conversation has at most one summary in flight. A pass that finds one
19
+ * waits for it instead of starting another, and a pass a person asked for
20
+ * stops it first.
21
+ *
22
+ * The store lives in the process, per session. It holds no secrets beyond the
23
+ * summary text the session would have written anyway, and is never written to
24
+ * disk.
25
+ */
26
+
27
+ /** Consecutive prepared summaries that failed or were refused before the session stops preparing them. */
28
+ export const PRECOMPUTE_MAX_FAILURES = 3
29
+
30
+ /** How much of the way to the trigger a summary starts when the host names nothing else: see `armUsage`. */
31
+ export const PRECOMPUTE_DEFAULT_ARM_FRACTION = 0.2
32
+
33
+ /** Why a prepared summary was not used. */
34
+ export type PrecomputeRefusal =
35
+ | 'boundary_missing'
36
+ | 'covered_changed'
37
+ /** An assistant reply sits among the covered messages that the summary never saw. */
38
+ | 'unseen_reply'
39
+ /** The model now serving the conversation has another context window than the one the summary was sized for. */
40
+ | 'window_changed'
41
+ /** A recalled-memory entry the summary was written from is gone or different. */
42
+ | 'memory_withdrawn'
43
+ /** A tool result the summary was written from is gone or different (cleared, replaced). */
44
+ | 'tool_results_withdrawn'
45
+ | 'hook_rewrite'
46
+ | 'would_not_fit'
47
+ | 'summary_failed'
48
+
49
+ /** Where the arm came from, for the log: a loop entry, a reply, an idle host. */
50
+ export type PrecomputeArmSource = 'estimate' | 'after_turn' | 'idle'
51
+
52
+ /** What a prepared summary cost, kept until a pass takes it so the spend lands on the turn that used it. */
53
+ export interface PreparedSpend {
54
+ readonly usage: TokenUsage
55
+ readonly route: { readonly providerId: string; readonly model: string }
56
+ }
57
+
58
+ export interface PrecomputeEntry {
59
+ status: 'pending' | 'ready' | 'failed'
60
+ readonly source: PrecomputeArmSource
61
+ /** The messages the summary was written from, as they were when it was armed. */
62
+ readonly covered: readonly Message[]
63
+ /**
64
+ * What each covered message said when the summary was armed, by
65
+ * {@link messageDigest}. A message edited or replaced in place under the same
66
+ * id, or the same object changed after the summary read it, no longer matches.
67
+ */
68
+ readonly coveredDigests: readonly string[]
69
+ /** The context window the summary was sized for; a model with another window refuses it. */
70
+ readonly windowTokens?: number
71
+ /** The user message the conversation was on when it was armed. */
72
+ readonly prompt: Message | undefined
73
+ readonly controller: AbortController
74
+ /** Settles when the summary is ready, failed or stopped. Never rejects. */
75
+ done: Promise<void>
76
+ summary?: string
77
+ hookInstructions?: string
78
+ /**
79
+ * What the request spent and no turn has booked yet. Spend that arrives while
80
+ * the arming turn is open goes onto that turn at once and never lands here.
81
+ */
82
+ readonly spend: PreparedSpend[]
83
+ }
84
+
85
+ export class PrecomputeStore {
86
+ #entry: PrecomputeEntry | undefined
87
+ /** Spend of prepared summaries that were dropped or outlived their turn, waiting for a pass to book it. */
88
+ readonly #unbooked: PreparedSpend[] = []
89
+ #failures = 0
90
+ #vetoed: Message | undefined
91
+
92
+ get entry(): PrecomputeEntry | undefined {
93
+ return this.#entry
94
+ }
95
+
96
+ get failures(): number {
97
+ return this.#failures
98
+ }
99
+
100
+ /** True when a prepared summary may be started for the conversation as it stands. */
101
+ canArm(prompt: Message | undefined): boolean {
102
+ if (this.#entry) return false
103
+ if (this.#failures >= PRECOMPUTE_MAX_FAILURES) return false
104
+ return !(prompt !== undefined && this.#vetoed === prompt)
105
+ }
106
+
107
+ set(entry: PrecomputeEntry): void {
108
+ this.#entry = entry
109
+ }
110
+
111
+ /** Forget the entry (it was used, refused, or the context it described is gone). */
112
+ clear(entry?: PrecomputeEntry): void {
113
+ if (entry === undefined || this.#entry === entry) this.#entry = undefined
114
+ }
115
+
116
+ /** A prepared summary failed or was refused: count it, and do not retry for the same prompt. */
117
+ countFailure(prompt: Message | undefined): void {
118
+ this.#failures++
119
+ this.#vetoed = prompt
120
+ }
121
+
122
+ /** A prepared summary was used: the failure run ends. */
123
+ countSuccess(): void {
124
+ this.#failures = 0
125
+ this.#vetoed = undefined
126
+ }
127
+
128
+ /**
129
+ * Stop the summary in flight and wait until it has stopped. Returns what it
130
+ * spent that no turn had booked, which the caller owes a ledger: a stopped
131
+ * summary still cost the tokens it used.
132
+ */
133
+ async cancel(): Promise<readonly PreparedSpend[]> {
134
+ const entry = this.#entry
135
+ if (!entry) return []
136
+ this.#entry = undefined
137
+ entry.controller.abort()
138
+ await entry.done
139
+ const spend = [...entry.spend]
140
+ entry.spend.length = 0
141
+ return spend
142
+ }
143
+
144
+ /** Keep spend nobody could book yet for the next pass that can. */
145
+ addUnbooked(spend: readonly PreparedSpend[]): void {
146
+ this.#unbooked.push(...spend)
147
+ }
148
+
149
+ /** Take what is waiting to be booked: spend kept by {@link addUnbooked}. Empties it. */
150
+ drainUnbooked(): PreparedSpend[] {
151
+ return this.#unbooked.splice(0)
152
+ }
153
+
154
+ /**
155
+ * Take every unbooked cost this session holds: the ones kept by
156
+ * {@link addUnbooked} and what the prepared summary in the store spent but no
157
+ * turn booked. The summary is left in place, so a ready one can still be used;
158
+ * its spend is moved out and counted once.
159
+ */
160
+ takeSpend(): PreparedSpend[] {
161
+ const taken = this.drainUnbooked()
162
+ const entry = this.#entry
163
+ if (entry && entry.status !== 'pending') taken.push(...entry.spend.splice(0))
164
+ return taken
165
+ }
166
+
167
+ /** True when the store holds spend nobody has booked. */
168
+ holdsSpend(): boolean {
169
+ return this.#unbooked.length > 0 || (this.#entry?.spend.length ?? 0) > 0
170
+ }
171
+ }
172
+
173
+ const stores = new Map<string, PrecomputeStore>()
174
+ const MAX_STORES = 32
175
+
176
+ /** The store of one session, made on first use. The oldest idle stores are dropped past a bound. */
177
+ export function precomputeStoreFor(sessionId: string): PrecomputeStore {
178
+ let store = stores.get(sessionId)
179
+ if (store) {
180
+ stores.delete(sessionId)
181
+ stores.set(sessionId, store)
182
+ return store
183
+ }
184
+ store = new PrecomputeStore()
185
+ stores.set(sessionId, store)
186
+ for (const [id, old] of stores) {
187
+ if (stores.size <= MAX_STORES) break
188
+ if (id !== sessionId && old.entry?.status !== 'pending' && !old.holdsSpend()) stores.delete(id)
189
+ }
190
+ return store
191
+ }
192
+
193
+ /**
194
+ * End a conversation's prepared summary: stop the one in flight or waiting and
195
+ * return what it and any earlier one cost that no turn or pass booked. A host
196
+ * calls it when the conversation closes, so a summary the conversation never
197
+ * used is still on its ledger once. The session's store is forgotten.
198
+ */
199
+ export async function releasePreparedSummary(sessionId: string): Promise<readonly PreparedSpend[]> {
200
+ const store = stores.get(sessionId)
201
+ if (!store) return []
202
+ const stopped = await store.cancel()
203
+ const spend = [...store.drainUnbooked(), ...stopped]
204
+ stores.delete(sessionId)
205
+ return spend
206
+ }
207
+
208
+ /** For tests: forget every store. */
209
+ export function resetPrecomputeStores(): void {
210
+ stores.clear()
211
+ }
212
+
213
+ /**
214
+ * The context size, as a share of the window, at which a summary starts:
215
+ * `1 - armFraction` of the window, or the trigger when that is lower.
216
+ */
217
+ export function armUsage(trigger: number, armFraction: number): number {
218
+ return Math.min(1 - armFraction, trigger)
219
+ }
220
+
221
+ /** The same message: the same object, or the same recorded id (an edit copies the object and keeps the id). */
222
+ export function sameMessage(a: Message | undefined, b: Message | undefined): boolean {
223
+ if (a === undefined || b === undefined) return false
224
+ if (a === b) return true
225
+ return a.id !== undefined && a.id === b.id && a.role === b.role
226
+ }
227
+
228
+ /** `value` as JSON with object keys in a fixed order, so two equal messages digest alike whatever order they were built in. */
229
+ function canonicalJson(value: unknown): string {
230
+ return JSON.stringify(value, (_key, nested: unknown) => {
231
+ if (typeof nested !== 'object' || nested === null || Array.isArray(nested)) return nested
232
+ const sorted: Record<string, unknown> = {}
233
+ for (const key of Object.keys(nested).sort())
234
+ sorted[key] = (nested as Record<string, unknown>)[key]
235
+ return sorted
236
+ })
237
+ }
238
+
239
+ /** A stable digest of a message as it reads now: role, content, tool calls, source, id, everything it carries. */
240
+ export function messageDigest(message: Message): string {
241
+ return createHash('sha256')
242
+ .update(canonicalJson(message) ?? 'null')
243
+ .digest('hex')
244
+ }
245
+
246
+ export type PreparedAssessment =
247
+ | { readonly ok: true; readonly keepStart: number }
248
+ | { readonly ok: false; readonly reason: PrecomputeRefusal }
249
+
250
+ /** Why the covered message at `index` is no longer what the summary read. */
251
+ function changedReason(
252
+ entry: PrecomputeEntry,
253
+ live: readonly Message[],
254
+ floorLength: number,
255
+ index: number,
256
+ ): PrecomputeRefusal {
257
+ const covered = entry.covered
258
+ const wanted = covered[index] as Message
259
+ const here = live[floorLength + index]
260
+ // An assistant reply the summary never saw, in the middle of what it covers.
261
+ if (
262
+ here?.role === 'assistant' &&
263
+ !covered.some((message) => sameMessage(message, here)) &&
264
+ live.some((message, at) => at > floorLength + index && sameMessage(message, wanted))
265
+ ) {
266
+ return 'unseen_reply'
267
+ }
268
+ return withdrawnReason(wanted) ?? 'covered_changed'
269
+ }
270
+
271
+ /** The reason that names what a covered message was, when what it carried is the kind a host withdraws. */
272
+ function withdrawnReason(message: Message | undefined): PrecomputeRefusal | undefined {
273
+ if (message === undefined) return undefined
274
+ if (turnContextKey(message) === RECALLED_MEMORY_ENTRY_KEY) return 'memory_withdrawn'
275
+ if (message.role === 'tool') return 'tool_results_withdrawn'
276
+ return undefined
277
+ }
278
+
279
+ /**
280
+ * Whether a ready summary still describes the start of the conversation.
281
+ *
282
+ * `floorLength` is the count of leading system messages. The summary stands
283
+ * for the run of messages right after them: every message it covered must
284
+ * still be there, in order, and say what it said (compared by digest, not by
285
+ * identity or id). What came after stays as it is, so the new cut is just past
286
+ * the covered run.
287
+ */
288
+ export function assessPrepared(
289
+ entry: PrecomputeEntry,
290
+ live: readonly Message[],
291
+ input: {
292
+ readonly floorLength: number
293
+ readonly hookInstructions: string | undefined
294
+ /** Size of the context after the swap, and the size it must stay under. */
295
+ readonly tokensAfterSwap: (keepStart: number, summary: string) => number
296
+ readonly limitTokens: number
297
+ /** The window the conversation is sized for now. */
298
+ readonly windowTokens?: number
299
+ },
300
+ ): PreparedAssessment {
301
+ if (entry.status !== 'ready' || entry.summary === undefined) {
302
+ return { ok: false, reason: 'summary_failed' }
303
+ }
304
+ const covered = entry.covered
305
+ if (covered.length === 0 || !live.some((message) => sameMessage(message, covered[0]))) {
306
+ return { ok: false, reason: withdrawnReason(covered[0]) ?? 'boundary_missing' }
307
+ }
308
+ if (
309
+ entry.windowTokens !== undefined &&
310
+ input.windowTokens !== undefined &&
311
+ entry.windowTokens !== input.windowTokens
312
+ ) {
313
+ return { ok: false, reason: 'window_changed' }
314
+ }
315
+ for (let i = 0; i < covered.length; i++) {
316
+ const here = live[input.floorLength + i]
317
+ if (
318
+ here === undefined ||
319
+ !sameMessage(here, covered[i]) ||
320
+ messageDigest(here) !== entry.coveredDigests[i]
321
+ ) {
322
+ return { ok: false, reason: changedReason(entry, live, input.floorLength, i) }
323
+ }
324
+ }
325
+ if (entry.hookInstructions !== input.hookInstructions) {
326
+ return { ok: false, reason: 'hook_rewrite' }
327
+ }
328
+ const keepStart = input.floorLength + covered.length
329
+ if (input.tokensAfterSwap(keepStart, entry.summary) >= input.limitTokens) {
330
+ return { ok: false, reason: 'would_not_fit' }
331
+ }
332
+ return { ok: true, keepStart }
333
+ }
334
+
335
+ export type ClaimedSummary =
336
+ | {
337
+ readonly ok: true
338
+ readonly summary: string
339
+ readonly keepStart: number
340
+ readonly spend: readonly PreparedSpend[]
341
+ }
342
+ | {
343
+ readonly ok: false
344
+ /** `none`: nothing was prepared. */
345
+ readonly reason: PrecomputeRefusal | 'none'
346
+ readonly spend: readonly PreparedSpend[]
347
+ }
348
+
349
+ /**
350
+ * Take the session's prepared summary for a pass about to write one.
351
+ *
352
+ * A summary still in flight is waited for when `awaitPending` is set (it is
353
+ * the one this pass would have written) and left alone otherwise. The entry is
354
+ * consumed either way; a refusal counts toward the failure cap, a use ends it.
355
+ * What the prepared request spent comes back for the caller to put on its
356
+ * ledger.
357
+ */
358
+ export async function claimPrepared(
359
+ store: PrecomputeStore,
360
+ live: readonly Message[],
361
+ input: {
362
+ readonly floorLength: number
363
+ readonly hookInstructions: string | undefined
364
+ readonly tokensAfterSwap: (keepStart: number, summary: string) => number
365
+ readonly limitTokens: number
366
+ readonly windowTokens?: number
367
+ readonly awaitPending: boolean
368
+ readonly waitFor?: (promise: Promise<void>) => Promise<void>
369
+ },
370
+ ): Promise<ClaimedSummary> {
371
+ const entry = store.entry
372
+ if (!entry) return { ok: false, reason: 'none', spend: [] }
373
+ if (entry.status === 'pending') {
374
+ if (!input.awaitPending) return { ok: false, reason: 'none', spend: [] }
375
+ await (input.waitFor ? input.waitFor(entry.done) : entry.done)
376
+ }
377
+ // Another pass may have taken it while this one waited.
378
+ if (store.entry !== entry) return { ok: false, reason: 'none', spend: [] }
379
+ store.clear(entry)
380
+ const spend = [...entry.spend]
381
+ entry.spend.length = 0
382
+ if (entry.status !== 'ready') return { ok: false, reason: 'summary_failed', spend }
383
+ const assessment = assessPrepared(entry, live, input)
384
+ if (!assessment.ok) {
385
+ store.countFailure(entry.prompt)
386
+ return { ok: false, reason: assessment.reason, spend }
387
+ }
388
+ store.countSuccess()
389
+ return { ok: true, summary: entry.summary as string, keepStart: assessment.keepStart, spend }
390
+ }
@@ -72,6 +72,23 @@ export const CompactionConfigSchema = z.object({
72
72
  * compaction on.
73
73
  */
74
74
  autoCompact: z.boolean().optional(),
75
+ /**
76
+ * Write the summary before it is needed. When the context nears the
77
+ * trigger and the host has a model set aside for summaries, one summary
78
+ * request starts in the background; at the trigger the pass installs it at
79
+ * once if the conversation it saw is still the start of this one, and makes
80
+ * a fresh summary when it is not. Nothing runs when automatic compaction is
81
+ * off, and a short session never reaches the arm point. Absent or `true` keeps it on; `false`
82
+ * keeps every summary to the moment it is needed.
83
+ */
84
+ precompute: z.boolean().optional(),
85
+ /**
86
+ * How far before the window is full the summary starts: the arm point is
87
+ * `1 - precomputeArmFraction` of the window (0.2 when absent, so 0.8 of it), or
88
+ * the trigger when that is lower. `0` arms only at the trigger, which is no
89
+ * head start.
90
+ */
91
+ precomputeArmFraction: z.number().min(0).max(1).optional(),
75
92
  /** Optional automatic-summary window; capped to the actual model window. */
76
93
  autoCompactWindowTokens: z.number().int().positive().safe().optional(),
77
94
  /**
@@ -946,6 +946,15 @@ export class AgentManager {
946
946
  childConfig.toolResultGuardrails = inheritedScreens
947
947
  }
948
948
 
949
+ // The parent's hook manager, for the same reason as the screens: a
950
+ // child's `configBuilder` cannot forward what it was never told about.
951
+ const inheritedPlugins =
952
+ (options.configOverrides as { pluginManager?: unknown } | undefined)?.pluginManager ??
953
+ context.pluginManager
954
+ if (inheritedPlugins !== undefined) {
955
+ ;(childConfig as { pluginManager?: unknown }).pluginManager = inheritedPlugins
956
+ }
957
+
949
958
  // A child of its own reader record over the family's authored ledger, so
950
959
  // what the parent wrote is still "this session's" to a child that runs
951
960
  // it, while what the child has read stays its own and a write by a
@@ -266,6 +266,10 @@ export class TurnRecorder {
266
266
  #turnSystemPrompt: string | undefined
267
267
  /** Set by {@link resume}: the next reconciliation re-bases the fold on the restored context. */
268
268
  #rebasePending = false
269
+ /** What the pass that is about to be re-based on measured; see {@link noteCompaction}. */
270
+ #pendingCompaction: CompactionFacts | undefined
271
+ /** Tokens all earlier compactions of this session dropped; read from the log when the first compaction of this recorder is written. */
272
+ #cumulativeDropped: number | undefined
269
273
  /** The summary the log already folds to, read when the recorder opened. */
270
274
  #foldSummary: readonly Message[] = []
271
275
  /**
@@ -371,6 +375,11 @@ export class TurnRecorder {
371
375
  return this.#phase === 'active'
372
376
  }
373
377
 
378
+ /** Whether usage accumulated now still reaches the turn's record: the turn is active and its closing record is not queued. */
379
+ get acceptsUsage(): boolean {
380
+ return this.#turnOpen()
381
+ }
382
+
374
383
  /** Whether the turn's last segment record is `turn_paused`. */
375
384
  get isPaused(): boolean {
376
385
  return this.#phase === 'paused'
@@ -578,6 +587,17 @@ export class TurnRecorder {
578
587
  this.#lastPromptMessageCount = this.#turn.messages.length
579
588
  }
580
589
 
590
+ /**
591
+ * Say what the compaction pass that just replaced the context measured. The
592
+ * `compaction` record the next reconciliation writes carries it (its
593
+ * trigger, real token counts, duration and the running total of tokens
594
+ * dropped). Without it the record still names the messages kept, with the
595
+ * counts left at zero.
596
+ */
597
+ noteCompaction(facts: CompactionFacts): void {
598
+ this.#pendingCompaction = facts
599
+ }
600
+
581
601
  /** Forget the last prompt measurement (after compaction replaced the context it described). */
582
602
  clearLastPromptTokens(): void {
583
603
  this.#lastPromptTokens = undefined
@@ -1479,20 +1499,40 @@ export class TurnRecorder {
1479
1499
  const keptMessageIds = keptEntries.map((entry) => entry.id as MessageId)
1480
1500
  this.#view = next
1481
1501
  const turnId = this.turnId
1502
+ const facts = this.#pendingCompaction
1503
+ this.#pendingCompaction = undefined
1504
+ const dropped = facts ? Math.max(0, facts.tokensBefore - facts.tokensAfter) : 0
1482
1505
  void this.#enqueue(async () => {
1506
+ // Read once, from the records already in the log, when the first
1507
+ // compaction of this recorder is written: a session that never compacts
1508
+ // never reads it.
1509
+ this.#cumulativeDropped ??= await readCumulativeDropped(this.log)
1510
+ this.#cumulativeDropped += dropped
1511
+ const cumulativeDropped = this.#cumulativeDropped
1483
1512
  const toSeq = this.#lastEntry?.record.seq ?? (await this.log.head())?.pointer.seq ?? 1
1484
- return this.#append({
1513
+ const compactionId = generateMessageId()
1514
+ const entry = await this.#append({
1485
1515
  type: 'compaction',
1486
1516
  turnId,
1487
- compactionId: generateMessageId(),
1517
+ compactionId,
1488
1518
  strategy: 'context-rewrite',
1489
- trigger: 'auto',
1519
+ // What an earlier release reads: `prepared` is told by the record below.
1520
+ trigger:
1521
+ facts?.trigger === 'prepared' || facts?.trigger === undefined ? 'auto' : facts.trigger,
1490
1522
  replacesSeqRange: [1, toSeq],
1491
1523
  summary,
1492
1524
  keptMessageIds,
1493
- tokensBefore: 0,
1494
- tokensAfter: 0,
1525
+ tokensBefore: facts?.tokensBefore ?? 0,
1526
+ tokensAfter: facts?.tokensAfter ?? 0,
1495
1527
  })
1528
+ if (facts) {
1529
+ // A record of its own, never a field of the one above: see
1530
+ // `CompactionMeasuredRecordSchema`. A refused write loses only the measures.
1531
+ await this.#append(measuredDraft(compactionId, facts, cumulativeDropped, turnId)).catch(
1532
+ () => undefined,
1533
+ )
1534
+ }
1535
+ return entry
1496
1536
  }).catch(() => undefined)
1497
1537
  for (const entry of tailEntries) {
1498
1538
  const message = entry.message
@@ -1673,6 +1713,53 @@ export async function recordedTurnStart(
1673
1713
  return undefined
1674
1714
  }
1675
1715
 
1716
+ /** What a compaction pass measured, handed to the recorder so its record is not left at zero. */
1717
+ export interface CompactionFacts {
1718
+ readonly trigger?: 'auto' | 'manual' | 'idle' | 'prepared'
1719
+ readonly tokensBefore: number
1720
+ readonly tokensAfter: number
1721
+ readonly durationMs?: number
1722
+ readonly precomputed?: boolean
1723
+ }
1724
+
1725
+ /** The `compaction_measured` record that follows the `compaction` record `compactionId`. */
1726
+ export function measuredDraft(
1727
+ compactionId: string,
1728
+ facts: CompactionFacts,
1729
+ cumulativeDroppedTokens: number,
1730
+ turnId?: TurnId,
1731
+ ): Parameters<SessionLog['append']>[1] {
1732
+ return {
1733
+ type: 'compaction_measured',
1734
+ ...(turnId ? { turnId } : {}),
1735
+ ignorable: true,
1736
+ compactionId,
1737
+ trigger: facts.trigger ?? 'auto',
1738
+ ...(facts.durationMs !== undefined ? { durationMs: facts.durationMs } : {}),
1739
+ cumulativeDroppedTokens,
1740
+ ...(facts.precomputed ? { precomputed: true } : {}),
1741
+ }
1742
+ }
1743
+
1744
+ /**
1745
+ * The running total of tokens the session's compactions have dropped: what
1746
+ * each `compaction` record's sizes say, summed. Read from the sizes, which an
1747
+ * earlier release also writes and reads, never from a stored total.
1748
+ */
1749
+ export async function readCumulativeDropped(log: SessionLog): Promise<number> {
1750
+ return foldSessionLog(log, {
1751
+ name: 'compaction-dropped',
1752
+ mode: 'strict',
1753
+ create: () => ({ total: 0 }),
1754
+ apply: (state, entry) => {
1755
+ const record = entry.record as SessionRecord
1756
+ if (record.type !== 'compaction') return
1757
+ state.total += Math.max(0, record.tokensBefore - record.tokensAfter)
1758
+ },
1759
+ result: (state) => state.total,
1760
+ })
1761
+ }
1762
+
1676
1763
  /**
1677
1764
  * The session's folded context with the id each message's record gave it,
1678
1765
  * spilled bodies read back.
@@ -43,6 +43,9 @@ export const MAX_PEER_CONNECTIONS = 16
43
43
  // only long enough to be verified, never accepts messages, and is not a terminal.
44
44
  // 'person' is `namzu send` or the watcher's message key: the operator's own words from another terminal. It
45
45
  // listens only long enough to be verified, never accepts messages, and is not a terminal either.
46
+ // 'run' is one scheduled run of a job: it opens a restricted endpoint for the life of the run, takes
47
+ // only plain messages (never an approval or an interrupt), and is not a terminal. An older reader skips
48
+ // a record of this kind, so it simply does not see the run.
46
49
  export const PeerSessionKindSchema = z.enum([
47
50
  'tui',
48
51
  'exec',
@@ -51,6 +54,7 @@ export const PeerSessionKindSchema = z.enum([
51
54
  'cli',
52
55
  'person',
53
56
  'net',
57
+ 'run',
54
58
  ])
55
59
  export type PeerSessionKind = z.infer<typeof PeerSessionKindSchema>
56
60
 
@@ -107,6 +107,10 @@ export const PeerRecordSchema = z
107
107
  /** The name of the machine that set the role. */
108
108
  roleBy: z.string().min(1).max(80).optional(),
109
109
  roleAt: z.number().int().nonnegative().optional(),
110
+ /** `kind: 'run'` only: the name of the scheduled job this run belongs to. */
111
+ jobName: z.string().min(1).max(64).optional(),
112
+ /** `kind: 'run'` only: the id of this run. */
113
+ runId: z.string().min(1).max(128).optional(),
110
114
  })
111
115
  .strict()
112
116
 
@@ -45,6 +45,7 @@ export {
45
45
  SHELL_HOOK_PASCAL_EVENT_NAMES,
46
46
  SHELL_HOOKS_PLUGIN_ID,
47
47
  shellHookIfMatches,
48
+ shellHookEntryLimitProblem,
48
49
  shellHookIfProblem,
49
50
  shellHookMatcherProblem,
50
51
  shellHookMatches,
@@ -80,6 +81,7 @@ export type {
80
81
  ShellHookOnFailure,
81
82
  ShellHookCall,
82
83
  ShellHookInput,
84
+ ShellHookHandlerType,
83
85
  ShellHookOptions,
84
86
  ShellHookPathFilter,
85
87
  ShellHookOutcome,