@namzu/sdk 56.1.0 → 57.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 (247) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/agents/QueryAgent.d.ts.map +1 -1
  3. package/dist/agents/QueryAgent.js +1 -0
  4. package/dist/agents/QueryAgent.js.map +1 -1
  5. package/dist/agents/index.d.ts +1 -0
  6. package/dist/agents/index.d.ts.map +1 -1
  7. package/dist/agents/index.js +1 -0
  8. package/dist/agents/index.js.map +1 -1
  9. package/dist/agents/plan.d.ts +20 -0
  10. package/dist/agents/plan.d.ts.map +1 -0
  11. package/dist/agents/plan.js +27 -0
  12. package/dist/agents/plan.js.map +1 -0
  13. package/dist/compaction/context-breakdown.d.ts +1 -1
  14. package/dist/compaction/context-breakdown.d.ts.map +1 -1
  15. package/dist/compaction/context-breakdown.js +9 -2
  16. package/dist/compaction/context-breakdown.js.map +1 -1
  17. package/dist/compaction/dangling.d.ts +12 -1
  18. package/dist/compaction/dangling.d.ts.map +1 -1
  19. package/dist/compaction/dangling.js +17 -3
  20. package/dist/compaction/dangling.js.map +1 -1
  21. package/dist/compaction/index.d.ts +2 -2
  22. package/dist/compaction/index.d.ts.map +1 -1
  23. package/dist/compaction/index.js.map +1 -1
  24. package/dist/compaction/manager.d.ts +16 -0
  25. package/dist/compaction/manager.d.ts.map +1 -1
  26. package/dist/compaction/manager.js +55 -0
  27. package/dist/compaction/manager.js.map +1 -1
  28. package/dist/compaction/manual.d.ts +2 -0
  29. package/dist/compaction/manual.d.ts.map +1 -1
  30. package/dist/compaction/manual.js +33 -4
  31. package/dist/compaction/manual.js.map +1 -1
  32. package/dist/compaction/restore.d.ts +51 -0
  33. package/dist/compaction/restore.d.ts.map +1 -0
  34. package/dist/compaction/restore.js +123 -0
  35. package/dist/compaction/restore.js.map +1 -0
  36. package/dist/compaction/types.d.ts +22 -0
  37. package/dist/compaction/types.d.ts.map +1 -1
  38. package/dist/compaction/verifier.d.ts.map +1 -1
  39. package/dist/compaction/verifier.js +3 -1
  40. package/dist/compaction/verifier.js.map +1 -1
  41. package/dist/compaction/wire.d.ts +3 -1
  42. package/dist/compaction/wire.d.ts.map +1 -1
  43. package/dist/compaction/wire.js +16 -0
  44. package/dist/compaction/wire.js.map +1 -1
  45. package/dist/index.d.ts +1 -1
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/plugin/shell-hook.d.ts +19 -1
  48. package/dist/plugin/shell-hook.d.ts.map +1 -1
  49. package/dist/plugin/shell-hook.js +21 -5
  50. package/dist/plugin/shell-hook.js.map +1 -1
  51. package/dist/prompt/coding-agent-doctrine.d.ts +2 -2
  52. package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
  53. package/dist/prompt/coding-agent-doctrine.js +3 -2
  54. package/dist/prompt/coding-agent-doctrine.js.map +1 -1
  55. package/dist/provider/errors.d.ts +3 -0
  56. package/dist/provider/errors.d.ts.map +1 -1
  57. package/dist/provider/errors.js +23 -3
  58. package/dist/provider/errors.js.map +1 -1
  59. package/dist/provider/fallback.d.ts.map +1 -1
  60. package/dist/provider/fallback.js +34 -3
  61. package/dist/provider/fallback.js.map +1 -1
  62. package/dist/provider/retry.d.ts +12 -5
  63. package/dist/provider/retry.d.ts.map +1 -1
  64. package/dist/provider/retry.js +22 -8
  65. package/dist/provider/retry.js.map +1 -1
  66. package/dist/public-runtime.d.ts +5 -3
  67. package/dist/public-runtime.d.ts.map +1 -1
  68. package/dist/public-runtime.js +5 -2
  69. package/dist/public-runtime.js.map +1 -1
  70. package/dist/public-types.d.ts +1 -1
  71. package/dist/public-types.d.ts.map +1 -1
  72. package/dist/runtime/jobs/registry.d.ts +42 -0
  73. package/dist/runtime/jobs/registry.d.ts.map +1 -1
  74. package/dist/runtime/jobs/registry.js +77 -0
  75. package/dist/runtime/jobs/registry.js.map +1 -1
  76. package/dist/runtime/query/calls-that-never-started.d.ts +12 -0
  77. package/dist/runtime/query/calls-that-never-started.d.ts.map +1 -0
  78. package/dist/runtime/query/calls-that-never-started.js +41 -0
  79. package/dist/runtime/query/calls-that-never-started.js.map +1 -0
  80. package/dist/runtime/query/executor/tool-call-admission.d.ts +2 -2
  81. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  82. package/dist/runtime/query/executor/tool-call-admission.js +13 -9
  83. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  84. package/dist/runtime/query/executor.d.ts +16 -1
  85. package/dist/runtime/query/executor.d.ts.map +1 -1
  86. package/dist/runtime/query/executor.js +45 -2
  87. package/dist/runtime/query/executor.js.map +1 -1
  88. package/dist/runtime/query/file-evidence-context.d.ts +21 -4
  89. package/dist/runtime/query/file-evidence-context.d.ts.map +1 -1
  90. package/dist/runtime/query/file-evidence-context.js +70 -8
  91. package/dist/runtime/query/file-evidence-context.js.map +1 -1
  92. package/dist/runtime/query/index.d.ts +6 -0
  93. package/dist/runtime/query/index.d.ts.map +1 -1
  94. package/dist/runtime/query/index.js +7 -11
  95. package/dist/runtime/query/index.js.map +1 -1
  96. package/dist/runtime/query/iteration/index.d.ts +1 -2
  97. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  98. package/dist/runtime/query/iteration/index.js +30 -19
  99. package/dist/runtime/query/iteration/index.js.map +1 -1
  100. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  101. package/dist/runtime/query/iteration/phases/compaction.js +20 -0
  102. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  103. package/dist/runtime/query/iteration/phases/context.d.ts +2 -0
  104. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  105. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  106. package/dist/runtime/query/iteration/recorded-context.d.ts +18 -0
  107. package/dist/runtime/query/iteration/recorded-context.d.ts.map +1 -0
  108. package/dist/runtime/query/iteration/recorded-context.js +37 -0
  109. package/dist/runtime/query/iteration/recorded-context.js.map +1 -0
  110. package/dist/runtime/query/iteration/step-context.d.ts +15 -51
  111. package/dist/runtime/query/iteration/step-context.d.ts.map +1 -1
  112. package/dist/runtime/query/iteration/step-context.js +24 -134
  113. package/dist/runtime/query/iteration/step-context.js.map +1 -1
  114. package/dist/runtime/query/iteration/step-shaping.d.ts +20 -8
  115. package/dist/runtime/query/iteration/step-shaping.d.ts.map +1 -1
  116. package/dist/runtime/query/iteration/step-shaping.js +52 -26
  117. package/dist/runtime/query/iteration/step-shaping.js.map +1 -1
  118. package/dist/runtime/query/iteration/stream-turn.d.ts.map +1 -1
  119. package/dist/runtime/query/iteration/stream-turn.js +45 -25
  120. package/dist/runtime/query/iteration/stream-turn.js.map +1 -1
  121. package/dist/runtime/query/prepare-turn.d.ts.map +1 -1
  122. package/dist/runtime/query/prepare-turn.js +10 -1
  123. package/dist/runtime/query/prepare-turn.js.map +1 -1
  124. package/dist/scheduler/completion-inbox.d.ts +27 -0
  125. package/dist/scheduler/completion-inbox.d.ts.map +1 -1
  126. package/dist/scheduler/completion-inbox.js +90 -23
  127. package/dist/scheduler/completion-inbox.js.map +1 -1
  128. package/dist/store/session-index/fts.d.ts.map +1 -1
  129. package/dist/store/session-index/fts.js +6 -0
  130. package/dist/store/session-index/fts.js.map +1 -1
  131. package/dist/test-support/file-evidence-held.d.ts +11 -0
  132. package/dist/test-support/file-evidence-held.d.ts.map +1 -0
  133. package/dist/test-support/file-evidence-held.js +28 -0
  134. package/dist/test-support/file-evidence-held.js.map +1 -0
  135. package/dist/test-support/request-only.d.ts +10 -0
  136. package/dist/test-support/request-only.d.ts.map +1 -0
  137. package/dist/test-support/request-only.js +15 -0
  138. package/dist/test-support/request-only.js.map +1 -0
  139. package/dist/tools/admit-facts.d.ts.map +1 -1
  140. package/dist/tools/admit-facts.js +1 -0
  141. package/dist/tools/admit-facts.js.map +1 -1
  142. package/dist/tools/builtins/bash.d.ts +42 -1
  143. package/dist/tools/builtins/bash.d.ts.map +1 -1
  144. package/dist/tools/builtins/bash.js +115 -48
  145. package/dist/tools/builtins/bash.js.map +1 -1
  146. package/dist/tools/builtins/read-file.d.ts.map +1 -1
  147. package/dist/tools/builtins/read-file.js +55 -5
  148. package/dist/tools/builtins/read-file.js.map +1 -1
  149. package/dist/tools/file-read-tracker.d.ts.map +1 -1
  150. package/dist/tools/file-read-tracker.js +28 -0
  151. package/dist/tools/file-read-tracker.js.map +1 -1
  152. package/dist/tools/untrusted-envelope.d.ts +7 -0
  153. package/dist/tools/untrusted-envelope.d.ts.map +1 -1
  154. package/dist/tools/untrusted-envelope.js +3 -1
  155. package/dist/tools/untrusted-envelope.js.map +1 -1
  156. package/dist/turn/evidence-recall.d.ts +19 -8
  157. package/dist/turn/evidence-recall.d.ts.map +1 -1
  158. package/dist/turn/evidence-recall.js +134 -53
  159. package/dist/turn/evidence-recall.js.map +1 -1
  160. package/dist/turn/memory-recall.d.ts +18 -0
  161. package/dist/turn/memory-recall.d.ts.map +1 -1
  162. package/dist/turn/memory-recall.js +43 -4
  163. package/dist/turn/memory-recall.js.map +1 -1
  164. package/dist/types/agent/base.d.ts +6 -0
  165. package/dist/types/agent/base.d.ts.map +1 -1
  166. package/dist/types/errors/catalog.d.ts +3 -0
  167. package/dist/types/errors/catalog.d.ts.map +1 -1
  168. package/dist/types/errors/catalog.js +24 -2
  169. package/dist/types/errors/catalog.js.map +1 -1
  170. package/dist/types/message/index.d.ts +46 -1
  171. package/dist/types/message/index.d.ts.map +1 -1
  172. package/dist/types/message/index.js +78 -1
  173. package/dist/types/message/index.js.map +1 -1
  174. package/dist/types/provider/error.d.ts +7 -0
  175. package/dist/types/provider/error.d.ts.map +1 -1
  176. package/dist/types/provider/errors.d.ts +24 -0
  177. package/dist/types/provider/errors.d.ts.map +1 -1
  178. package/dist/types/provider/errors.js +101 -1
  179. package/dist/types/provider/errors.js.map +1 -1
  180. package/dist/types/provider/stream.d.ts +6 -0
  181. package/dist/types/provider/stream.d.ts.map +1 -1
  182. package/dist/types/session/events.d.ts +8 -0
  183. package/dist/types/session/events.d.ts.map +1 -1
  184. package/dist/types/session/events.js.map +1 -1
  185. package/dist/types/session/prepare-step.d.ts +24 -0
  186. package/dist/types/session/prepare-step.d.ts.map +1 -1
  187. package/dist/types/tool/index.d.ts +39 -0
  188. package/dist/types/tool/index.d.ts.map +1 -1
  189. package/dist/types/tool/index.js.map +1 -1
  190. package/dist/types/tool/presentation.d.ts +4 -0
  191. package/dist/types/tool/presentation.d.ts.map +1 -1
  192. package/package.json +1 -1
  193. package/src/agents/QueryAgent.ts +1 -0
  194. package/src/agents/index.ts +1 -0
  195. package/src/agents/plan.ts +30 -0
  196. package/src/compaction/context-breakdown.ts +11 -3
  197. package/src/compaction/dangling.ts +35 -3
  198. package/src/compaction/index.ts +4 -0
  199. package/src/compaction/manager.ts +53 -0
  200. package/src/compaction/manual.ts +42 -10
  201. package/src/compaction/restore.ts +159 -0
  202. package/src/compaction/types.ts +25 -0
  203. package/src/compaction/verifier.ts +3 -1
  204. package/src/compaction/wire.ts +26 -1
  205. package/src/index.ts +2 -0
  206. package/src/plugin/shell-hook.ts +33 -5
  207. package/src/prompt/coding-agent-doctrine.ts +3 -2
  208. package/src/provider/errors.ts +27 -3
  209. package/src/provider/fallback.ts +34 -2
  210. package/src/provider/retry.ts +30 -10
  211. package/src/public-runtime.ts +15 -0
  212. package/src/public-types.ts +3 -0
  213. package/src/runtime/jobs/registry.ts +105 -0
  214. package/src/runtime/query/calls-that-never-started.ts +37 -0
  215. package/src/runtime/query/executor/tool-call-admission.ts +12 -9
  216. package/src/runtime/query/executor.ts +57 -2
  217. package/src/runtime/query/file-evidence-context.ts +79 -11
  218. package/src/runtime/query/index.ts +14 -10
  219. package/src/runtime/query/iteration/index.ts +32 -26
  220. package/src/runtime/query/iteration/phases/compaction.ts +19 -0
  221. package/src/runtime/query/iteration/phases/context.ts +3 -0
  222. package/src/runtime/query/iteration/recorded-context.ts +48 -0
  223. package/src/runtime/query/iteration/step-context.ts +27 -155
  224. package/src/runtime/query/iteration/step-shaping.ts +64 -40
  225. package/src/runtime/query/iteration/stream-turn.ts +47 -25
  226. package/src/runtime/query/prepare-turn.ts +10 -1
  227. package/src/scheduler/completion-inbox.ts +89 -22
  228. package/src/store/session-index/fts.ts +5 -0
  229. package/src/test-support/file-evidence-held.ts +27 -0
  230. package/src/test-support/request-only.ts +19 -0
  231. package/src/tools/admit-facts.ts +1 -0
  232. package/src/tools/builtins/bash.ts +149 -54
  233. package/src/tools/builtins/read-file.ts +66 -4
  234. package/src/tools/file-read-tracker.ts +25 -1
  235. package/src/tools/untrusted-envelope.ts +10 -1
  236. package/src/turn/evidence-recall.ts +189 -58
  237. package/src/turn/memory-recall.ts +59 -5
  238. package/src/types/agent/base.ts +7 -0
  239. package/src/types/errors/catalog.ts +31 -2
  240. package/src/types/message/index.ts +108 -1
  241. package/src/types/provider/error.ts +7 -0
  242. package/src/types/provider/errors.ts +120 -1
  243. package/src/types/provider/stream.ts +6 -0
  244. package/src/types/session/events.ts +8 -0
  245. package/src/types/session/prepare-step.ts +26 -0
  246. package/src/types/tool/index.ts +40 -0
  247. package/src/types/tool/presentation.ts +4 -0
@@ -1,6 +1,5 @@
1
1
  import { createRuntimeContextMessage } from '../../../types/message/index.js'
2
2
  import type { Message } from '../../../types/message/index.js'
3
- import { isOperatorUserMessage } from '../steering.js'
4
3
 
5
4
  /**
6
5
  * Request-only context, as the model reads it: a runtime-context user
@@ -18,167 +17,40 @@ export function stepContextMessage(content: string) {
18
17
  )
19
18
  }
20
19
 
21
- /**
22
- * Put `blocks` in front of the operator's new message when that message is
23
- * what the model is about to answer, so the request is the last thing it
24
- * reads and the longest data comes before it. Only the reminders and other
25
- * request-only context may follow that message: once the turn has an
26
- * assistant or tool message after it, the blocks stay at the end of the
27
- * history, where a caching driver ends its breakpoint before them, so the
28
- * tool loop of a long turn is not re-read at full price on every step.
29
- *
30
- * Reminders and notices that follow the operator's message stay where they
31
- * are: they are short, and the edge after the request is where they are read.
32
- */
33
- export function placeBeforeLatestOperatorMessage(history: Message[], blocks: readonly Message[]) {
34
- if (blocks.length === 0) return
35
- let at = history.length
36
- for (let i = history.length - 1; i >= 0; i--) {
37
- const message = history[i] as Message
38
- if (isOperatorUserMessage(message)) {
39
- at = i
40
- break
41
- }
42
- // A reply or a tool result after the message: the model has moved on.
43
- if (message.role === 'assistant' || message.role === 'tool') break
44
- }
45
- history.splice(at, 0, ...blocks)
46
- }
47
-
48
- interface PlacedBlock {
49
- readonly text: string
50
- /** The operator message this block precedes, or the history message it follows. */
51
- at: { readonly before: Message } | { readonly after: Message | undefined }
52
- }
53
-
54
20
  function textOf(message: Message): string {
55
21
  return typeof message.content === 'string' ? message.content : JSON.stringify(message.content)
56
22
  }
57
23
 
58
- /** The operator message the model is about to answer, when there is one. */
59
- function pendingOperatorMessage(history: readonly Message[]): Message | undefined {
60
- for (let i = history.length - 1; i >= 0; i--) {
61
- const message = history[i] as Message
62
- if (isOperatorUserMessage(message)) return message
63
- if (message.role === 'assistant' || message.role === 'tool') return undefined
64
- }
65
- return undefined
66
- }
67
-
68
- /** A block whose own text says that a later one replaces it, under the name of what it reports. */
69
- export interface ReplaceableBlock {
70
- readonly key: string
71
- readonly message: Message
72
- }
73
-
74
- /** How many superseded versions of a replaceable block still go with the latest. */
75
- export const EARLIER_VERSIONS_KEPT = 2
76
-
77
- interface VersionedBlock extends PlacedBlock {
78
- readonly message: Message
79
- }
80
-
81
24
  /**
82
- * Where a turn's request-only data sits, so it stays put from call to call.
83
- *
84
- * What a block says is the step's own business: a block it offers again with
85
- * the same text is the same block, and it keeps the place it first had; a
86
- * block it no longer offers is withdrawn, so corrected data never lingers.
87
- * A block seen for the first time goes before the operator's message when that
88
- * message is what the model is answering, and otherwise after the history of
89
- * that moment. So the requests of a turn share their opening up to the first
90
- * block that changed, and a caching driver keeps reading the same prefix
91
- * instead of re-reading the turn from the operator's message on.
25
+ * Put a request's own data into it: after everything the history holds, in
26
+ * the order offered, each distinct text once.
92
27
  *
93
- * A block that says of itself that a later one replaces it (the file
94
- * evidence) is never taken back. When its text changes, the earlier text stays
95
- * where it went and the new text follows the history of that moment, which is
96
- * how the block itself tells the model to read it; when it stops holding, a
97
- * short block says so. Only the latest version and the last
98
- * `EARLIER_VERSIONS_KEPT` before it are carried, and an earlier version whose
99
- * place a compaction rewrote is dropped, so the stale text stays small. Until
100
- * a version is dropped no request of the turn rewrites the one before it.
28
+ * Request-only data is what the model needs for this request alone (a note
29
+ * that something is unavailable, the work still running). It is re-placed on
30
+ * every call and always last, so the history before it never changes shape
31
+ * from one call to the next and a caching driver, which ends its breakpoint
32
+ * before the first such block, covers the whole history on every call. What
33
+ * the model should keep reading in later requests is recorded as turn context
34
+ * instead (`PrepareStepResult.recordedContext`), and the loop records what it
35
+ * learns about files and finished work the same way.
101
36
  *
102
- * One carry per turn. A position whose message has left the history (a
103
- * compaction rewrote it) is given up and the block follows the history.
37
+ * `request` is the projected history. `recorded` are entries the loop has just
38
+ * recorded: they join the history at the end of this call, so they go ahead
39
+ * of the first request-only block already in `request` (`tail` of them, at the
40
+ * end), which is where the next request will find them.
104
41
  */
105
- export class TurnContextCarry {
106
- private placed = new Map<string, PlacedBlock>()
107
- private readonly versions = new Map<string, VersionedBlock[]>()
108
-
109
- /**
110
- * Put `blocks` and the `replaceable` ones into `request`, the projected copy
111
- * of `history` (same length and order). `end` is the last message of the
112
- * turn's own history. `retractions` says, per replaceable key, what to
113
- * write when an earlier block of that key no longer holds.
114
- */
115
- place(
116
- request: Message[],
117
- history: readonly Message[],
118
- end: Message | undefined,
119
- blocks: readonly Message[],
120
- replaceable: readonly ReplaceableBlock[] = [],
121
- retractions: Readonly<Record<string, Message>> = {},
122
- ): void {
123
- const index = (message: Message | undefined) =>
124
- message ? history.lastIndexOf(message) : history.length - 1
125
- const operator = pendingOperatorMessage(history)
126
- const positionOf = (slot: PlacedBlock) =>
127
- 'before' in slot.at ? index(slot.at.before) : index(slot.at.after) + 1
128
- const anchorOf = (slot: PlacedBlock) => ('before' in slot.at ? slot.at.before : slot.at.after)
129
- const next = new Map<string, PlacedBlock>()
130
- const inserts: { at: number; message: Message }[] = []
131
- for (const message of blocks) {
132
- const text = textOf(message)
133
- if (next.has(text)) continue
134
- let slot: PlacedBlock | undefined = this.placed.get(text)
135
- if (slot) {
136
- const anchor = anchorOf(slot)
137
- if (anchor && index(anchor) < 0) slot = { text, at: { after: end } }
138
- } else {
139
- slot = { text, at: operator ? { before: operator } : { after: end } }
140
- }
141
- next.set(text, slot)
142
- inserts.push({ at: positionOf(slot), message })
143
- }
144
- this.placed = next
145
-
146
- const offered = new Map(replaceable.map((block) => [block.key, block.message]))
147
- for (const key of new Set([...this.versions.keys(), ...offered.keys()])) {
148
- const held = this.versions.get(key) ?? []
149
- const wanted = offered.get(key) ?? retractions[key]
150
- const last = held.at(-1)
151
- if (wanted !== undefined && (last === undefined || last.text !== textOf(wanted)))
152
- held.push({
153
- text: textOf(wanted),
154
- message: wanted,
155
- // The first version goes where the other blocks go; a later one
156
- // follows the history, after the one it replaces.
157
- at: last === undefined && operator ? { before: operator } : { after: end },
158
- })
159
- // An earlier version whose place a compaction rewrote is given up: the
160
- // request is rewritten at that point anyway, and stacking stale copies
161
- // at the end would only add bulk. The latest version is never given up.
162
- const kept = held.filter((version, i) => {
163
- if (i === held.length - 1) return true
164
- const anchor = anchorOf(version)
165
- return !anchor || index(anchor) >= 0
166
- })
167
- // Only the latest and a few earlier versions are carried, so a long turn
168
- // does not grow by a full copy per change.
169
- kept.splice(0, Math.max(0, kept.length - (EARLIER_VERSIONS_KEPT + 1)))
170
- this.versions.set(key, kept)
171
- for (const version of kept) {
172
- const anchor = anchorOf(version)
173
- if (anchor && index(anchor) < 0) version.at = { after: end }
174
- inserts.push({ at: positionOf(version), message: version.message })
175
- }
176
- }
177
-
178
- // Back to front, so an earlier position is not shifted by a later one;
179
- // blocks at one position keep the order they were offered in.
180
- const order = inserts.map((entry, position) => ({ ...entry, position }))
181
- order.sort((a, b) => b.at - a.at || b.position - a.position)
182
- for (const entry of order) request.splice(entry.at, 0, entry.message)
42
+ export function placeRequestContext(
43
+ request: Message[],
44
+ recorded: readonly Message[],
45
+ tail: number,
46
+ blocks: readonly Message[],
47
+ ): void {
48
+ if (recorded.length > 0) request.splice(request.length - tail, 0, ...recorded)
49
+ const seen = new Set<string>()
50
+ for (const message of blocks) {
51
+ const text = textOf(message)
52
+ if (seen.has(text)) continue
53
+ seen.add(text)
54
+ request.push(message)
183
55
  }
184
56
  }
@@ -1,30 +1,30 @@
1
1
  import { resolveContextWindow } from '../../../compaction/context-window.js'
2
- import { estimateMessageTokens } from '../../../compaction/token-estimate.js'
2
+ import { estimateMessageTokens, estimateTextTokens } from '../../../compaction/token-estimate.js'
3
3
  import { NAMZU } from '../../../constants/telemetry/index.js'
4
4
  import { renderSkillsSection } from '../../../persona/assembler.js'
5
+ import { recordedOwnedTaskIds } from '../../../scheduler/completion-inbox.js'
5
6
  import { PreparationContextError } from '../../../turn/preparation-context-error.js'
6
7
  import {
7
8
  type Message,
8
9
  type UserMessage,
9
10
  createSystemMessage,
11
+ turnContextEntries,
10
12
  } from '../../../types/message/index.js'
11
13
  import type { ToolChoice } from '../../../types/provider/chat.js'
12
14
  import type {
13
15
  PrepareStepContext,
14
16
  PrepareStepResult,
17
+ RecordedContextItem,
15
18
  StepResult,
16
19
  StepVeto,
17
20
  } from '../../../types/session/index.js'
18
21
  import type { Skill } from '../../../types/skills/index.js'
19
22
  import { toErrorMessage } from '../../../utils/error.js'
20
23
  import { createCallbackInference } from '../callback-inference.js'
24
+ import { recordFileEvidence } from '../file-evidence-context.js'
21
25
  import { measureContext } from './phases/compaction.js'
22
26
  import type { IterationContext } from './phases/index.js'
23
- import {
24
- type ReplaceableBlock,
25
- placeBeforeLatestOperatorMessage,
26
- stepContextMessage,
27
- } from './step-context.js'
27
+ import { stepContextMessage } from './step-context.js'
28
28
 
29
29
  /**
30
30
  * How the next request is shaped: admission, preparation, and the context
@@ -48,57 +48,68 @@ export interface StepShaping {
48
48
 
49
49
  export { stepContextMessage }
50
50
 
51
- /** Derived after request projection; never accumulates in canonical history or replaces operator intent. */
52
- export function appendWorkContext(
53
- shaping: StepShaping,
54
- messages: Message[],
55
- stepNumber: number,
56
- prepared: PrepareStepResult,
57
- ): void {
58
- // Per-turn data goes in front of the operator's new message while that is
59
- // what the model is answering, like the other blocks of request-only data.
60
- placeBeforeLatestOperatorMessage(
61
- messages,
62
- workContextBlocks(shaping, messages, stepNumber, prepared).map((block) => block.message),
63
- )
64
- }
65
-
66
- /** What the two work-context blocks report; each tells the model a later one replaces it. */
51
+ /** The names the two kinds of recorded work context are filed under. */
67
52
  export const OWNED_WORK_KEY = 'owned-work'
68
53
  export const FILE_EVIDENCE_KEY = 'file-evidence'
69
54
 
55
+ /** What the work context says for one request. */
56
+ export interface WorkContext {
57
+ /** Facts that do not change once true, to be kept in the conversation. */
58
+ readonly recorded: RecordedContextItem[]
59
+ /** Facts about now, shown with this request only. */
60
+ readonly requestOnly: Message[]
61
+ }
62
+
70
63
  /**
71
- * The work-context blocks for a request whose projected messages are
72
- * `messages`, each under the name of what it reports.
64
+ * The work context for a request whose projected messages are `messages`.
65
+ *
66
+ * Two kinds of fact, each where it belongs. What holds until something
67
+ * changes it, or never changes, is recorded: the file entries that are new or
68
+ * changed since the last record (with the paths whose entry no longer holds),
69
+ * and each owned task once it has finished. What is true only now, the tasks
70
+ * still running, goes with this request alone. Each text is admitted whole or
71
+ * not at all, within the room the request has left.
73
72
  */
74
- export function workContextBlocks(
73
+ export function workContext(
75
74
  shaping: StepShaping,
76
75
  messages: readonly Message[],
77
76
  stepNumber: number,
78
77
  prepared: PrepareStepResult,
79
- ): ReplaceableBlock[] {
78
+ ): WorkContext {
80
79
  const { ctx } = shaping
80
+ const held = (key: string) => turnContextEntries(ctx.recorder.messages, key)
81
+ const inbox = ctx.completionInbox
81
82
 
82
- const contributions = (
83
- [
84
- [OWNED_WORK_KEY, ctx.completionInbox?.describeOwnedWork()],
85
- [FILE_EVIDENCE_KEY, ctx.toolExecutor.describeFileEvidence(messages)],
86
- ] as [string, string | undefined][]
87
- ).filter((entry): entry is [string, string] => Boolean(entry[1]))
88
- if (contributions.length === 0) return []
89
- const placed: ReplaceableBlock[] = []
83
+ const contributions: { content: string | undefined; key?: string }[] = [
84
+ { content: inbox?.describeRunningWork() },
85
+ {
86
+ content: inbox?.describeSettledWork(recordedOwnedTaskIds(held(OWNED_WORK_KEY))),
87
+ key: OWNED_WORK_KEY,
88
+ },
89
+ {
90
+ content: recordFileEvidence(
91
+ ctx.toolExecutor.fileEvidenceEntries(messages),
92
+ held(FILE_EVIDENCE_KEY),
93
+ ),
94
+ key: FILE_EVIDENCE_KEY,
95
+ },
96
+ ]
97
+ const present = contributions.filter((entry) => Boolean(entry.content))
98
+ const work: WorkContext = { recorded: [], requestOnly: [] }
99
+ if (present.length === 0) return work
90
100
  let room = stepContext(shaping, stepNumber, prepared).contextBudget?.remainingTokens ?? 0
91
101
  // Leave room for the actual task; admit whole contributions, never dangling partial references.
92
- if (room < 1_500) return []
93
- for (const [key, content] of contributions) {
102
+ if (room < 1_500) return work
103
+ for (const { content, key } of present) {
94
104
  if (!content || content.length > 8_000) continue
95
105
  const message = stepContextMessage(content)
96
106
  const tokens = estimateMessageTokens(message)
97
107
  if (tokens > Math.min(2_000, room - 1_000)) continue
98
- placed.push({ key, message })
108
+ if (key) work.recorded.push({ key, text: content })
109
+ else work.requestOnly.push(message)
99
110
  room -= tokens
100
111
  }
101
- return placed
112
+ return work
102
113
  }
103
114
 
104
115
  export function stepContext(
@@ -122,7 +133,8 @@ export function stepContext(
122
133
  const preamble = [prepared.system, skills].filter(Boolean).join('\n\n')
123
134
  const preparedTokens =
124
135
  (preamble ? estimateMessageTokens(createSystemMessage(preamble)) : 0) +
125
- (prepared.context ? estimateMessageTokens(stepContextMessage(prepared.context)) : 0)
136
+ (prepared.context ? estimateMessageTokens(stepContextMessage(prepared.context)) : 0) +
137
+ (prepared.recordedContext ?? []).reduce((sum, item) => sum + estimateTextTokens(item.text), 0)
126
138
  const responseReserve = Math.min(
127
139
  prepared.maxResponseTokens ?? ctx.turnConfig.maxResponseTokens ?? Math.floor(window.tokens / 4),
128
140
  Math.floor(window.tokens / 4),
@@ -180,6 +192,7 @@ export async function prepareStep(
180
192
  model?: string
181
193
  system?: string
182
194
  context?: string
195
+ recordedContext?: readonly RecordedContextItem[]
183
196
  skills?: readonly Skill[]
184
197
  temperature?: number
185
198
  maxResponseTokens?: number
@@ -206,7 +219,16 @@ export async function prepareStep(
206
219
  ...stepContext(shaping, stepNumber, result),
207
220
  generateText: inference.generateText,
208
221
  })
209
- if (decided) result = { ...result, ...decided }
222
+ if (decided) {
223
+ // Recorded context adds up across stages: each stage files its own
224
+ // keys, and one stage must not erase what an earlier one recorded.
225
+ const recorded = [...(result.recordedContext ?? []), ...(decided.recordedContext ?? [])]
226
+ result = {
227
+ ...result,
228
+ ...decided,
229
+ ...(recorded.length > 0 ? { recordedContext: recorded } : {}),
230
+ }
231
+ }
210
232
  await selectContextModel(shaping, result.model ?? ctx.turnConfig.model)
211
233
  } catch (err) {
212
234
  // Skipped, and the rest still run: one broken concern must
@@ -242,6 +264,7 @@ export async function prepareStep(
242
264
  model?: string
243
265
  system?: string
244
266
  context?: string
267
+ recordedContext?: readonly RecordedContextItem[]
245
268
  skills?: readonly Skill[]
246
269
  temperature?: number
247
270
  maxResponseTokens?: number
@@ -279,6 +302,7 @@ export async function prepareStep(
279
302
  if (result.model !== undefined) prepared.model = result.model
280
303
  if (result.system !== undefined) prepared.system = result.system
281
304
  if (result.context !== undefined) prepared.context = result.context
305
+ if (result.recordedContext !== undefined) prepared.recordedContext = result.recordedContext
282
306
  if (result.skills !== undefined) prepared.skills = result.skills
283
307
  if (result.temperature !== undefined) prepared.temperature = result.temperature
284
308
  if (result.maxResponseTokens !== undefined) {
@@ -30,7 +30,7 @@ import type {
30
30
  ReasoningBlock,
31
31
  ToolInputError,
32
32
  } from '../../../types/message/index.js'
33
- import { ProviderError } from '../../../types/provider/errors.js'
33
+ import { ProviderError, classifyProviderError } from '../../../types/provider/errors.js'
34
34
  import type {
35
35
  ChatCompletionResponse,
36
36
  LLMProvider,
@@ -298,7 +298,7 @@ export async function* streamProviderTurn(
298
298
  let streamedLength = 0
299
299
  const toolBuckets = new Map<number, ToolCallBucket>()
300
300
  // Places a fragment that came without an index; see `ToolCallIndexer`.
301
- const toolIndexer = new ToolCallIndexer()
301
+ let toolIndexer = new ToolCallIndexer()
302
302
  // The call the model's latest output went to, or `undefined` once text,
303
303
  // reasoning or a hosted tool followed it. An output limit, a content
304
304
  // filter or a dropped stream stops the response wherever it is, so this
@@ -397,6 +397,36 @@ export async function* streamProviderTurn(
397
397
  })
398
398
  : undefined
399
399
 
400
+ /**
401
+ * Drop everything the failed attempt wrote, so the request starts over under
402
+ * the same message: after a restarting retry, or a swap that says the same.
403
+ * The failed attempt's text, reasoning and tool calls are void. A call is
404
+ * restarted only while still being written and nothing runs before the
405
+ * response settles, so a half-written call never reaches the model.
406
+ */
407
+ const discardAttempt = () => {
408
+ toolBuckets.clear()
409
+ toolIndexer = new ToolCallIndexer()
410
+ framingViolated = false
411
+ text = new StreamTextAccumulator()
412
+ reasoningBuckets.clear()
413
+ citations.length = 0
414
+ replayState = undefined
415
+ id = ''
416
+ finishReason = 'stop'
417
+ reportedFinishReason = undefined
418
+ finishDetail = undefined
419
+ streamedLength = 0
420
+ lastOutputCall = undefined
421
+ usage = {
422
+ promptTokens: 0,
423
+ completionTokens: 0,
424
+ totalTokens: 0,
425
+ cachedTokens: 0,
426
+ cacheWriteTokens: 0,
427
+ }
428
+ }
429
+
400
430
  try {
401
431
  for (;;) {
402
432
  const next = it.next()
@@ -426,28 +456,7 @@ export async function* streamProviderTurn(
426
456
  ...(chunk.retry.restart ? { restart: true } : {}),
427
457
  })
428
458
  yield* drainPending()
429
- if (chunk.retry.restart) {
430
- // The failed attempt's text and reasoning are void: the request
431
- // starts over under the same message. The decorator never
432
- // restarts once a tool call began, so no bucket is left behind.
433
- text = new StreamTextAccumulator()
434
- reasoningBuckets.clear()
435
- citations.length = 0
436
- replayState = undefined
437
- id = ''
438
- finishReason = 'stop'
439
- reportedFinishReason = undefined
440
- finishDetail = undefined
441
- streamedLength = 0
442
- lastOutputCall = undefined
443
- usage = {
444
- promptTokens: 0,
445
- completionTokens: 0,
446
- totalTokens: 0,
447
- cachedTokens: 0,
448
- cacheWriteTokens: 0,
449
- }
450
- }
459
+ if (chunk.retry.restart) discardAttempt()
451
460
  continue
452
461
  }
453
462
 
@@ -472,8 +481,10 @@ export async function* streamProviderTurn(
472
481
  code: chunk.fallback.code,
473
482
  ...(chunk.fallback.status !== undefined ? { status: chunk.fallback.status } : {}),
474
483
  reason: chunk.fallback.reason,
484
+ ...(chunk.fallback.restart ? { restart: true } : {}),
475
485
  })
476
486
  yield* drainPending()
487
+ if (chunk.fallback.restart) discardAttempt()
477
488
  continue
478
489
  }
479
490
 
@@ -947,10 +958,21 @@ export async function* streamProviderTurn(
947
958
 
948
959
  // Not after a framing violation: the calls it would recover are the ones
949
960
  // the stream was just refused for garbling.
961
+ //
962
+ // Nor when the stream was cut by a connection that may come back and no
963
+ // call came through whole: the retries are spent, the half-written call is
964
+ // not the model's mistake, and telling the model about it would spend a
965
+ // turn on a fault it cannot fix. The failure goes up and the turn pauses.
966
+ const cutByConnection =
967
+ streamError !== undefined &&
968
+ streamCause !== undefined &&
969
+ classifyProviderError(streamCause).retryable
950
970
  const recoveredToolInputFromStreamError =
951
971
  streamError !== undefined &&
952
972
  !framingViolated &&
953
- toolCalls.some((tc) => tc.id && tc.function.name)
973
+ toolCalls.some(
974
+ (tc) => tc.id && tc.function.name && (!cutByConnection || !tc.metadata?.inputError),
975
+ )
954
976
  const effectiveFinishReason: ChatCompletionResponse['finishReason'] =
955
977
  recoveredToolInputFromStreamError ? 'tool_calls' : finishReason
956
978
 
@@ -43,6 +43,7 @@ import { generateCheckpointId, generateTurnId } from '../../utils/id.js'
43
43
  import { errorAttributes } from '../../utils/log/exception.js'
44
44
  import type { Logger } from '../../utils/logger.js'
45
45
  import { AUTO_APPROVE_POLICY_NAME, createSessionApprovalPolicy } from './approval-policy.js'
46
+ import { readCallsThatNeverStarted } from './calls-that-never-started.js'
46
47
  import { type TurnContext, TurnContextFactory } from './context.js'
47
48
  import { EventTranslator } from './events.js'
48
49
  import type { QueryParams } from './index.js'
@@ -681,9 +682,17 @@ export async function prepareTurn(params: QueryParams): Promise<PreparedTurn> {
681
682
  pinCompaction: true,
682
683
  })),
683
684
  ])
684
- const initialRepair = params.resumeFromCheckpoint
685
+ let initialRepair = params.resumeFromCheckpoint
685
686
  ? { messages: projectedInitialMessages, report: undefined }
686
687
  : repairToolMessageHistory(projectedInitialMessages)
688
+ if (initialRepair.report && initialRepair.report.syntheticToolResultsInserted > 0) {
689
+ // A call that was waiting for approval when the session ended never ran;
690
+ // the model is told so rather than that its outcome is unknown.
691
+ const neverRan = await readCallsThatNeverStarted(storage.log)
692
+ if (neverRan.size > 0) {
693
+ initialRepair = repairToolMessageHistory(projectedInitialMessages, { neverRan })
694
+ }
695
+ }
687
696
  const initialMessages = initialRepair.messages
688
697
  if (initialRepair.report && toolHistoryRepairChanged(initialRepair.report)) {
689
698
  pendingHistoryRepairs.push({