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