@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
@@ -24,6 +24,7 @@ import {
24
24
  planCompaction,
25
25
  planSalienceWorkingSet,
26
26
  } from '../../../../compaction/plan.js'
27
+ import { precomputeStoreFor } from '../../../../compaction/precompute.js'
27
28
  import type { ContextReducer, ContextReduction } from '../../../../compaction/reducer.js'
28
29
  import { createSlidingWindowReducer } from '../../../../compaction/reducer.js'
29
30
  import {
@@ -60,6 +61,7 @@ import {
60
61
  estimateRefillTokens,
61
62
  } from './compaction-breaker.js'
62
63
  import type { IterationContext } from './context.js'
64
+ import { armPrecompute, bookPreparedSpend, takePrepared } from './precompute.js'
63
65
  import { isWorkingMemoryMessage } from './working-memory.js'
64
66
 
65
67
  // `isCompactionMessage` and the header moved to `compaction/summary.ts` —
@@ -652,6 +654,7 @@ async function applyReducer(
652
654
  windowSource: 'config' | 'provider' | 'model-table' | 'default'
653
655
  },
654
656
  ): Promise<void> {
657
+ const startedAt = performance.now()
655
658
  const messages = ctx.recorder.messages
656
659
  const before = messages.length
657
660
  const beforeChars = totalChars(messages)
@@ -724,6 +727,13 @@ async function applyReducer(
724
727
  // Found by a test written for the decline paths asserting that success does
725
728
  // NOT report a failure, which is the only reason anybody looked here.
726
729
  const tokensAfter = estimateTokens(ctx)
730
+ const durationMs = Math.max(0, Math.round(performance.now() - startedAt))
731
+ ctx.recorder.noteCompaction?.({
732
+ trigger: 'auto',
733
+ tokensBefore: reduction.estimatedTokens,
734
+ tokensAfter,
735
+ durationMs,
736
+ })
727
737
  await ctx.emitEvent?.({
728
738
  type: 'compaction_completed',
729
739
  turnId: ctx.recorder.turnId,
@@ -735,6 +745,8 @@ async function applyReducer(
735
745
  measuredBy: measurement.measuredBy,
736
746
  contextWindowTokens: reduction.contextWindowTokens,
737
747
  windowSource: measurement.windowSource,
748
+ trigger: 'auto',
749
+ durationMs,
738
750
  })
739
751
  await emitContextUsageSnapshot(
740
752
  ctx,
@@ -801,17 +813,22 @@ interface CompactionPass {
801
813
  hookInstructions?: string
802
814
  /** The summary the pass installed, for `post_compact`. */
803
815
  summary?: string
816
+ /** The summary was written ahead of time and installed at once. */
817
+ precomputed?: boolean
818
+ /** A turn that started after the prompt cache lapsed asked for it. */
819
+ cause?: 'cache_expired'
804
820
  tokensBefore: number
805
821
  contextWindowTokens: number
806
822
  }
807
823
 
808
824
  export async function runCompactionCheck(
809
825
  ctx: IterationContext,
810
- options?: { force?: boolean; deeper?: boolean },
826
+ options?: { force?: boolean; deeper?: boolean; preparedOnly?: boolean },
811
827
  ): Promise<void> {
812
828
  const pass: CompactionPass = {
813
829
  attempted: false,
814
830
  reason: options?.force ? 'overflow' : 'threshold',
831
+ ...(options?.preparedOnly ? { cause: 'cache_expired' as const } : {}),
815
832
  tokensBefore: 0,
816
833
  contextWindowTokens: 0,
817
834
  }
@@ -852,13 +869,23 @@ export async function runCompactionCheck(
852
869
  async function runCompactionCheckInner(
853
870
  ctx: IterationContext,
854
871
  pass: CompactionPass,
855
- options?: { force?: boolean; deeper?: boolean },
872
+ options?: { force?: boolean; deeper?: boolean; preparedOnly?: boolean },
856
873
  ): Promise<void> {
874
+ const startedAt = performance.now()
875
+ // What summaries prepared earlier cost, before any early return below.
876
+ bookPreparedSpend(ctx)
857
877
  const configured = ctx.compactionConfig
858
878
  if (!configured) return
859
879
  if (configured.strategy === 'disabled') return
860
880
  // Automatic compaction off: only a pass the provider forced (an overflow) runs.
861
881
  if (configured.autoCompact === false && !options?.force) return
882
+ if (options?.preparedOnly) {
883
+ // Only a summary already written, and only where one could be used: a
884
+ // reducer owns reduction, and nothing prepared means nothing to install.
885
+ if (configured.precompute === false || !ctx.compactionSummaryRoute) return
886
+ if (ctx.contextReducer || configured.strategy === 'sliding-window') return
887
+ if (precomputeStoreFor(ctx.recorder.sessionId).entry?.status !== 'ready') return
888
+ }
862
889
  const deepened = options?.deeper ? deepenConfig(configured, ctx.recorder.messages) : configured
863
890
 
864
891
  const measured = measureContext(ctx)
@@ -907,7 +934,20 @@ async function runCompactionCheckInner(
907
934
  config.autoCompactWindowTokens,
908
935
  )
909
936
  const startAt = salience ? Math.min(config.softTarget ?? DEFAULT_SOFT_TARGET, trigger) : trigger
910
- if (!options?.force && usage < startAt) return
937
+ if (!options?.force && !options?.preparedOnly && usage < startAt) {
938
+ // Short of the trigger. Near it, a summary starts in the background so it
939
+ // is ready by the time the trigger is reached; far from it, nothing runs.
940
+ armPrecompute(ctx, {
941
+ config,
942
+ usage,
943
+ trigger,
944
+ budget,
945
+ estimatedTokens,
946
+ ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),
947
+ source: 'estimate',
948
+ })
949
+ return
950
+ }
911
951
 
912
952
  // A pass that can shed nothing and has not reached the summary trigger
913
953
  // does nothing but announce itself: two hooks, a started event and a log
@@ -919,10 +959,21 @@ async function runCompactionCheckInner(
919
959
  if (
920
960
  salience &&
921
961
  !options?.force &&
962
+ !options?.preparedOnly &&
922
963
  !ctx.contextReducer &&
923
964
  usage < trigger &&
924
965
  !canShedSalienceWorkingSet(ctx.recorder.messages, config)
925
966
  ) {
967
+ // Nothing to shed yet, but the summary can still start near the trigger.
968
+ armPrecompute(ctx, {
969
+ config,
970
+ usage,
971
+ trigger,
972
+ budget,
973
+ estimatedTokens,
974
+ ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),
975
+ source: 'estimate',
976
+ })
926
977
  return
927
978
  }
928
979
 
@@ -1056,7 +1107,7 @@ async function runCompactionCheckInner(
1056
1107
  // The decision is `planCompaction`'s; installing it is this file's. The
1057
1108
  // planner touches no `ctx` at all, which is what lets the boundary
1058
1109
  // arithmetic be tested without a turn.
1059
- if (salience) {
1110
+ if (salience && !options?.preparedOnly) {
1060
1111
  let openTasks: string[] | undefined
1061
1112
  if (ctx.taskStore) {
1062
1113
  try {
@@ -1084,6 +1135,15 @@ async function runCompactionCheckInner(
1084
1135
  // Under the trigger, the working set was the whole pass: the summary
1085
1136
  // path is for the trigger, not for the soft target.
1086
1137
  if (!options?.force && (estimatedTokens - working.reclaimedTokens) / budget < trigger) {
1138
+ armPrecompute(ctx, {
1139
+ config,
1140
+ usage: (estimatedTokens - working.reclaimedTokens) / budget,
1141
+ trigger,
1142
+ budget,
1143
+ estimatedTokens: estimatedTokens - working.reclaimedTokens,
1144
+ ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),
1145
+ source: 'estimate',
1146
+ })
1087
1147
  return
1088
1148
  }
1089
1149
  }
@@ -1094,6 +1154,8 @@ async function runCompactionCheckInner(
1094
1154
  ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),
1095
1155
  estimatedTokens,
1096
1156
  ...(options?.force ? { force: true } : {}),
1157
+ // Installing a prepared summary leaves the tool results to the stale clear.
1158
+ ...(options?.preparedOnly ? { skipToolResultClear: true } : {}),
1097
1159
  })
1098
1160
 
1099
1161
  if (clearPlan.kind === 'cleared') {
@@ -1168,52 +1230,82 @@ async function runCompactionCheckInner(
1168
1230
  return
1169
1231
  }
1170
1232
 
1171
- const { systemMessages, olderMessages, recentMessages, keepStart } = plan
1233
+ let { olderMessages, recentMessages, keepStart } = plan
1234
+ const { systemMessages } = plan
1172
1235
 
1173
1236
  let compactedContent: string
1174
1237
 
1238
+ // A summary written ahead of time stands in for the one this pass would
1239
+ // write, when it still describes the start of the conversation. What was
1240
+ // said after it was armed stays verbatim after the summary.
1241
+ const prepared =
1242
+ ctx.compactionSummaryRoute && config.precompute !== false && !ctx.contextReducer
1243
+ ? await takePrepared(ctx, {
1244
+ messages,
1245
+ floorLength: systemMessages.length,
1246
+ hookInstructions: pass.hookInstructions,
1247
+ overheadTokens: estimateToolCatalogTokens(ctx),
1248
+ budget,
1249
+ triggerTokens: trigger * budget,
1250
+ ...(options?.preparedOnly ? { readyOnly: true } : {}),
1251
+ })
1252
+ : undefined
1253
+ // A turn that starts after the cache lapsed installs a summary that is
1254
+ // ready, and writes none: a refusal is a skip.
1255
+ if (options?.preparedOnly && !prepared) return
1256
+ if (prepared) {
1257
+ keepStart = prepared.keepStart
1258
+ olderMessages = messages.slice(systemMessages.length, keepStart)
1259
+ recentMessages = messages.slice(keepStart)
1260
+ pass.precomputed = true
1261
+ }
1262
+
1175
1263
  // A model the host set aside writes the summary when it can. Its own cost
1176
1264
  // goes on the turn's ledger at the price of the model that answered. When
1177
1265
  // there is no such model, or its call does not give a summary, the
1178
1266
  // extracted state below is used, with its verifier step where that applies.
1179
1267
  let modelRoute: { providerId: string; model: string } | undefined
1180
- const modelWritten = !ctx.compactionSummaryRoute
1181
- ? undefined
1182
- : await summarizeWithModel({
1183
- manager,
1184
- olderMessages,
1185
- previousSummaries: replaceableSummaries(systemMessages),
1186
- config,
1187
- ...(pass.hookInstructions !== undefined ? { hookInstructions: pass.hookInstructions } : {}),
1188
- resolveRoute: async (signal) => {
1189
- const route = await ctx.compactionSummaryRoute?.(signal)
1190
- if (route) {
1191
- modelRoute = {
1192
- providerId: route.providerId ?? ctx.recorder.servingProviderId,
1193
- model: route.model,
1268
+ const modelWritten = prepared
1269
+ ? prepared.summary
1270
+ : !ctx.compactionSummaryRoute
1271
+ ? undefined
1272
+ : await summarizeWithModel({
1273
+ manager,
1274
+ olderMessages,
1275
+ previousSummaries: replaceableSummaries(systemMessages),
1276
+ config,
1277
+ ...(pass.hookInstructions !== undefined
1278
+ ? { hookInstructions: pass.hookInstructions }
1279
+ : {}),
1280
+ resolveRoute: async (signal) => {
1281
+ const route = await ctx.compactionSummaryRoute?.(signal)
1282
+ if (route) {
1283
+ modelRoute = {
1284
+ providerId: route.providerId ?? ctx.recorder.servingProviderId,
1285
+ model: route.model,
1286
+ }
1194
1287
  }
1195
- }
1196
- return route
1197
- },
1198
- onUsage: (usage) => {
1199
- if (modelRoute) ctx.recorder.accumulateUsage(usage, modelRoute)
1200
- },
1201
- signal: ctx.abortController.signal,
1202
- onFallback: (reason, error) => {
1203
- if (reason === 'no_route') return
1204
- if (error !== undefined) noteCompactionError(ctx, error)
1205
- ctx.log.warn(
1206
- 'The model-written compaction summary was not used — using the extracted state',
1207
- {
1208
- [NAMZU.TURN_ID]: ctx.recorder.turnId,
1209
- 'namzu.runtime.reason': reason,
1210
- ...(error !== undefined
1211
- ? { 'exception.message': error instanceof Error ? error.message : String(error) }
1212
- : {}),
1213
- },
1214
- )
1215
- },
1216
- })
1288
+ return route
1289
+ },
1290
+ onUsage: (usage) => {
1291
+ if (modelRoute) ctx.recorder.accumulateUsage(usage, modelRoute)
1292
+ },
1293
+ signal: ctx.abortController.signal,
1294
+ onFallback: (reason, error) => {
1295
+ if (reason === 'no_route') return
1296
+ if (error !== undefined) noteCompactionError(ctx, error)
1297
+ ctx.log.warn(
1298
+ 'The model-written compaction summary was not used — using the extracted state',
1299
+ {
1300
+ [NAMZU.TURN_ID]: ctx.recorder.turnId,
1301
+ 'namzu.runtime.reason': reason,
1302
+ ...(error !== undefined
1303
+ ? { 'exception.message': error instanceof Error ? error.message : String(error) }
1304
+ : {}),
1305
+ },
1306
+ )
1307
+ },
1308
+ })
1217
1309
 
1218
1310
  if (modelWritten !== undefined) {
1219
1311
  compactedContent = modelWritten
@@ -1393,6 +1485,16 @@ async function runCompactionCheckInner(
1393
1485
  pass.summary = compactedContent
1394
1486
 
1395
1487
  const newEstimate = estimateTokens(ctx)
1488
+ // Said before anything below emits: an emit reconciles the log with the new
1489
+ // context, and the `compaction` record it writes carries what was said here.
1490
+ const durationMs = Math.max(0, Math.round(performance.now() - startedAt))
1491
+ ctx.recorder.noteCompaction?.({
1492
+ trigger: pass.precomputed ? 'prepared' : 'auto',
1493
+ tokensBefore: estimatedTokens,
1494
+ tokensAfter: newEstimate,
1495
+ durationMs,
1496
+ ...(pass.precomputed ? { precomputed: true } : {}),
1497
+ })
1396
1498
 
1397
1499
  // The provider's count described the PRE-compaction prompt; the window
1398
1500
  // it just shrank to has not been sent yet, so the post number is
@@ -1446,6 +1548,10 @@ async function runCompactionCheckInner(
1446
1548
  contextWindowTokens: budget,
1447
1549
  windowSource: window.source,
1448
1550
  reachedResetThreshold: reachedReset,
1551
+ trigger: pass.precomputed ? 'prepared' : 'auto',
1552
+ durationMs,
1553
+ ...(pass.precomputed ? { precomputed: true } : {}),
1554
+ ...(pass.cause ? { cause: pass.cause } : {}),
1449
1555
  })
1450
1556
  await emitContextUsageSnapshot(ctx, newEstimate, budget, window.source)
1451
1557
  if (putBack.rendered && putBack.rendered.carried.length > 0) {
@@ -0,0 +1,277 @@
1
+ import { askPreCompact } from '../../../../compaction/hooks.js'
2
+ import { replaceableSummaries, summarizeWithModel } from '../../../../compaction/model-summary.js'
3
+ import { planCompaction } from '../../../../compaction/plan.js'
4
+ import {
5
+ PRECOMPUTE_DEFAULT_ARM_FRACTION,
6
+ type PrecomputeArmSource,
7
+ type PrecomputeEntry,
8
+ armUsage,
9
+ claimPrepared,
10
+ messageDigest,
11
+ precomputeStoreFor,
12
+ } from '../../../../compaction/precompute.js'
13
+ import { estimateMessagesTokens } from '../../../../compaction/token-estimate.js'
14
+ import type { CompactionConfig } from '../../../../config/runtime.js'
15
+ import { CHARS_PER_TOKEN } from '../../../../constants/limits.js'
16
+ import { NAMZU } from '../../../../constants/telemetry/index.js'
17
+ import type { Message } from '../../../../types/message/index.js'
18
+ import type { IterationContext } from './context.js'
19
+
20
+ /** The message the conversation is on: the last one the person's side wrote. */
21
+ function currentPrompt(messages: readonly Message[]): Message | undefined {
22
+ for (let i = messages.length - 1; i >= 0; i--) {
23
+ if (messages[i]?.role === 'user') return messages[i]
24
+ }
25
+ return undefined
26
+ }
27
+
28
+ export interface ArmInput {
29
+ readonly config: CompactionConfig
30
+ /** Context size and trigger, as shares of the window. */
31
+ readonly usage: number
32
+ readonly trigger: number
33
+ readonly budget: number
34
+ readonly estimatedTokens: number
35
+ readonly maxOutputTokens?: number
36
+ readonly source: PrecomputeArmSource
37
+ }
38
+
39
+ /**
40
+ * Start a summary in the background when the context is near the trigger.
41
+ *
42
+ * Costs nothing until the context passes the arm point, so a short session
43
+ * never makes the request. Returns at once; the request runs on its own
44
+ * controller, tied to the session and not to this turn, so a turn that ends
45
+ * before the trigger leaves it running for the next one to use.
46
+ */
47
+ export function armPrecompute(ctx: IterationContext, input: ArmInput): boolean {
48
+ const { config } = input
49
+ if (config.precompute === false) return false
50
+ if (config.strategy === 'disabled') return false
51
+ if (config.autoCompact === false) return false
52
+ // A reducer owns reduction, and without a model route the extracted state
53
+ // is free to build at the trigger: there is nothing to prepare.
54
+ if (ctx.contextReducer || config.strategy === 'sliding-window') return false
55
+ const route = ctx.compactionSummaryRoute
56
+ const manager = ctx.workingStateManager
57
+ if (!route || !manager) return false
58
+ if (
59
+ input.usage <
60
+ armUsage(input.trigger, config.precomputeArmFraction ?? PRECOMPUTE_DEFAULT_ARM_FRACTION)
61
+ )
62
+ return false
63
+ if (input.usage >= input.trigger) return false
64
+
65
+ const store = precomputeStoreFor(ctx.recorder.sessionId)
66
+ const live = [...ctx.recorder.messages]
67
+ const prompt = currentPrompt(live)
68
+ if (!store.canArm(prompt)) return false
69
+
70
+ const plan = planCompaction({
71
+ messages: live,
72
+ config,
73
+ contextWindowTokens: input.budget,
74
+ ...(input.maxOutputTokens !== undefined ? { maxOutputTokens: input.maxOutputTokens } : {}),
75
+ estimatedTokens: input.estimatedTokens,
76
+ skipToolResultClear: true,
77
+ })
78
+ if (plan.kind !== 'plan') return false
79
+
80
+ const controller = new AbortController()
81
+ const entry: PrecomputeEntry = {
82
+ status: 'pending',
83
+ source: input.source,
84
+ covered: plan.olderMessages,
85
+ coveredDigests: plan.olderMessages.map(messageDigest),
86
+ windowTokens: input.budget,
87
+ prompt,
88
+ controller,
89
+ done: Promise.resolve(),
90
+ spend: [],
91
+ }
92
+ store.set(entry)
93
+ const providerFallback = ctx.recorder.servingProviderId
94
+ let modelRoute: { providerId: string; model: string } | undefined
95
+ const settle = (status: 'ready' | 'failed'): void => {
96
+ entry.status = status
97
+ if (status === 'failed') {
98
+ // A failed request may still have spent tokens. When the entry is still the
99
+ // store's (nobody has cancelled or taken it), its spend moves to the
100
+ // unbooked list now, because clearing the entry would drop it. A cancel or
101
+ // a claim returns the entry's spend itself.
102
+ if (store.entry === entry) store.addUnbooked(entry.spend.splice(0))
103
+ store.clear(entry)
104
+ // A stopped summary is not the summary's fault.
105
+ if (!controller.signal.aborted) store.countFailure(prompt)
106
+ }
107
+ }
108
+ entry.done = (async () => {
109
+ try {
110
+ if (ctx.pluginManager) {
111
+ const answer = await askPreCompact(
112
+ ctx.pluginManager,
113
+ {
114
+ sessionId: ctx.recorder.sessionId,
115
+ turnId: ctx.recorder.turnId,
116
+ iteration: ctx.recorder.currentIteration,
117
+ signal: controller.signal,
118
+ emitEvent: ctx.emitEvent,
119
+ },
120
+ {
121
+ reason: 'threshold',
122
+ trigger: 'auto',
123
+ instructions: null,
124
+ tokensBefore: input.estimatedTokens,
125
+ contextWindowTokens: input.budget,
126
+ },
127
+ )
128
+ if (answer.refusal !== undefined) {
129
+ // A hook postponed this housekeeping: say so for this prompt only.
130
+ ctx.log.info('A pre_compact hook cancelled a summary prepared ahead', {
131
+ [NAMZU.TURN_ID]: ctx.recorder.turnId,
132
+ 'namzu.hook.reason': answer.refusal,
133
+ })
134
+ settle('failed')
135
+ return
136
+ }
137
+ if (answer.instructions !== undefined) entry.hookInstructions = answer.instructions
138
+ }
139
+ const text = await summarizeWithModel({
140
+ manager,
141
+ olderMessages: plan.olderMessages,
142
+ previousSummaries: replaceableSummaries(plan.systemMessages),
143
+ config,
144
+ ...(entry.hookInstructions !== undefined
145
+ ? { hookInstructions: entry.hookInstructions }
146
+ : {}),
147
+ resolveRoute: async (signal) => {
148
+ const resolved = await route(signal)
149
+ if (resolved) {
150
+ modelRoute = {
151
+ providerId: resolved.providerId ?? providerFallback,
152
+ model: resolved.model,
153
+ }
154
+ }
155
+ return resolved
156
+ },
157
+ onUsage: (usage) => {
158
+ if (!modelRoute) return
159
+ // On the turn that armed it while that turn is open; otherwise kept
160
+ // on the entry for the pass that takes it, the one that stops it, or
161
+ // the next turn.
162
+ if (ctx.recorder.acceptsUsage) ctx.recorder.accumulateUsage(usage, modelRoute)
163
+ else entry.spend.push({ usage, route: modelRoute })
164
+ },
165
+ signal: controller.signal,
166
+ })
167
+ if (text === undefined) {
168
+ settle('failed')
169
+ return
170
+ }
171
+ entry.summary = text
172
+ settle('ready')
173
+ } catch {
174
+ settle('failed')
175
+ }
176
+ })()
177
+ ctx.log.info('Preparing a compaction summary ahead of the trigger', {
178
+ [NAMZU.TURN_ID]: ctx.recorder.turnId,
179
+ 'namzu.runtime.arm_source': input.source,
180
+ 'namzu.runtime.context_tokens': input.estimatedTokens,
181
+ 'namzu.runtime.covered_messages': plan.olderMessages.length,
182
+ })
183
+ return true
184
+ }
185
+
186
+ /**
187
+ * Put on this turn what prepared summaries spent that no turn has booked: a
188
+ * request that finished after the turn that started it had ended, one stopped
189
+ * by a pass a person asked for, one a pass refused or found nothing to do with.
190
+ * A summary still in flight is left alone (nothing it has spent is known yet),
191
+ * and one still waiting to be used keeps its summary and gives up only its cost.
192
+ */
193
+ export function bookPreparedSpend(ctx: IterationContext): void {
194
+ if (!ctx.recorder.acceptsUsage) return
195
+ const store = precomputeStoreFor(ctx.recorder.sessionId)
196
+ if (!store.holdsSpend()) return
197
+ for (const { usage, route } of store.takeSpend()) ctx.recorder.accumulateUsage(usage, route)
198
+ }
199
+
200
+ export interface TakeInput {
201
+ /** The messages the pass is about to cut; a staged clear, when there is one. Same positions as the live context. */
202
+ readonly messages: readonly Message[]
203
+ /** The leading system messages. */
204
+ readonly floorLength: number
205
+ readonly hookInstructions: string | undefined
206
+ /** Tokens the request carries beyond its messages (the tool catalogue). */
207
+ readonly overheadTokens: number
208
+ readonly budget: number
209
+ /** The trigger as tokens: a swap that leaves the context at or above it is refused. */
210
+ readonly triggerTokens: number
211
+ /** Take only a summary that is already written; never wait for one in flight. */
212
+ readonly readyOnly?: boolean
213
+ }
214
+
215
+ export interface TakenSummary {
216
+ readonly summary: string
217
+ /** The new cut: everything before it is summarised, everything from it on stays. */
218
+ readonly keepStart: number
219
+ }
220
+
221
+ /**
222
+ * Take the prepared summary for the pass that is about to write one.
223
+ *
224
+ * Waits for one still in flight (it is the summary this pass would have
225
+ * written). A refusal consumes the entry, counts toward the failure cap and
226
+ * returns `undefined`, and the caller writes a fresh summary as before. What
227
+ * the prepared request spent goes onto the turn that takes it.
228
+ */
229
+ export async function takePrepared(
230
+ ctx: IterationContext,
231
+ input: TakeInput,
232
+ ): Promise<TakenSummary | undefined> {
233
+ const store = precomputeStoreFor(ctx.recorder.sessionId)
234
+ const pending = store.entry?.status === 'pending'
235
+ if (pending && !input.readyOnly) {
236
+ ctx.log.info('Waiting for the summary prepared ahead', {
237
+ [NAMZU.TURN_ID]: ctx.recorder.turnId,
238
+ })
239
+ }
240
+ const claimed = await claimPrepared(store, ctx.recorder.messages, {
241
+ floorLength: input.floorLength,
242
+ hookInstructions: input.hookInstructions,
243
+ limitTokens: input.triggerTokens,
244
+ windowTokens: input.budget,
245
+ awaitPending: !input.readyOnly,
246
+ waitFor: (promise) => raceWithAbort(promise, ctx.abortController.signal),
247
+ tokensAfterSwap: (keepStart, summary) =>
248
+ estimateMessagesTokens(input.messages.slice(0, input.floorLength)) +
249
+ estimateMessagesTokens(input.messages.slice(keepStart)) +
250
+ Math.ceil(summary.length / CHARS_PER_TOKEN) +
251
+ input.overheadTokens,
252
+ })
253
+ for (const { usage, route } of claimed.spend) ctx.recorder.accumulateUsage(usage, route)
254
+ if (claimed.ok) return { summary: claimed.summary, keepStart: claimed.keepStart }
255
+ if (claimed.reason !== 'none') {
256
+ ctx.log.info('The summary prepared ahead was not used', {
257
+ [NAMZU.TURN_ID]: ctx.recorder.turnId,
258
+ 'namzu.runtime.reason': claimed.reason,
259
+ })
260
+ }
261
+ return undefined
262
+ }
263
+
264
+ /** Wait for `promise`, or throw when `signal` aborts first. Neither outcome stops `promise`. */
265
+ async function raceWithAbort(promise: Promise<void>, signal: AbortSignal): Promise<void> {
266
+ signal.throwIfAborted()
267
+ let onAbort: (() => void) | undefined
268
+ const aborted = new Promise<never>((_, reject) => {
269
+ onAbort = () => reject(signal.reason ?? new Error('aborted'))
270
+ signal.addEventListener('abort', onAbort, { once: true })
271
+ })
272
+ try {
273
+ await Promise.race([promise, aborted])
274
+ } finally {
275
+ if (onAbort) signal.removeEventListener('abort', onAbort)
276
+ }
277
+ }
@@ -379,6 +379,8 @@ export class OutcomeLedger {
379
379
  /** A call ran that could change the workspace and is not a write tool: only the detector could say whether it did. */
380
380
  private couldHaveChangedUnseen = false
381
381
  private writes = 0
382
+ /** The loop step the last observed calls finished in. */
383
+ private lastStep = 0
382
384
  private readonly checks = new Map<string, CheckState>()
383
385
  /** Background jobs that run a recognised check, by job id: the command they run. */
384
386
  private readonly jobChecks = new Map<string, string>()
@@ -500,6 +502,7 @@ export class OutcomeLedger {
500
502
 
501
503
  /** Feed the calls of one finished step, in order. */
502
504
  async observe(step: number, calls: readonly OutcomeCall[]): Promise<void> {
505
+ this.lastStep = Math.max(this.lastStep, step)
503
506
  // Checks that finished in this step with nothing after them that could
504
507
  // change the workspace: the detector, asked once at the end of the step,
505
508
  // answers for exactly the state they left.
@@ -591,6 +594,33 @@ export class OutcomeLedger {
591
594
  this.paths.add(clipped)
592
595
  }
593
596
 
597
+ /**
598
+ * A check the host ran itself, such as a gate the person set for a goal. It is
599
+ * recorded as the latest run of its command on the files as they are now: the
600
+ * fingerprint is taken here, so a write or an unseen change after it makes it
601
+ * stale as for any other check.
602
+ */
603
+ async recordHostCheck(check: {
604
+ readonly command: string
605
+ readonly result: 'passed' | 'failed'
606
+ readonly exitCode?: number
607
+ }): Promise<void> {
608
+ if (this.unrecorded) return
609
+ const key = normalise(check.command)
610
+ const fingerprint =
611
+ this.started && this.startFingerprint !== null ? await this.detect() : undefined
612
+ this.storeCheck(key, {
613
+ key,
614
+ command: clip(key, OUTCOME_MAX_COMMAND_CHARS),
615
+ step: this.lastStep,
616
+ result: check.result,
617
+ ...(check.exitCode !== undefined ? { exitCode: check.exitCode } : {}),
618
+ afterWrite: false,
619
+ afterUnknown: false,
620
+ fingerprint,
621
+ })
622
+ }
623
+
594
624
  private recordCheck(step: number, command: string, call: OutcomeCall): CheckState {
595
625
  const key = normalise(command)
596
626
  const { result, exitCode } = this.judge(command, call)
@@ -605,6 +635,10 @@ export class OutcomeLedger {
605
635
  // Not asked for yet: `undefined` until the step's detector call answers.
606
636
  fingerprint: undefined,
607
637
  }
638
+ return this.storeCheck(key, state)
639
+ }
640
+
641
+ private storeCheck(key: string, state: CheckState): CheckState {
608
642
  // A failure stands until the same command passes. A later run that never
609
643
  // settled (background, timed out) says nothing about the failure.
610
644
  const earlier = this.checks.get(key)