@namzu/sdk 73.0.0 → 74.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 (208) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +34 -34
  3. package/dist/authorization/protected-paths.d.ts +7 -0
  4. package/dist/authorization/protected-paths.d.ts.map +1 -1
  5. package/dist/authorization/protected-paths.js +7 -0
  6. package/dist/authorization/protected-paths.js.map +1 -1
  7. package/dist/authorization/readonly-commands.d.ts +23 -0
  8. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  9. package/dist/authorization/readonly-commands.js +89 -3
  10. package/dist/authorization/readonly-commands.js.map +1 -1
  11. package/dist/authorization/shell-paths.d.ts +8 -0
  12. package/dist/authorization/shell-paths.d.ts.map +1 -1
  13. package/dist/authorization/shell-paths.js +125 -2
  14. package/dist/authorization/shell-paths.js.map +1 -1
  15. package/dist/bridge/acp/permission.d.ts +6 -0
  16. package/dist/bridge/acp/permission.d.ts.map +1 -1
  17. package/dist/bridge/acp/permission.js.map +1 -1
  18. package/dist/bridge/acp/server.d.ts.map +1 -1
  19. package/dist/bridge/acp/server.js +21 -3
  20. package/dist/bridge/acp/server.js.map +1 -1
  21. package/dist/compaction/context-window.d.ts.map +1 -1
  22. package/dist/compaction/context-window.js +11 -0
  23. package/dist/compaction/context-window.js.map +1 -1
  24. package/dist/compaction/manual.d.ts.map +1 -1
  25. package/dist/compaction/manual.js +15 -8
  26. package/dist/compaction/manual.js.map +1 -1
  27. package/dist/compaction/plan.d.ts +2 -1
  28. package/dist/compaction/plan.d.ts.map +1 -1
  29. package/dist/compaction/plan.js +6 -5
  30. package/dist/compaction/plan.js.map +1 -1
  31. package/dist/compaction/retained-images.d.ts +16 -0
  32. package/dist/compaction/retained-images.d.ts.map +1 -0
  33. package/dist/compaction/retained-images.js +113 -0
  34. package/dist/compaction/retained-images.js.map +1 -0
  35. package/dist/compaction/token-estimate.d.ts +8 -3
  36. package/dist/compaction/token-estimate.d.ts.map +1 -1
  37. package/dist/compaction/token-estimate.js +76 -8
  38. package/dist/compaction/token-estimate.js.map +1 -1
  39. package/dist/compaction/tool-result-editing.d.ts.map +1 -1
  40. package/dist/compaction/tool-result-editing.js +15 -8
  41. package/dist/compaction/tool-result-editing.js.map +1 -1
  42. package/dist/constants/acp/index.d.ts +2 -0
  43. package/dist/constants/acp/index.d.ts.map +1 -1
  44. package/dist/constants/acp/index.js +2 -0
  45. package/dist/constants/acp/index.js.map +1 -1
  46. package/dist/pricing/catalogue.generated.d.ts.map +1 -1
  47. package/dist/pricing/catalogue.generated.js +178 -1
  48. package/dist/pricing/catalogue.generated.js.map +1 -1
  49. package/dist/provider/attribution.js +1 -1
  50. package/dist/provider/attribution.js.map +1 -1
  51. package/dist/public-runtime.d.ts +4 -2
  52. package/dist/public-runtime.d.ts.map +1 -1
  53. package/dist/public-runtime.js +7 -1
  54. package/dist/public-runtime.js.map +1 -1
  55. package/dist/rag/embedding.d.ts +5 -1
  56. package/dist/rag/embedding.d.ts.map +1 -1
  57. package/dist/rag/embedding.js +22 -7
  58. package/dist/rag/embedding.js.map +1 -1
  59. package/dist/runtime/query/abandon-turn.d.ts.map +1 -1
  60. package/dist/runtime/query/abandon-turn.js +9 -0
  61. package/dist/runtime/query/abandon-turn.js.map +1 -1
  62. package/dist/runtime/query/compact-session.d.ts +10 -3
  63. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  64. package/dist/runtime/query/compact-session.js +24 -14
  65. package/dist/runtime/query/compact-session.js.map +1 -1
  66. package/dist/runtime/query/index.d.ts.map +1 -1
  67. package/dist/runtime/query/index.js +1 -0
  68. package/dist/runtime/query/index.js.map +1 -1
  69. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  70. package/dist/runtime/query/iteration/index.js +14 -0
  71. package/dist/runtime/query/iteration/index.js.map +1 -1
  72. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  73. package/dist/runtime/query/iteration/phases/compaction.js +60 -5
  74. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  75. package/dist/runtime/query/iteration/phases/context.d.ts +2 -0
  76. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  77. package/dist/runtime/query/iteration/phases/context.js +1 -0
  78. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  79. package/dist/runtime/query/iteration/request-prefix.d.ts +21 -0
  80. package/dist/runtime/query/iteration/request-prefix.d.ts.map +1 -0
  81. package/dist/runtime/query/iteration/request-prefix.js +111 -0
  82. package/dist/runtime/query/iteration/request-prefix.js.map +1 -0
  83. package/dist/runtime/query/review-policy.d.ts +11 -3
  84. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  85. package/dist/runtime/query/review-policy.js +54 -3
  86. package/dist/runtime/query/review-policy.js.map +1 -1
  87. package/dist/sandbox/exec-stdin.d.ts +21 -0
  88. package/dist/sandbox/exec-stdin.d.ts.map +1 -0
  89. package/dist/sandbox/exec-stdin.js +40 -0
  90. package/dist/sandbox/exec-stdin.js.map +1 -0
  91. package/dist/sandbox/file-walk.d.ts +12 -7
  92. package/dist/sandbox/file-walk.d.ts.map +1 -1
  93. package/dist/sandbox/file-walk.js +13 -4
  94. package/dist/sandbox/file-walk.js.map +1 -1
  95. package/dist/sandbox/ignore-matcher.d.ts +1 -0
  96. package/dist/sandbox/ignore-matcher.d.ts.map +1 -1
  97. package/dist/sandbox/ignore-matcher.js.map +1 -1
  98. package/dist/sandbox/ignore-source.js +1 -1
  99. package/dist/sandbox/index.d.ts +3 -2
  100. package/dist/sandbox/index.d.ts.map +1 -1
  101. package/dist/sandbox/index.js +2 -1
  102. package/dist/sandbox/index.js.map +1 -1
  103. package/dist/sandbox/provider/local.d.ts.map +1 -1
  104. package/dist/sandbox/provider/local.js +2 -0
  105. package/dist/sandbox/provider/local.js.map +1 -1
  106. package/dist/session/paths.d.ts +6 -0
  107. package/dist/session/paths.d.ts.map +1 -1
  108. package/dist/session/paths.js +7 -0
  109. package/dist/session/paths.js.map +1 -1
  110. package/dist/session-query/index.d.ts +1 -0
  111. package/dist/session-query/index.d.ts.map +1 -1
  112. package/dist/session-query/index.js +26 -15
  113. package/dist/session-query/index.js.map +1 -1
  114. package/dist/store/evidence/disk.js +3 -1
  115. package/dist/store/evidence/disk.js.map +1 -1
  116. package/dist/store/evidence/index-page.d.ts +1 -0
  117. package/dist/store/evidence/index-page.d.ts.map +1 -1
  118. package/dist/store/evidence/index-page.js +8 -0
  119. package/dist/store/evidence/index-page.js.map +1 -1
  120. package/dist/store/memory/operation-lock.d.ts.map +1 -1
  121. package/dist/store/memory/operation-lock.js +15 -1
  122. package/dist/store/memory/operation-lock.js.map +1 -1
  123. package/dist/store/session-log/core.d.ts.map +1 -1
  124. package/dist/store/session-log/core.js +23 -0
  125. package/dist/store/session-log/core.js.map +1 -1
  126. package/dist/tools/builtins/computer-use-image.d.ts +9 -0
  127. package/dist/tools/builtins/computer-use-image.d.ts.map +1 -1
  128. package/dist/tools/builtins/computer-use-image.js +21 -0
  129. package/dist/tools/builtins/computer-use-image.js.map +1 -1
  130. package/dist/tools/builtins/computer-use.d.ts +1 -9
  131. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  132. package/dist/tools/builtins/computer-use.js +2 -22
  133. package/dist/tools/builtins/computer-use.js.map +1 -1
  134. package/dist/toolsets/manager.d.ts +7 -3
  135. package/dist/toolsets/manager.d.ts.map +1 -1
  136. package/dist/toolsets/manager.js +7 -3
  137. package/dist/toolsets/manager.js.map +1 -1
  138. package/dist/types/common/index.d.ts +20 -0
  139. package/dist/types/common/index.d.ts.map +1 -1
  140. package/dist/types/common/index.js +4 -1
  141. package/dist/types/common/index.js.map +1 -1
  142. package/dist/types/hitl/index.d.ts +11 -0
  143. package/dist/types/hitl/index.d.ts.map +1 -1
  144. package/dist/types/hitl/index.js.map +1 -1
  145. package/dist/types/rag/embedding.d.ts +4 -0
  146. package/dist/types/rag/embedding.d.ts.map +1 -1
  147. package/dist/types/sandbox/index.d.ts +19 -0
  148. package/dist/types/sandbox/index.d.ts.map +1 -1
  149. package/dist/types/sandbox/index.js.map +1 -1
  150. package/dist/types/session/events.d.ts +48 -0
  151. package/dist/types/session/events.d.ts.map +1 -1
  152. package/dist/types/session/events.js.map +1 -1
  153. package/dist/types/session/records.d.ts +2 -0
  154. package/dist/types/session/records.d.ts.map +1 -1
  155. package/dist/types/session/records.js +9 -0
  156. package/dist/types/session/records.js.map +1 -1
  157. package/dist/utils/cost.d.ts +15 -0
  158. package/dist/utils/cost.d.ts.map +1 -1
  159. package/dist/utils/cost.js +24 -1
  160. package/dist/utils/cost.js.map +1 -1
  161. package/package.json +2 -2
  162. package/src/authorization/protected-paths.ts +7 -0
  163. package/src/authorization/readonly-commands.ts +85 -3
  164. package/src/authorization/shell-paths.ts +141 -3
  165. package/src/bridge/acp/permission.ts +6 -0
  166. package/src/bridge/acp/server.ts +20 -1
  167. package/src/compaction/context-window.ts +11 -0
  168. package/src/compaction/manual.ts +23 -8
  169. package/src/compaction/plan.ts +11 -5
  170. package/src/compaction/retained-images.ts +130 -0
  171. package/src/compaction/token-estimate.ts +86 -8
  172. package/src/compaction/tool-result-editing.ts +20 -8
  173. package/src/constants/acp/index.ts +2 -0
  174. package/src/pricing/catalogue.generated.ts +178 -1
  175. package/src/pricing/rates.source.json +155 -2
  176. package/src/provider/attribution.ts +1 -1
  177. package/src/public-runtime.ts +21 -0
  178. package/src/rag/embedding.ts +23 -7
  179. package/src/runtime/query/abandon-turn.ts +9 -0
  180. package/src/runtime/query/compact-session.ts +50 -15
  181. package/src/runtime/query/index.ts +1 -0
  182. package/src/runtime/query/iteration/index.ts +14 -0
  183. package/src/runtime/query/iteration/phases/compaction.ts +77 -5
  184. package/src/runtime/query/iteration/phases/context.ts +3 -0
  185. package/src/runtime/query/iteration/request-prefix.ts +161 -0
  186. package/src/runtime/query/review-policy.ts +79 -11
  187. package/src/sandbox/exec-stdin.ts +54 -0
  188. package/src/sandbox/file-walk.ts +25 -18
  189. package/src/sandbox/ignore-matcher.ts +1 -0
  190. package/src/sandbox/ignore-source.ts +1 -1
  191. package/src/sandbox/index.ts +8 -2
  192. package/src/sandbox/provider/local.ts +2 -0
  193. package/src/session/paths.ts +9 -0
  194. package/src/session-query/index.ts +23 -14
  195. package/src/store/evidence/disk.ts +3 -1
  196. package/src/store/evidence/index-page.ts +11 -0
  197. package/src/store/memory/operation-lock.ts +19 -1
  198. package/src/store/session-log/core.ts +26 -0
  199. package/src/tools/builtins/computer-use-image.ts +20 -0
  200. package/src/tools/builtins/computer-use.ts +1 -20
  201. package/src/toolsets/manager.ts +7 -3
  202. package/src/types/common/index.ts +26 -1
  203. package/src/types/hitl/index.ts +11 -0
  204. package/src/types/rag/embedding.ts +7 -0
  205. package/src/types/sandbox/index.ts +19 -0
  206. package/src/types/session/events.ts +49 -0
  207. package/src/types/session/records.ts +14 -0
  208. package/src/utils/cost.ts +44 -1
@@ -16,8 +16,11 @@ import {
16
16
  readCumulativeDropped,
17
17
  readFoldedHistory,
18
18
  } from '../../manager/session/turn-recorder.js'
19
- import type { SessionLog } from '../../store/session-log/index.js'
20
- import { DiskSessionLog } from '../../store/session-log/index.js'
19
+ import {
20
+ DiskSessionLog,
21
+ type SessionLease,
22
+ type SessionLog,
23
+ } from '../../store/session-log/index.js'
21
24
  import { accumulateTokenUsage } from '../../types/common/index.js'
22
25
  import { NamzuError } from '../../types/errors/index.js'
23
26
  import type { MessageId, SessionId } from '../../types/ids/index.js'
@@ -50,6 +53,12 @@ export interface CompactSessionParams
50
53
  * which always stops it.
51
54
  */
52
55
  readonly preparedSummary?: 'only' | false
56
+ /**
57
+ * Close a turn whose writer is gone before a manual pass, keeping its
58
+ * recorded messages. Ignored for idle passes. Running and paused turns
59
+ * are always refused.
60
+ */
61
+ readonly abandonInterrupted?: boolean
53
62
  /** Where to find the session's log, and the lease to append under. */
54
63
  readonly locator?: SessionLocatorOptions
55
64
  }
@@ -60,19 +69,25 @@ export interface CompactSessionParams
60
69
  * with no `turnId`: the messages the pass kept are named by id, the summary
61
70
  * is recorded in full, and the shed messages stay in the log for audit.
62
71
  *
63
- * Refused while a turn is active (`TurnInProgressError`). `null` when there
64
- * was nothing to compact; nothing is appended then.
72
+ * Refused while a turn is active (`TurnInProgressError`), unless a manual
73
+ * pass opts into closing an interrupted turn. `null` when there was nothing
74
+ * to compact.
65
75
  */
66
76
  export async function compactSession(
67
77
  params: CompactSessionParams,
68
78
  ): Promise<CompactionResult | null> {
69
- const { sessionId, locator = {}, trigger = 'manual', hooks, preparedSummary, ...input } = params
79
+ const {
80
+ sessionId,
81
+ locator = {},
82
+ trigger = 'manual',
83
+ hooks,
84
+ preparedSummary,
85
+ abandonInterrupted,
86
+ ...input
87
+ } = params
70
88
  const log = await locateSessionLog(sessionId, locator)
71
89
  return withSessionLease(log, locator.lease, async (lease) => {
72
- const active = await log.activeTurn({ lease })
73
- if (active) {
74
- throw new TurnInProgressError({ sessionId, activeTurnId: active.turnId, state: active.state })
75
- }
90
+ await prepareCompaction(log, lease, trigger === 'manual' && abandonInterrupted)
76
91
  // One summary at a time. A host compacting an idle conversation takes the
77
92
  // summary prepared ahead when it is still valid (or waits for the one being
78
93
  // written); any other pass stops it first.
@@ -147,18 +162,15 @@ export interface CompactSessionRangeParams extends CompactSessionParams {
147
162
  * context (a compaction may already have folded it away), and
148
163
  * `invalid_config` when a boundary would split a tool call from its result.
149
164
  * `null` when the span holds nothing worth summarising; nothing is appended
150
- * then. Refused while a turn is active (`TurnInProgressError`).
165
+ * then except to close an interrupted turn when explicitly requested.
151
166
  */
152
167
  export async function compactSessionRange(
153
168
  params: CompactSessionRangeParams,
154
169
  ): Promise<CompactionResult | null> {
155
- const { sessionId, locator = {}, from, until, hooks, ...input } = params
170
+ const { sessionId, locator = {}, from, until, hooks, abandonInterrupted, ...input } = params
156
171
  const log = await locateSessionLog(sessionId, locator)
157
172
  return withSessionLease(log, locator.lease, async (lease) => {
158
- const active = await log.activeTurn({ lease })
159
- if (active) {
160
- throw new TurnInProgressError({ sessionId, activeTurnId: active.turnId, state: active.state })
161
- }
173
+ await prepareCompaction(log, lease, abandonInterrupted)
162
174
  // One summary at a time: a pass asked for between turns stops one being prepared.
163
175
  const store = precomputeStoreFor(sessionId)
164
176
  const owed = [...store.drainUnbooked(), ...(await store.cancel())]
@@ -216,6 +228,29 @@ export async function compactSessionRange(
216
228
  })
217
229
  }
218
230
 
231
+ /** Check and close an interrupted turn under the same lease used for compaction. */
232
+ async function prepareCompaction(
233
+ log: SessionLog,
234
+ lease: SessionLease,
235
+ abandonInterrupted?: boolean,
236
+ ): Promise<void> {
237
+ const active = await log.activeTurn({ lease })
238
+ if (!active) return
239
+ if (active.state === 'interrupted' && abandonInterrupted) {
240
+ await log.abandonTurn(
241
+ lease,
242
+ active.turnId,
243
+ 'The reply was interrupted before manual compaction.',
244
+ )
245
+ return
246
+ }
247
+ throw new TurnInProgressError({
248
+ sessionId: log.sessionId,
249
+ activeTurnId: active.turnId,
250
+ state: active.state,
251
+ })
252
+ }
253
+
219
254
  /**
220
255
  * Run a between-turns pass that owes a ledger what prepared summaries spent
221
256
  * (one this pass stopped, one that outlived its turn): the cost joins the
@@ -2109,6 +2109,7 @@ export async function* query(params: QueryParams): AsyncGenerator<SessionEvent,
2109
2109
  ...(params.durableInbound ? { durableInbound: params.durableInbound } : {}),
2110
2110
  ...(params.resumeFromCheckpoint ? { resumedInput: queuedForThisRun } : {}),
2111
2111
  ...(params.waitForInbound ? { waitForInbound: params.waitForInbound } : {}),
2112
+ ...(params.waitForOperator ? { waitForOperator: params.waitForOperator } : {}),
2112
2113
  ...(params.projectInstructionContext
2113
2114
  ? { projectInstructionContext: params.projectInstructionContext }
2114
2115
  : {}),
@@ -136,6 +136,7 @@ import {
136
136
  streamWithProviderRejectedImageRecovery,
137
137
  } from './provider-rejected-image.js'
138
138
  import { appendRecordedContext } from './recorded-context.js'
139
+ import { digestRequestPrefix } from './request-prefix.js'
139
140
  import { type MediaRemoval, RequestRepair } from './request-repair.js'
140
141
  import { placeRequestContext } from './step-context.js'
141
142
  import {
@@ -1519,6 +1520,19 @@ export class IterationOrchestrator {
1519
1520
  ...(response.usage.cacheMiss !== undefined
1520
1521
  ? { cacheMiss: response.usage.cacheMiss }
1521
1522
  : {}),
1523
+ requestPrefix: digestRequestPrefix({
1524
+ conversation: recorder.sessionId,
1525
+ model: stepModel,
1526
+ tools: llmTools,
1527
+ messages,
1528
+ wire: response.usage.requestShape,
1529
+ params: {
1530
+ effort: stepEffort,
1531
+ speed: turnConfig.speed,
1532
+ thinking: turnConfig.thinking,
1533
+ choice: step.toolChoice,
1534
+ },
1535
+ }),
1522
1536
  ...contextFigures,
1523
1537
  })
1524
1538
 
@@ -33,6 +33,7 @@ import {
33
33
  keptInstructionFiles,
34
34
  renderRestoredContext,
35
35
  } from '../../../../compaction/restore.js'
36
+ import { fitRetainedImages } from '../../../../compaction/retained-images.js'
36
37
  import { findRetainedIndices } from '../../../../compaction/retention.js'
37
38
  import { serializeState } from '../../../../compaction/serializer.js'
38
39
  import {
@@ -41,7 +42,10 @@ import {
41
42
  collectRevealedTools,
42
43
  isCompactionMessage,
43
44
  } from '../../../../compaction/summary.js'
44
- import { estimateMessagesTokens } from '../../../../compaction/token-estimate.js'
45
+ import {
46
+ estimateMessagesTokens,
47
+ estimateMessagesTokensForModel,
48
+ } from '../../../../compaction/token-estimate.js'
45
49
  import { clearStaleToolResults } from '../../../../compaction/tool-result-editing.js'
46
50
  import { buildVerifiedSummaryWithBoundedProvider } from '../../../../compaction/verifier.js'
47
51
  import type { CompactionConfig } from '../../../../config/runtime.js'
@@ -131,7 +135,12 @@ function estimateToolCatalogTokens(ctx: IterationContext): number {
131
135
  }
132
136
 
133
137
  function estimateTokens(ctx: IterationContext): number {
134
- return estimateMessagesTokens(ctx.recorder.messages) + estimateToolCatalogTokens(ctx)
138
+ return (
139
+ estimateMessagesTokensForModel(
140
+ ctx.recorder.messages,
141
+ ctx.contextModel ?? ctx.turnConfig.model,
142
+ ) + estimateToolCatalogTokens(ctx)
143
+ )
135
144
  }
136
145
 
137
146
  type ToolResultClearPlan = Extract<CompactionPlan, { kind: 'cleared' }>
@@ -366,7 +375,12 @@ export function measureContext(ctx: IterationContext): {
366
375
  if (reported !== undefined && reported > 0) {
367
376
  const measuredThrough = ctx.recorder.lastPromptMessageCount ?? ctx.recorder.messages.length
368
377
  const appended = ctx.recorder.messages.slice(measuredThrough)
369
- return { tokens: reported + estimateMessagesTokens(appended), source: 'provider' }
378
+ return {
379
+ tokens:
380
+ reported +
381
+ estimateMessagesTokensForModel(appended, ctx.contextModel ?? ctx.turnConfig.model),
382
+ source: 'provider',
383
+ }
370
384
  }
371
385
  return { tokens: estimateTokens(ctx), source: 'estimate' }
372
386
  }
@@ -1147,7 +1161,49 @@ async function runCompactionCheckInner(
1147
1161
  return
1148
1162
  }
1149
1163
  }
1164
+ const fitWithoutSummary = async (candidate: readonly Message[]): Promise<boolean> => {
1165
+ if (options?.preparedOnly) return false
1166
+ const copy = [...candidate]
1167
+ const fitted = fitRetainedImages(
1168
+ copy,
1169
+ Math.floor(budget * config.resetThreshold) - estimateToolCatalogTokens(ctx),
1170
+ model,
1171
+ )
1172
+ if (fitted === copy) return false
1173
+
1174
+ const live = ctx.recorder.messages
1175
+ await recordShed(ctx, live, fitted, pass.reason)
1176
+ installMessages(live, fitted)
1177
+ ctx.recorder.clearLastPromptTokens?.()
1178
+ const tokensAfter = estimateTokens(ctx)
1179
+ const durationMs = Math.max(0, Math.round(performance.now() - startedAt))
1180
+ ctx.recorder.noteCompaction?.({
1181
+ trigger: 'auto',
1182
+ tokensBefore: estimatedTokens,
1183
+ tokensAfter,
1184
+ durationMs,
1185
+ })
1186
+ await ctx.emitEvent?.({
1187
+ type: 'compaction_completed',
1188
+ turnId: ctx.recorder.turnId,
1189
+ iteration: ctx.recorder.currentIteration,
1190
+ messagesBefore: live.length,
1191
+ messagesAfter: live.length,
1192
+ tokensBefore: estimatedTokens,
1193
+ tokensAfter,
1194
+ measuredBy: measured.source,
1195
+ contextWindowTokens: budget,
1196
+ windowSource: window.source,
1197
+ reachedResetThreshold: tokensAfter / budget <= config.resetThreshold,
1198
+ trigger: 'auto',
1199
+ durationMs,
1200
+ })
1201
+ await emitContextUsageSnapshot(ctx, tokensAfter, budget, window.source)
1202
+ breaker?.recordRelief()
1203
+ return true
1204
+ }
1150
1205
  const clearPlan = planCompaction({
1206
+ model,
1151
1207
  messages: ctx.recorder.messages,
1152
1208
  config,
1153
1209
  contextWindowTokens: budget,
@@ -1176,6 +1232,7 @@ async function runCompactionCheckInner(
1176
1232
  const stagedClear = clearPlan.kind === 'cleared' ? clearPlan : undefined
1177
1233
  const messages = stagedClear?.messages ?? ctx.recorder.messages
1178
1234
  const plan = planCompaction({
1235
+ model,
1179
1236
  messages,
1180
1237
  config,
1181
1238
  contextWindowTokens: budget,
@@ -1186,6 +1243,7 @@ async function runCompactionCheckInner(
1186
1243
  })
1187
1244
 
1188
1245
  if (plan.kind !== 'plan') {
1246
+ if (await fitWithoutSummary(messages)) return
1189
1247
  // One log line per reason, with the fields each one was already
1190
1248
  // reporting. The planner names the reason; what it means to an
1191
1249
  // operator reading a turn is this file's to say.
@@ -1440,7 +1498,17 @@ async function runCompactionCheckInner(
1440
1498
  },
1441
1499
  )
1442
1500
 
1443
- const newMessages = [...preservedSystem, compactionMessage, ...retainedOlder, ...recentMessages]
1501
+ const newMessages = fitRetainedImages(
1502
+ [...preservedSystem, compactionMessage, ...retainedOlder, ...recentMessages],
1503
+ Math.floor(budget * config.resetThreshold) - estimateToolCatalogTokens(ctx),
1504
+ model,
1505
+ config.keepRecentTokens === undefined
1506
+ ? undefined
1507
+ : {
1508
+ start: preservedSystem.length + 1 + retainedOlder.length,
1509
+ tokens: config.keepRecentTokens,
1510
+ },
1511
+ )
1444
1512
 
1445
1513
  // OPAQUE survival guard: the pinned working-memory slot is a
1446
1514
  // leading system message, so it is kept in `preservedSystem` (the compaction
@@ -1471,7 +1539,11 @@ async function runCompactionCheckInner(
1471
1539
  // comparing provider usage against an estimate or trusting message count.
1472
1540
  // When a clear was staged, require the summary itself to improve on it;
1473
1541
  // otherwise publish the useful clear without consuming its savings.
1474
- if (estimateMessagesTokens(newMessages) >= estimateMessagesTokens(messages)) {
1542
+ if (
1543
+ estimateMessagesTokensForModel(newMessages, model) >=
1544
+ estimateMessagesTokensForModel(messages, model)
1545
+ ) {
1546
+ if (await fitWithoutSummary(messages)) return
1475
1547
  if (stagedClear && stagedClear.reclaimedTokens > 0) {
1476
1548
  await commitToolResultClear(ctx, stagedClear, budget, window.source, pass.reason)
1477
1549
  } else {
@@ -269,6 +269,8 @@ export interface IterationContext {
269
269
  readonly resumedInput?: readonly import('../../../../types/message/index.js').Message[]
270
270
  /** Observes pending input without draining it; abort releases the waiter. */
271
271
  readonly waitForInbound?: (signal: AbortSignal) => Promise<void>
272
+ /** Resolves when the person wrote to this turn; handed to resume handlers, see `ResumeContext`. */
273
+ readonly waitForOperator?: (signal: AbortSignal) => Promise<void>
272
274
  readonly durableInbound?: DurableInboundSource
273
275
 
274
276
  /** Live project policy; separate from human inbound continuation. */
@@ -481,6 +483,7 @@ function resumeContextOf(ctx: IterationContext, scope?: AskScope): ResumeContext
481
483
  return {
482
484
  transcript: () => ctx.recorder.messages,
483
485
  ...(signal ? { signal } : {}),
486
+ ...(ctx.waitForOperator ? { waitForOperator: ctx.waitForOperator } : {}),
484
487
  ...(typeof ctx.toolExecutor?.launchedScripts === 'function'
485
488
  ? {
486
489
  launchedScripts: (callId, line, dialect) =>
@@ -0,0 +1,161 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ import type { RequestWireShape } from '../../../types/common/index.js'
4
+ import type { Message } from '../../../types/message/index.js'
5
+ import type { RequestPrefixDigest } from '../../../types/session/events.js'
6
+
7
+ /**
8
+ * Where a conversation's prompt cache can break, readable from the log
9
+ * without its content.
10
+ *
11
+ * A provider cache reads the start of a request: the model, the tools, the
12
+ * system text, then each message in order. Each of those is reduced here to a
13
+ * short hash, and each request is compared with the one before it for the same
14
+ * conversation. When the cached share of a request falls, the record beside it
15
+ * says whether the model, the tools or the system text moved, or the first
16
+ * earlier message that was not repeated in place. Nothing of the content is
17
+ * kept: a hash of a message says only whether it changed.
18
+ */
19
+
20
+ /** What the next request of a conversation is compared with. */
21
+ interface Earlier {
22
+ readonly model: string
23
+ readonly tools: string
24
+ readonly system: string
25
+ readonly params: string
26
+ /** Hash of the reported wire shape; empty when the driver reported none. */
27
+ readonly wire: string
28
+ readonly items: readonly string[]
29
+ /** How many of the last items were request-only: the next request does not repeat them. */
30
+ readonly tail: number
31
+ }
32
+
33
+ /** Conversations kept, oldest dropped first. A long-running host holds many, a turn needs one. */
34
+ const MAX_CONVERSATIONS = 64
35
+ const earlier = new Map<string, Earlier>()
36
+
37
+ const hex = (text: string, length: number): string =>
38
+ createHash('sha256').update(text).digest('hex').slice(0, length)
39
+
40
+ /** The parts of a message the model is sent; bookkeeping (time, id, cache hints) is left out. */
41
+ function wireOf(message: Message): string {
42
+ const { role, content } = message
43
+ const extra = message as unknown as Record<string, unknown>
44
+ return JSON.stringify([
45
+ role,
46
+ content,
47
+ extra.toolCalls,
48
+ extra.toolCallId,
49
+ extra.textParts,
50
+ extra.attachments,
51
+ (extra.source as { replayState?: unknown } | undefined)?.replayState,
52
+ ])
53
+ }
54
+
55
+ /**
56
+ * A message the next request does not repeat: a request-only note, or the step's own
57
+ * guidance, a system message sent after the history (a system message that opens the
58
+ * conversation is part of the system text instead).
59
+ */
60
+ const isRequestOnly = (message: Message): boolean => {
61
+ if (message.role === 'system') return true
62
+ const source = (message as { source?: { type?: string; kind?: string } }).source
63
+ return source?.type === 'runtime-context' && source.kind === 'step-context'
64
+ }
65
+
66
+ export interface RequestPrefixInput {
67
+ readonly conversation: string
68
+ readonly model: string
69
+ readonly tools: readonly unknown[] | undefined
70
+ readonly messages: readonly Message[]
71
+ /**
72
+ * What the driver reports it sent (see `TokenUsage.requestShape`); undefined when it does
73
+ * not say. The digest is computed from the SDK-level request, before the driver builds the
74
+ * wire request, so this is the only record of what the driver then kept or dropped.
75
+ */
76
+ readonly wire?: RequestWireShape
77
+ /** The request's settings that are not part of its start but can still move a cache (effort, speed, choice). */
78
+ readonly params: unknown
79
+ }
80
+
81
+ export function digestRequestPrefix(input: RequestPrefixInput): RequestPrefixDigest {
82
+ let opening = 0
83
+ while (input.messages[opening]?.role === 'system') opening++
84
+ const system = hex(
85
+ input.messages
86
+ .slice(0, opening)
87
+ .map((message) => String(message.content))
88
+ .join('\n\n'),
89
+ 12,
90
+ )
91
+ const rest = input.messages.slice(opening)
92
+ const items = rest.map((message) => hex(wireOf(message), 6))
93
+ let tail = 0
94
+ while (tail < rest.length && isRequestOnly(rest[rest.length - 1 - tail] as Message)) tail++
95
+ const model = hex(input.model, 12)
96
+ const tools = hex(JSON.stringify(input.tools ?? []), 12)
97
+ const params = hex(JSON.stringify(input.params ?? null), 12)
98
+ // Only these three move `wire`: a developer item appearing for the first time in a
99
+ // healthy conversation is not a change of how the driver talks to the backend.
100
+ const wire = input.wire
101
+ ? hex(
102
+ JSON.stringify([
103
+ input.wire.cacheKey,
104
+ input.wire.sessionHeader,
105
+ input.wire.developerRefused === true,
106
+ ]),
107
+ 12,
108
+ )
109
+ : ''
110
+
111
+ const before = earlier.get(input.conversation)
112
+ let changed: RequestPrefixDigest['changed']
113
+ let firstChangedItem: number | undefined
114
+ if (before) {
115
+ const moved: NonNullable<RequestPrefixDigest['changed']> = []
116
+ if (before.model !== model) moved.push('model')
117
+ if (before.tools !== tools) moved.push('tools')
118
+ if (before.system !== system) moved.push('system')
119
+ if (before.params !== params) moved.push('params')
120
+ if (before.wire !== wire && before.wire !== '' && wire !== '') moved.push('wire')
121
+ changed = moved
122
+ // Only what the earlier request kept for good can be rewritten: its own request-only
123
+ // tail is gone from this one by design.
124
+ const stable = before.items.length - before.tail
125
+ for (let at = 0; at < stable; at++) {
126
+ if (items[at] !== before.items[at]) {
127
+ firstChangedItem = at
128
+ break
129
+ }
130
+ }
131
+ }
132
+ earlier.delete(input.conversation)
133
+ earlier.set(input.conversation, { model, tools, system, params, wire, items, tail })
134
+ while (earlier.size > MAX_CONVERSATIONS) {
135
+ const oldest = earlier.keys().next().value
136
+ if (oldest === undefined) break
137
+ earlier.delete(oldest)
138
+ }
139
+
140
+ return {
141
+ model,
142
+ tools,
143
+ system,
144
+ params,
145
+ items: items.join(''),
146
+ ...(input.wire
147
+ ? {
148
+ cacheKey: input.wire.cacheKey,
149
+ sessionHeader: input.wire.sessionHeader,
150
+ developerRefused: input.wire.developerRefused === true,
151
+ }
152
+ : {}),
153
+ ...(changed ? { changed } : {}),
154
+ ...(firstChangedItem !== undefined ? { firstChangedItem } : {}),
155
+ }
156
+ }
157
+
158
+ /** Test seam: forget what earlier requests held. */
159
+ export function resetRequestPrefixDigests(): void {
160
+ earlier.clear()
161
+ }
@@ -854,9 +854,11 @@ export interface ToolReviewRequest {
854
854
  readonly perCall?: true
855
855
  /**
856
856
  * Aborts when the question stops being open: the turn was cancelled, a
857
- * rule or the mode now covers the call, or an earlier refusal ended the
858
- * turn. A host that shows the question closes it then; its answer is
859
- * ignored. Present only with `perCall`.
857
+ * rule or the mode now covers the call, an earlier refusal ended the
858
+ * turn, or the person wrote a message instead of answering. A host that
859
+ * shows the question closes it then; its answer is ignored. Present with
860
+ * `perCall`, and on any request when the host gave the turn a live message
861
+ * box (`ResumeContext.waitForOperator`).
860
862
  */
861
863
  readonly signal?: AbortSignal
862
864
  }
@@ -1037,6 +1039,69 @@ function isHookGranted(tc: ToolCallSummary): boolean {
1037
1039
  )
1038
1040
  }
1039
1041
 
1042
+ /**
1043
+ * What the model is told when a message from the person closed a question that
1044
+ * was open, or about to be shown. Nobody refused the call, and the text says so:
1045
+ * the refusal path would otherwise read as the person's decision.
1046
+ */
1047
+ export const CLOSED_BY_MESSAGE_FEEDBACK =
1048
+ "[Tool call not completed: a message from the user arrived while the approval request for this call was open or about to be shown, so the request was closed and the call did not run. Nobody refused it, so this is not the user's decision. The message follows; ask again if the action is still needed.]"
1049
+
1050
+ /**
1051
+ * Put one question to the person, and take it back if they write instead.
1052
+ *
1053
+ * The host's prompt is handed a signal that closes it (the turn's own, joined
1054
+ * with this one), so a card is taken off the screen; the answer is then the
1055
+ * message's closing text rather than a refusal by the person. With no live
1056
+ * message box (`ResumeContext.waitForOperator`) the question waits as before.
1057
+ */
1058
+ async function askUntilMessage(
1059
+ prompt: ToolReviewPrompt,
1060
+ request: Omit<ToolReviewRequest, 'signal'>,
1061
+ context: ResumeContext | undefined,
1062
+ ): Promise<ToolReviewAnswer> {
1063
+ const wake = context?.waitForOperator
1064
+ if (!wake) {
1065
+ return prompt({
1066
+ ...request,
1067
+ ...(request.perCall && context?.signal ? { signal: context.signal } : {}),
1068
+ })
1069
+ }
1070
+ const closing = new AbortController()
1071
+ const turn = context?.signal
1072
+ const signal = turn ? AbortSignal.any([turn, closing.signal]) : closing.signal
1073
+ const watching = new AbortController()
1074
+ return new Promise<ToolReviewAnswer>((resolve, reject) => {
1075
+ let done = false
1076
+ const finish = (settle: () => void): void => {
1077
+ if (done) return
1078
+ done = true
1079
+ watching.abort()
1080
+ settle()
1081
+ }
1082
+ turn?.addEventListener('abort', () => watching.abort(), { once: true })
1083
+ Promise.resolve(wake(watching.signal)).then(
1084
+ () =>
1085
+ finish(() => {
1086
+ // Settled first, so the prompt's own rejection on the close below is ignored.
1087
+ resolve({ kind: 'reject', feedback: CLOSED_BY_MESSAGE_FEEDBACK })
1088
+ closing.abort(new Error('A message from the user closed the approval request.'))
1089
+ }),
1090
+ // An aborted or closed wait is the turn ending, which is not a message.
1091
+ () => {},
1092
+ )
1093
+ // One turn of the microtask queue later, so a message that was already waiting has
1094
+ // settled the question before the person is shown it, not after.
1095
+ queueMicrotask(() => {
1096
+ if (done) return
1097
+ Promise.resolve(prompt({ ...request, signal })).then(
1098
+ (answer) => finish(() => resolve(answer)),
1099
+ (error: unknown) => finish(() => reject(error)),
1100
+ )
1101
+ })
1102
+ })
1103
+ }
1104
+
1040
1105
  /** The handler behind `createReviewPolicy`, for a host that wants only the function. */
1041
1106
  export function createReviewHandler(options: ReviewPolicyOptions = {}): ResumeHandler {
1042
1107
  const { prompt, registry } = options
@@ -1254,14 +1319,17 @@ export function createReviewHandler(options: ReviewPolicyOptions = {}): ResumeHa
1254
1319
  shown?: readonly ToolCallSummary[],
1255
1320
  ): Promise<ToolReviewAnswer> =>
1256
1321
  answered ??
1257
- (prompt as ToolReviewPrompt)({
1258
- sessionId: request.sessionId,
1259
- turnId: request.turnId,
1260
- toolCalls: shown ?? request.toolCalls,
1261
- ...(screenConsent ? { screenConsent } : {}),
1262
- ...(request.perCall ? { perCall: true as const } : {}),
1263
- ...(request.perCall && context?.signal ? { signal: context.signal } : {}),
1264
- })
1322
+ askUntilMessage(
1323
+ prompt as ToolReviewPrompt,
1324
+ {
1325
+ sessionId: request.sessionId,
1326
+ turnId: request.turnId,
1327
+ toolCalls: shown ?? request.toolCalls,
1328
+ ...(screenConsent ? { screenConsent } : {}),
1329
+ ...(request.perCall ? { perCall: true as const } : {}),
1330
+ },
1331
+ context,
1332
+ )
1265
1333
  // The first look at the screen in a session is the operator's to allow:
1266
1334
  // what is on it goes to the model provider, and a screenshot reads as
1267
1335
  // harmlessly as a file read to every rule below. Asked once, in the
@@ -0,0 +1,54 @@
1
+ import type { SandboxExecOptions } from '../types/sandbox/index.js'
2
+
3
+ /** The most standard input, in UTF-8 bytes, one `exec` may carry. */
4
+ export const SANDBOX_EXEC_STDIN_MAX_BYTES = 1024 * 1024
5
+
6
+ /**
7
+ * `SandboxExecOptions.stdin` was refused: it is not text, it is over
8
+ * {@link SANDBOX_EXEC_STDIN_MAX_BYTES}, or the backend has no guest agent to
9
+ * carry it. Thrown before anything is sent or started.
10
+ */
11
+ export class SandboxExecStdinError extends Error {
12
+ constructor(
13
+ message: string,
14
+ readonly reason: 'not-text' | 'too-large' | 'unsupported',
15
+ ) {
16
+ super(message)
17
+ this.name = 'SandboxExecStdinError'
18
+ }
19
+ }
20
+
21
+ /**
22
+ * The stdin an agent-backed backend sends, validated: `undefined` when the
23
+ * caller gave none, the text when it is within the bound, a
24
+ * {@link SandboxExecStdinError} otherwise.
25
+ */
26
+ export function execStdinOf(
27
+ opts: Pick<SandboxExecOptions, 'stdin'> | undefined,
28
+ ): string | undefined {
29
+ const stdin = opts?.stdin
30
+ if (stdin === undefined) return undefined
31
+ if (typeof stdin !== 'string') {
32
+ throw new SandboxExecStdinError('exec stdin must be a string.', 'not-text')
33
+ }
34
+ const bytes = Buffer.byteLength(stdin, 'utf8')
35
+ if (bytes > SANDBOX_EXEC_STDIN_MAX_BYTES) {
36
+ throw new SandboxExecStdinError(
37
+ `exec stdin is ${bytes} bytes, over the ${SANDBOX_EXEC_STDIN_MAX_BYTES}-byte limit. Nothing was sent. Stage a larger document with writeFile and redirect it.`,
38
+ 'too-large',
39
+ )
40
+ }
41
+ return stdin
42
+ }
43
+
44
+ /** For a backend without a guest agent: refuse a call that carries stdin. */
45
+ export function refuseExecStdin(
46
+ opts: Pick<SandboxExecOptions, 'stdin'> | undefined,
47
+ backend: string,
48
+ ): void {
49
+ if (opts?.stdin === undefined) return
50
+ throw new SandboxExecStdinError(
51
+ `The ${backend} sandbox cannot give a command standard input, so nothing was run. Use an agent-backed sandbox (Firecracker or Kubernetes), or stage the text with writeFile and redirect it.`,
52
+ 'unsupported',
53
+ )
54
+ }