@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
@@ -5,8 +5,20 @@ import {
5
5
  compactNow,
6
6
  compactRegion,
7
7
  } from '../../compaction/manual.js'
8
- import { readFoldedHistory } from '../../manager/session/turn-recorder.js'
8
+ import {
9
+ type PrecomputeStore,
10
+ type PreparedSpend,
11
+ precomputeStoreFor,
12
+ } from '../../compaction/precompute.js'
13
+ import { estimateMessagesTokens } from '../../compaction/token-estimate.js'
14
+ import {
15
+ measuredDraft,
16
+ readCumulativeDropped,
17
+ readFoldedHistory,
18
+ } from '../../manager/session/turn-recorder.js'
19
+ import type { SessionLog } from '../../store/session-log/index.js'
9
20
  import { DiskSessionLog } from '../../store/session-log/index.js'
21
+ import { accumulateTokenUsage } from '../../types/common/index.js'
10
22
  import { NamzuError } from '../../types/errors/index.js'
11
23
  import type { MessageId, SessionId } from '../../types/ids/index.js'
12
24
  import type { Message } from '../../types/message/index.js'
@@ -29,6 +41,15 @@ export interface CompactSessionParams
29
41
  * lapses. Recorded on the `compaction` record.
30
42
  */
31
43
  readonly trigger?: 'manual' | 'idle'
44
+ /**
45
+ * What an `'idle'` pass does with a summary prepared ahead (see
46
+ * `CompactionConfig.precompute`). Absent: it is used when it is still valid
47
+ * (waiting for one still being written) and a fresh summary is written when
48
+ * it is not. `'only'`: used or nothing, a refusal ends the pass as a no-op
49
+ * (`null`). `false`: never used, and stopped first. Ignored for `'manual'`,
50
+ * which always stops it.
51
+ */
52
+ readonly preparedSummary?: 'only' | false
32
53
  /** Where to find the session's log, and the lease to append under. */
33
54
  readonly locator?: SessionLocatorOptions
34
55
  }
@@ -45,45 +66,57 @@ export interface CompactSessionParams
45
66
  export async function compactSession(
46
67
  params: CompactSessionParams,
47
68
  ): Promise<CompactionResult | null> {
48
- const { sessionId, locator = {}, trigger = 'manual', hooks, ...input } = params
69
+ const { sessionId, locator = {}, trigger = 'manual', hooks, preparedSummary, ...input } = params
49
70
  const log = await locateSessionLog(sessionId, locator)
50
71
  return withSessionLease(log, locator.lease, async (lease) => {
51
72
  const active = await log.activeTurn({ lease })
52
73
  if (active) {
53
74
  throw new TurnInProgressError({ sessionId, activeTurnId: active.turnId, state: active.state })
54
75
  }
55
- const history = await readFoldedHistory(log)
56
- const ids = new Map<Message, MessageId>()
57
- for (const entry of history) if (entry.messageId) ids.set(entry.message, entry.messageId)
58
- const result = await compactNow({
59
- // The session's own file, so the summary says where exact text is stored.
60
- ...(log instanceof DiskSessionLog ? { sessionFile: log.file } : {}),
61
- ...input,
62
- messages: history.map((entry) => entry.message),
63
- ...(hooks ? { hooks: { ...hooks, sessionId, trigger } } : {}),
64
- })
65
- if (!result) return null
66
- const head = await log.head()
67
- if (!head) {
68
- throw new NamzuError({
69
- code: 'not_found',
70
- message: `Session ${sessionId} has an empty log; there is nothing to compact.`,
71
- details: { sessionId },
76
+ // One summary at a time. A host compacting an idle conversation takes the
77
+ // summary prepared ahead when it is still valid (or waits for the one being
78
+ // written); any other pass stops it first.
79
+ const usePrepared = trigger === 'idle' && preparedSummary !== false
80
+ const store = precomputeStoreFor(sessionId)
81
+ const owed = [...store.drainUnbooked(), ...(usePrepared ? [] : await store.cancel())]
82
+ return carrying(store, owed, async () => {
83
+ const history = await readFoldedHistory(log)
84
+ const ids = new Map<Message, MessageId>()
85
+ for (const entry of history) if (entry.messageId) ids.set(entry.message, entry.messageId)
86
+ const startedAt = performance.now()
87
+ const result = await compactNow({
88
+ // The session's own file, so the summary says where exact text is stored.
89
+ ...(log instanceof DiskSessionLog ? { sessionFile: log.file } : {}),
90
+ ...input,
91
+ messages: history.map((entry) => entry.message),
92
+ ...(hooks ? { hooks: { ...hooks, sessionId, trigger } } : {}),
93
+ ...(usePrepared
94
+ ? { prepared: { sessionId, ...(preparedSummary === 'only' ? { only: true } : {}) } }
95
+ : {}),
72
96
  })
73
- }
74
- const { summary, keptMessageIds } = compactionShape(result.messages, ids)
75
- await log.append(lease, {
76
- type: 'compaction',
77
- compactionId: generateMessageId(),
78
- strategy: input.config.strategy,
79
- trigger,
80
- replacesSeqRange: [1, head.pointer.seq],
81
- summary,
82
- keptMessageIds,
83
- tokensBefore: 0,
84
- tokensAfter: 0,
97
+ if (!result) return null
98
+ const head = await log.head()
99
+ if (!head) {
100
+ throw new NamzuError({
101
+ code: 'not_found',
102
+ message: `Session ${sessionId} has an empty log; there is nothing to compact.`,
103
+ details: { sessionId },
104
+ })
105
+ }
106
+ const { summary, keptMessageIds } = compactionShape(result.messages, ids)
107
+ await appendCompaction(log, lease, {
108
+ strategy: input.config.strategy,
109
+ trigger,
110
+ replacesSeqRange: [1, head.pointer.seq],
111
+ summary,
112
+ keptMessageIds,
113
+ before: history.map((entry) => entry.message),
114
+ after: result.messages,
115
+ startedAt,
116
+ precomputed: result.precomputed === true,
117
+ })
118
+ return result
85
119
  })
86
- return result
87
120
  })
88
121
  }
89
122
 
@@ -126,57 +159,144 @@ export async function compactSessionRange(
126
159
  if (active) {
127
160
  throw new TurnInProgressError({ sessionId, activeTurnId: active.turnId, state: active.state })
128
161
  }
129
- const history = await readFoldedHistory(log)
130
- const position = (id: MessageId | undefined, fallback: number): number => {
131
- if (id === undefined) return fallback
132
- const at = history.findIndex((entry) => entry.messageId === id)
133
- if (at < 0) {
162
+ // One summary at a time: a pass asked for between turns stops one being prepared.
163
+ const store = precomputeStoreFor(sessionId)
164
+ const owed = [...store.drainUnbooked(), ...(await store.cancel())]
165
+ return carrying(store, owed, async () => {
166
+ const history = await readFoldedHistory(log)
167
+ const position = (id: MessageId | undefined, fallback: number): number => {
168
+ if (id === undefined) return fallback
169
+ const at = history.findIndex((entry) => entry.messageId === id)
170
+ if (at < 0) {
171
+ throw new NamzuError({
172
+ code: 'not_found',
173
+ message: `Message ${id} is not in session ${sessionId}'s current context; it may already have been summarised.`,
174
+ details: { sessionId, messageId: id },
175
+ })
176
+ }
177
+ return at
178
+ }
179
+ const start = position(from, 0)
180
+ const end = position(until, history.length)
181
+ const ids = new Map<Message, MessageId>()
182
+ for (const entry of history) if (entry.messageId) ids.set(entry.message, entry.messageId)
183
+ const startedAt = performance.now()
184
+ const result = await compactRegion({
185
+ // The session's own file, so the summary says where exact text is stored.
186
+ ...(log instanceof DiskSessionLog ? { sessionFile: log.file } : {}),
187
+ ...input,
188
+ messages: history.map((entry) => entry.message),
189
+ start,
190
+ end,
191
+ ...(hooks ? { hooks: { ...hooks, sessionId, trigger: 'manual' as const } } : {}),
192
+ })
193
+ if (!result) return null
194
+ const head = await log.head()
195
+ if (!head) {
134
196
  throw new NamzuError({
135
197
  code: 'not_found',
136
- message: `Message ${id} is not in session ${sessionId}'s current context; it may already have been summarised.`,
137
- details: { sessionId, messageId: id },
198
+ message: `Session ${sessionId} has an empty log; there is nothing to compact.`,
199
+ details: { sessionId },
138
200
  })
139
201
  }
140
- return at
141
- }
142
- const start = position(from, 0)
143
- const end = position(until, history.length)
144
- const ids = new Map<Message, MessageId>()
145
- for (const entry of history) if (entry.messageId) ids.set(entry.message, entry.messageId)
146
- const result = await compactRegion({
147
- // The session's own file, so the summary says where exact text is stored.
148
- ...(log instanceof DiskSessionLog ? { sessionFile: log.file } : {}),
149
- ...input,
150
- messages: history.map((entry) => entry.message),
151
- start,
152
- end,
153
- ...(hooks ? { hooks: { ...hooks, sessionId, trigger: 'manual' as const } } : {}),
154
- })
155
- if (!result) return null
156
- const head = await log.head()
157
- if (!head) {
158
- throw new NamzuError({
159
- code: 'not_found',
160
- message: `Session ${sessionId} has an empty log; there is nothing to compact.`,
161
- details: { sessionId },
202
+ const { summary, keptMessageIds } = compactionShape(result.messages, ids)
203
+ await appendCompaction(log, lease, {
204
+ strategy: input.config.strategy,
205
+ trigger: 'manual',
206
+ replacesSeqRange: [1, head.pointer.seq],
207
+ summary,
208
+ keptMessageIds,
209
+ before: history.map((entry) => entry.message),
210
+ after: result.messages,
211
+ startedAt,
212
+ precomputed: false,
162
213
  })
163
- }
164
- const { summary, keptMessageIds } = compactionShape(result.messages, ids)
165
- await log.append(lease, {
166
- type: 'compaction',
167
- compactionId: generateMessageId(),
168
- strategy: input.config.strategy,
169
- trigger: 'manual',
170
- replacesSeqRange: [1, head.pointer.seq],
171
- summary,
172
- keptMessageIds,
173
- tokensBefore: 0,
174
- tokensAfter: 0,
214
+ return result
175
215
  })
176
- return result
177
216
  })
178
217
  }
179
218
 
219
+ /**
220
+ * Run a between-turns pass that owes a ledger what prepared summaries spent
221
+ * (one this pass stopped, one that outlived its turn): the cost joins the
222
+ * result's `usage`, and a pass that ends without a result, or fails, leaves it
223
+ * with the session for the next pass or turn to book. Every prepared summary
224
+ * is booked once.
225
+ */
226
+ async function carrying(
227
+ store: PrecomputeStore,
228
+ owed: readonly PreparedSpend[],
229
+ run: () => Promise<CompactionResult | null>,
230
+ ): Promise<CompactionResult | null> {
231
+ try {
232
+ const result = await run()
233
+ if (!result) {
234
+ store.addUnbooked(owed)
235
+ return null
236
+ }
237
+ let usage = result.usage
238
+ for (const spent of owed) usage = accumulateTokenUsage(usage, spent.usage)
239
+ return { ...result, usage }
240
+ } catch (error) {
241
+ store.addUnbooked(owed)
242
+ throw error
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Append a between-turns pass: the `compaction` record, in the shape an
248
+ * earlier release reads (real sizes, a trigger it knows), then the
249
+ * `compaction_measured` record with what only this release records. A refused
250
+ * second write loses only the measures.
251
+ */
252
+ async function appendCompaction(
253
+ log: SessionLog,
254
+ lease: Parameters<SessionLog['append']>[0],
255
+ pass: {
256
+ readonly strategy: string
257
+ readonly trigger: 'manual' | 'idle'
258
+ readonly replacesSeqRange: [number, number]
259
+ readonly summary: Message[]
260
+ readonly keptMessageIds: MessageId[]
261
+ readonly before: readonly Message[]
262
+ readonly after: readonly Message[]
263
+ readonly startedAt: number
264
+ readonly precomputed: boolean
265
+ },
266
+ ): Promise<void> {
267
+ const tokensBefore = estimateMessagesTokens(pass.before)
268
+ const tokensAfter = estimateMessagesTokens(pass.after)
269
+ const compactionId = generateMessageId()
270
+ const priorDropped = await readCumulativeDropped(log)
271
+ await log.append(lease, {
272
+ type: 'compaction',
273
+ compactionId,
274
+ strategy: pass.strategy,
275
+ trigger: pass.trigger,
276
+ replacesSeqRange: pass.replacesSeqRange,
277
+ summary: pass.summary,
278
+ keptMessageIds: pass.keptMessageIds,
279
+ tokensBefore,
280
+ tokensAfter,
281
+ })
282
+ await log
283
+ .append(
284
+ lease,
285
+ measuredDraft(
286
+ compactionId,
287
+ {
288
+ trigger: pass.trigger,
289
+ tokensBefore,
290
+ tokensAfter,
291
+ durationMs: Math.max(0, Math.round(performance.now() - pass.startedAt)),
292
+ precomputed: pass.precomputed,
293
+ },
294
+ priorDropped + Math.max(0, tokensBefore - tokensAfter),
295
+ ),
296
+ )
297
+ .catch(() => undefined)
298
+ }
299
+
180
300
  /**
181
301
  * Express a compacted context as a `compaction` record: the new messages
182
302
  * before the first recorded one are its summary and the recorded ones are
@@ -1,6 +1,7 @@
1
1
  import type { TurnRecorder } from '../../manager/session/turn-recorder.js'
2
2
  import { buildLimitConfig, checkLimitsDetailed } from '../../turn/LimitChecker.js'
3
3
  import type { LimitCheckerConfig, StopReason } from '../../types/session/index.js'
4
+ import type { BudgetLeft } from './budget-nudge.js'
4
5
 
5
6
  export interface GuardConfig {
6
7
  tokenBudget: number
@@ -101,6 +102,27 @@ export class GuardCoordinator {
101
102
  return Math.max(0, this.limitConfig.timeoutMs - (Date.now() - this.startTime))
102
103
  }
103
104
 
105
+ /**
106
+ * What is left of each limit this turn has, for the request note that
107
+ * asks the model to leave its work tidy. `completedIterations` is the
108
+ * count before the call being prepared, so the call itself is counted.
109
+ * A limit that is off (zero) is left out.
110
+ */
111
+ budgetLeft(completedIterations: number): BudgetLeft {
112
+ const left: BudgetLeft = {}
113
+ const { maxIterations, timeoutMs } = this.limitConfig
114
+ if (maxIterations > 0) {
115
+ left.iterations = {
116
+ left: Math.max(0, maxIterations - completedIterations),
117
+ total: maxIterations,
118
+ }
119
+ }
120
+ if (timeoutMs > 0) {
121
+ left.timeMs = { left: this.remainingUntilTimeoutMs(), total: timeoutMs }
122
+ }
123
+ return left
124
+ }
125
+
104
126
  beforeIteration(recorder: TurnRecorder, abortSignal: AbortSignal): GuardCheckResult {
105
127
  const limitState = {
106
128
  aborted: abortSignal.aborted,
@@ -67,6 +67,7 @@ import { toErrorMessage } from '../../../utils/error.js'
67
67
  import { stableDigest } from '../../../utils/hash.js'
68
68
  import { generateMessageId } from '../../../utils/id.js'
69
69
  import { parseStructuredResultJson } from '../../../utils/structured-result-json.js'
70
+ import { type BudgetNudgeStage, budgetNudgeStage, budgetNudgeText } from '../budget-nudge.js'
70
71
  import { createCallbackInference } from '../callback-inference.js'
71
72
  import { SandboxAcquisitionStopped } from '../deferred-sandbox.js'
72
73
  import { deliverDurableInbound } from '../durable-inbound.js'
@@ -345,6 +346,8 @@ export class IterationOrchestrator {
345
346
  * sets it.
346
347
  */
347
348
  private stopDeferredForOutstandingWork = false
349
+ /** The latest budget line this turn has recorded, so each stage is said once. */
350
+ private budgetNudgeStage: BudgetNudgeStage = 0
348
351
  /** Nudges sent since the model last finished a call without hitting its output cap. */
349
352
  private outputContinuations = 0
350
353
  /** Watches the turn's steps for reasoning that piles up while nothing changes. */
@@ -888,6 +891,12 @@ export class IterationOrchestrator {
888
891
  // edge BEFORE compaction runs (so the refreshed slot is what
889
892
  // compaction preserves). No-op when no provider is configured.
890
893
  await refreshWorkingMemory(this.ctx)
894
+ // A turn that starts after the prompt cache lapsed installs a summary
895
+ // written earlier, when one is ready and still valid, before the old
896
+ // tool results are trimmed.
897
+ if (iterationNum === 1 && this.ctx.compactionConfig?.clearStaleToolResultsAtStart) {
898
+ await runCompactionCheck(this.ctx, { preparedOnly: true })
899
+ }
891
900
  if (iterationNum === 1) await runStaleResultClear(this.ctx)
892
901
  await runCompactionCheck(this.ctx)
893
902
  yield* this.ctx.drainPending()
@@ -922,6 +931,16 @@ export class IterationOrchestrator {
922
931
  this.ctx.log,
923
932
  )
924
933
  }
934
+ // Before the limit ends the run, say so once per stage. Recorded, so
935
+ // the model keeps reading it, and only after the guard has passed
936
+ // this call: a run that is about to be stopped has no call to spend.
937
+ const budgetLeft = this.ctx.guard.budgetLeft(iterationNum - 1)
938
+ const budgetStage = budgetNudgeStage(budgetLeft)
939
+ if (budgetStage > this.budgetNudgeStage) {
940
+ this.budgetNudgeStage = budgetStage
941
+ const text = budgetNudgeText(budgetLeft, budgetStage)
942
+ if (text) appendRecordedContext(recorder, [{ key: 'budget-nudge', text }], this.ctx.log)
943
+ }
925
944
  const contextSections =
926
945
  this.ctx.promptContributions?.render('context', { iteration: iterationNum }) ?? []
927
946
  const deferredMcpHints =
@@ -3627,7 +3646,13 @@ export class IterationOrchestrator {
3627
3646
  this.hydrateOutcome()
3628
3647
  return await this.outcomeLedger.preview()
3629
3648
  },
3630
- { finalMessage },
3649
+ {
3650
+ finalMessage,
3651
+ recordCheck: async (check) => {
3652
+ this.hydrateOutcome()
3653
+ await this.outcomeLedger.recordHostCheck(check)
3654
+ },
3655
+ },
3631
3656
  )
3632
3657
  if (typeof note !== 'string' || note.trim() === '') return undefined
3633
3658
  this.beforeEndNotes += 1