@namzu/sdk 1.3.0 → 2.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 +106 -0
- package/dist/compaction/__tests__/verifier-empty-reply.test.d.ts +12 -0
- package/dist/compaction/__tests__/verifier-empty-reply.test.d.ts.map +1 -0
- package/dist/compaction/__tests__/verifier-empty-reply.test.js +73 -0
- package/dist/compaction/__tests__/verifier-empty-reply.test.js.map +1 -0
- package/dist/compaction/verifier.d.ts.map +1 -1
- package/dist/compaction/verifier.js +10 -1
- package/dist/compaction/verifier.js.map +1 -1
- package/dist/config/__tests__/compaction-budget-schema.test.d.ts +18 -0
- package/dist/config/__tests__/compaction-budget-schema.test.d.ts.map +1 -0
- package/dist/config/__tests__/compaction-budget-schema.test.js +96 -0
- package/dist/config/__tests__/compaction-budget-schema.test.js.map +1 -0
- package/dist/config/runtime.d.ts.map +1 -1
- package/dist/config/runtime.js +20 -11
- package/dist/config/runtime.js.map +1 -1
- package/dist/manager/run/persistence.d.ts +2 -1
- package/dist/manager/run/persistence.d.ts.map +1 -1
- package/dist/manager/run/persistence.js +3 -1
- package/dist/manager/run/persistence.js.map +1 -1
- package/dist/provider/__tests__/errors.test.d.ts +2 -0
- package/dist/provider/__tests__/errors.test.d.ts.map +1 -0
- package/dist/provider/__tests__/errors.test.js +61 -0
- package/dist/provider/__tests__/errors.test.js.map +1 -0
- package/dist/provider/errors.d.ts +108 -0
- package/dist/provider/errors.d.ts.map +1 -0
- package/dist/provider/errors.js +311 -0
- package/dist/provider/errors.js.map +1 -0
- package/dist/provider/index.d.ts +2 -0
- package/dist/provider/index.d.ts.map +1 -1
- package/dist/provider/index.js +1 -0
- package/dist/provider/index.js.map +1 -1
- package/dist/public-runtime.d.ts +11 -11
- package/dist/public-runtime.d.ts.map +1 -1
- package/dist/public-runtime.js +11 -11
- package/dist/public-runtime.js.map +1 -1
- package/dist/registry/tool/execute.d.ts.map +1 -1
- package/dist/registry/tool/execute.js +45 -12
- package/dist/registry/tool/execute.js.map +1 -1
- package/dist/registry/tool/execute.test.js +104 -7
- package/dist/registry/tool/execute.test.js.map +1 -1
- package/dist/registry/toolset/catalog.d.ts.map +1 -1
- package/dist/registry/toolset/catalog.js +17 -4
- package/dist/registry/toolset/catalog.js.map +1 -1
- package/dist/registry/toolset/catalog.test.js +101 -0
- package/dist/registry/toolset/catalog.test.js.map +1 -1
- package/dist/runtime/query/__tests__/capability-negotiation.test.js +79 -0
- package/dist/runtime/query/__tests__/capability-negotiation.test.js.map +1 -1
- package/dist/runtime/query/__tests__/deferred-tools.test.js +100 -0
- package/dist/runtime/query/__tests__/deferred-tools.test.js.map +1 -1
- package/dist/runtime/query/__tests__/long-document-flow.test.js +12 -12
- package/dist/runtime/query/__tests__/long-document-flow.test.js.map +1 -1
- package/dist/runtime/query/__tests__/stream-recovery.test.js +55 -2
- package/dist/runtime/query/__tests__/stream-recovery.test.js.map +1 -1
- package/dist/runtime/query/executor.js +2 -2
- package/dist/runtime/query/executor.js.map +1 -1
- package/dist/runtime/query/iteration/index.d.ts.map +1 -1
- package/dist/runtime/query/iteration/index.js +10 -0
- package/dist/runtime/query/iteration/index.js.map +1 -1
- package/dist/runtime/query/iteration/phases/compaction-safe-cut.test.d.ts +32 -0
- package/dist/runtime/query/iteration/phases/compaction-safe-cut.test.d.ts.map +1 -0
- package/dist/runtime/query/iteration/phases/compaction-safe-cut.test.js +152 -0
- package/dist/runtime/query/iteration/phases/compaction-safe-cut.test.js.map +1 -0
- package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
- package/dist/runtime/query/iteration/phases/compaction.js +52 -12
- package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
- package/dist/runtime/query/iteration/stream-turn.d.ts.map +1 -1
- package/dist/runtime/query/iteration/stream-turn.js +11 -5
- package/dist/runtime/query/iteration/stream-turn.js.map +1 -1
- package/dist/runtime/query/result.d.ts.map +1 -1
- package/dist/runtime/query/result.js +11 -1
- package/dist/runtime/query/result.js.map +1 -1
- package/dist/tools/builtins/__tests__/edit.test.js +216 -10
- package/dist/tools/builtins/__tests__/edit.test.js.map +1 -1
- package/dist/tools/builtins/__tests__/payload-budget.test.js +30 -16
- package/dist/tools/builtins/__tests__/payload-budget.test.js.map +1 -1
- package/dist/tools/builtins/__tests__/write-file.test.js +37 -13
- package/dist/tools/builtins/__tests__/write-file.test.js.map +1 -1
- package/dist/tools/builtins/atomic-write-file.d.ts +13 -0
- package/dist/tools/builtins/atomic-write-file.d.ts.map +1 -0
- package/dist/tools/builtins/atomic-write-file.js +46 -0
- package/dist/tools/builtins/atomic-write-file.js.map +1 -0
- package/dist/tools/builtins/bash.js +2 -2
- package/dist/tools/builtins/bash.js.map +1 -1
- package/dist/tools/builtins/edit.d.ts +2 -5
- package/dist/tools/builtins/edit.d.ts.map +1 -1
- package/dist/tools/builtins/edit.js +105 -125
- package/dist/tools/builtins/edit.js.map +1 -1
- package/dist/tools/builtins/file-mutation-lock.d.ts +7 -0
- package/dist/tools/builtins/file-mutation-lock.d.ts.map +1 -0
- package/dist/tools/builtins/file-mutation-lock.js +25 -0
- package/dist/tools/builtins/file-mutation-lock.js.map +1 -0
- package/dist/tools/builtins/index.js +2 -2
- package/dist/tools/builtins/index.js.map +1 -1
- package/dist/tools/builtins/write-file.d.ts +1 -2
- package/dist/tools/builtins/write-file.d.ts.map +1 -1
- package/dist/tools/builtins/write-file.js +66 -40
- package/dist/tools/builtins/write-file.js.map +1 -1
- package/dist/tools/coordinator/__tests__/task-list.test.js +14 -0
- package/dist/tools/coordinator/__tests__/task-list.test.js.map +1 -1
- package/dist/tools/coordinator/agent.d.ts +6 -8
- package/dist/tools/coordinator/agent.d.ts.map +1 -1
- package/dist/tools/coordinator/agent.js.map +1 -1
- package/dist/tools/coordinator/index.d.ts.map +1 -1
- package/dist/tools/coordinator/index.js +11 -32
- package/dist/tools/coordinator/index.js.map +1 -1
- package/dist/tools/defineTool.d.ts +3 -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/types/provider/chat.d.ts +9 -0
- package/dist/types/provider/chat.d.ts.map +1 -1
- package/dist/types/provider/error.d.ts +22 -0
- package/dist/types/provider/error.d.ts.map +1 -0
- package/dist/types/provider/error.js +2 -0
- package/dist/types/provider/error.js.map +1 -0
- package/dist/types/provider/index.d.ts +1 -0
- package/dist/types/provider/index.d.ts.map +1 -1
- package/dist/types/run/entity.d.ts +2 -0
- package/dist/types/run/entity.d.ts.map +1 -1
- package/dist/types/run/events.d.ts +2 -0
- package/dist/types/run/events.d.ts.map +1 -1
- package/dist/types/run/events.js.map +1 -1
- package/dist/types/sandbox/index.d.ts +4 -0
- package/dist/types/sandbox/index.d.ts.map +1 -1
- package/dist/types/sandbox/index.js.map +1 -1
- package/dist/types/tool/index.d.ts +20 -0
- package/dist/types/tool/index.d.ts.map +1 -1
- package/package.json +2 -1
- package/src/compaction/__tests__/verifier-empty-reply.test.ts +96 -0
- package/src/compaction/verifier.ts +10 -1
- package/src/config/__tests__/compaction-budget-schema.test.ts +114 -0
- package/src/config/runtime.ts +20 -11
- package/src/manager/run/persistence.ts +3 -1
- package/src/provider/__tests__/errors.test.ts +85 -0
- package/src/provider/errors.ts +344 -0
- package/src/provider/index.ts +15 -0
- package/src/public-runtime.ts +53 -10
- package/src/registry/tool/execute.test.ts +121 -7
- package/src/registry/tool/execute.ts +50 -12
- package/src/registry/toolset/catalog.test.ts +118 -0
- package/src/registry/toolset/catalog.ts +26 -4
- package/src/runtime/query/__tests__/capability-negotiation.test.ts +88 -0
- package/src/runtime/query/__tests__/deferred-tools.test.ts +111 -0
- package/src/runtime/query/__tests__/long-document-flow.test.ts +12 -12
- package/src/runtime/query/__tests__/stream-recovery.test.ts +65 -2
- package/src/runtime/query/executor.ts +2 -2
- package/src/runtime/query/iteration/index.ts +15 -0
- package/src/runtime/query/iteration/phases/compaction-safe-cut.test.ts +186 -0
- package/src/runtime/query/iteration/phases/compaction.ts +54 -12
- package/src/runtime/query/iteration/stream-turn.ts +11 -6
- package/src/runtime/query/result.ts +11 -1
- package/src/tools/builtins/__tests__/edit.test.ts +270 -10
- package/src/tools/builtins/__tests__/payload-budget.test.ts +40 -20
- package/src/tools/builtins/__tests__/write-file.test.ts +52 -13
- package/src/tools/builtins/atomic-write-file.ts +58 -0
- package/src/tools/builtins/bash.ts +2 -2
- package/src/tools/builtins/edit.ts +116 -162
- package/src/tools/builtins/file-mutation-lock.ts +27 -0
- package/src/tools/builtins/index.ts +2 -2
- package/src/tools/builtins/write-file.ts +68 -44
- package/src/tools/coordinator/__tests__/task-list.test.ts +16 -0
- package/src/tools/coordinator/agent.ts +6 -8
- package/src/tools/coordinator/index.ts +11 -34
- package/src/tools/defineTool.ts +6 -0
- package/src/types/provider/chat.ts +14 -1
- package/src/types/provider/error.ts +29 -0
- package/src/types/provider/index.ts +5 -0
- package/src/types/run/entity.ts +2 -0
- package/src/types/run/events.ts +7 -1
- package/src/types/sandbox/index.ts +4 -0
- package/src/types/tool/index.ts +20 -0
|
@@ -6,6 +6,7 @@ import { GENAI, NAMZU, agentIterationSpanName } from '../../../telemetry/attribu
|
|
|
6
6
|
import { getTracer } from '../../../telemetry/runtime-accessors.js'
|
|
7
7
|
import { createAssistantMessage, createUserMessage } from '../../../types/message/index.js'
|
|
8
8
|
import type { RunEvent, StopReason } from '../../../types/run/index.js'
|
|
9
|
+
import type { LLMToolSchema, ToolRegistryContract } from '../../../types/tool/index.js'
|
|
9
10
|
import { toErrorMessage } from '../../../utils/error.js'
|
|
10
11
|
import { generateMessageId } from '../../../utils/id.js'
|
|
11
12
|
import { applyLifecycleHookResults } from '../plugin-hooks.js'
|
|
@@ -118,6 +119,7 @@ export class IterationOrchestrator {
|
|
|
118
119
|
// risks a 400 because the history still carries
|
|
119
120
|
// tool_use/tool_result blocks.
|
|
120
121
|
const openAITools = this.ctx.tools.toLLMTools(this.ctx.allowedTools)
|
|
122
|
+
const enforceToolInputSchema = enforcedModelInputToolNames(this.ctx.tools, openAITools)
|
|
121
123
|
|
|
122
124
|
const messages = forceFinalize
|
|
123
125
|
? [
|
|
@@ -152,6 +154,7 @@ export class IterationOrchestrator {
|
|
|
152
154
|
model,
|
|
153
155
|
messages,
|
|
154
156
|
tools: openAITools.length > 0 ? openAITools : undefined,
|
|
157
|
+
enforceToolInputSchema,
|
|
155
158
|
toolChoice: forceFinalize && openAITools.length > 0 ? 'none' : undefined,
|
|
156
159
|
temperature: runConfig.temperature,
|
|
157
160
|
maxTokens: runConfig.maxResponseTokens,
|
|
@@ -428,11 +431,13 @@ export class IterationOrchestrator {
|
|
|
428
431
|
// tools param identical to prior iterations (cache prefix intact,
|
|
429
432
|
// no 400 on tool blocks in history) and forbid use via tool_choice.
|
|
430
433
|
const finalTools = this.ctx.tools.toLLMTools(this.ctx.allowedTools)
|
|
434
|
+
const enforceToolInputSchema = enforcedModelInputToolNames(this.ctx.tools, finalTools)
|
|
431
435
|
const response = await collect(
|
|
432
436
|
this.ctx.provider.chatStream({
|
|
433
437
|
model,
|
|
434
438
|
messages: finalMessages,
|
|
435
439
|
tools: finalTools.length > 0 ? finalTools : undefined,
|
|
440
|
+
enforceToolInputSchema,
|
|
436
441
|
toolChoice: finalTools.length > 0 ? 'none' : undefined,
|
|
437
442
|
temperature: this.ctx.runConfig.temperature,
|
|
438
443
|
maxTokens: this.ctx.runConfig.maxResponseTokens,
|
|
@@ -471,3 +476,13 @@ export class IterationOrchestrator {
|
|
|
471
476
|
}
|
|
472
477
|
}
|
|
473
478
|
}
|
|
479
|
+
|
|
480
|
+
function enforcedModelInputToolNames(
|
|
481
|
+
registry: ToolRegistryContract,
|
|
482
|
+
tools: readonly LLMToolSchema[],
|
|
483
|
+
): readonly string[] | undefined {
|
|
484
|
+
const names = tools
|
|
485
|
+
.map((tool) => tool.function.name)
|
|
486
|
+
.filter((name) => registry.get(name)?.enforceModelInput === true)
|
|
487
|
+
return names.length > 0 ? names : undefined
|
|
488
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The UNBOUNDED CUT.
|
|
3
|
+
*
|
|
4
|
+
* `runCompactionCheck` snaps the naive recent-window boundary
|
|
5
|
+
* (`messages.length - keepRecentMessages`) FORWARD via `findSafeTrimIndex` so a
|
|
6
|
+
* tool pair is never split. But `findSafeTrimIndex` only ever walks forward, and
|
|
7
|
+
* its leading-`tool`-message skip has no stop short of `messages.length` — so
|
|
8
|
+
* whenever the whole suffix from the naive index to the end is `tool` messages,
|
|
9
|
+
* the cut lands ON `messages.length`, `recentMessages` comes back EMPTY, and
|
|
10
|
+
* `[...preservedSystem, compactionMessage]` replaces the ENTIRE recent window.
|
|
11
|
+
* What is left is a transcript with no non-system message at all.
|
|
12
|
+
*
|
|
13
|
+
* The shape that produces it: ONE assistant turn that fans out
|
|
14
|
+
* `>= keepRecentMessages` parallel tool calls, measured at the START of the next
|
|
15
|
+
* iteration — which is exactly where `runCompactionCheck` runs (iteration/index.ts,
|
|
16
|
+
* after `refreshWorkingMemory`, before the model call), i.e. immediately after
|
|
17
|
+
* those results were appended.
|
|
18
|
+
*
|
|
19
|
+
* The `olderMessages.length < 1` guard at :117 cannot fire: `olderMessages` is
|
|
20
|
+
* the whole transcript in exactly this situation.
|
|
21
|
+
*
|
|
22
|
+
* Symmetrically, when the naive index lands BELOW `systemMessages.length` the
|
|
23
|
+
* cut sits inside the system prefix and the leading prompts are duplicated into
|
|
24
|
+
* `recentMessages`.
|
|
25
|
+
*
|
|
26
|
+
* The invariant these tests pin is the one a cut taken AT OR BELOW naive gives
|
|
27
|
+
* for free: a pass never removes more than the naive cut would, so at least
|
|
28
|
+
* `keepRecentMessages` original messages survive verbatim — or, when no safe cut
|
|
29
|
+
* exists at all, the pass is skipped and the transcript is untouched.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
33
|
+
|
|
34
|
+
import { WorkingStateManager } from '../../../../compaction/manager.js'
|
|
35
|
+
import { CompactionConfigSchema } from '../../../../config/runtime.js'
|
|
36
|
+
import type { RunId } from '../../../../types/ids/index.js'
|
|
37
|
+
import {
|
|
38
|
+
type Message,
|
|
39
|
+
createAssistantMessage,
|
|
40
|
+
createSystemMessage,
|
|
41
|
+
createToolMessage,
|
|
42
|
+
createUserMessage,
|
|
43
|
+
} from '../../../../types/message/index.js'
|
|
44
|
+
import type { Logger } from '../../../../utils/logger.js'
|
|
45
|
+
import { runCompactionCheck } from './compaction.js'
|
|
46
|
+
import type { IterationContext } from './context.js'
|
|
47
|
+
|
|
48
|
+
function makeLogger(): Logger {
|
|
49
|
+
const self = {
|
|
50
|
+
info: vi.fn(),
|
|
51
|
+
warn: vi.fn(),
|
|
52
|
+
error: vi.fn(),
|
|
53
|
+
debug: vi.fn(),
|
|
54
|
+
child: vi.fn(),
|
|
55
|
+
} as unknown as Logger
|
|
56
|
+
;(self as { child: (ctx: unknown) => Logger }).child = vi.fn(() => self)
|
|
57
|
+
return self
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Long enough that a handful of messages overflow a tiny budget. */
|
|
61
|
+
const FILLER = 'x'.repeat(200)
|
|
62
|
+
|
|
63
|
+
const KEEP_RECENT = 4
|
|
64
|
+
|
|
65
|
+
function makeCtx(opts: {
|
|
66
|
+
messages: Message[]
|
|
67
|
+
contextWindowTokens?: number
|
|
68
|
+
tokenBudget?: number
|
|
69
|
+
}): IterationContext {
|
|
70
|
+
const config = CompactionConfigSchema.parse({
|
|
71
|
+
strategy: 'structured',
|
|
72
|
+
llmVerification: false,
|
|
73
|
+
keepRecentMessages: KEEP_RECENT,
|
|
74
|
+
...(opts.contextWindowTokens !== undefined
|
|
75
|
+
? { contextWindowTokens: opts.contextWindowTokens }
|
|
76
|
+
: {}),
|
|
77
|
+
})
|
|
78
|
+
const manager = new WorkingStateManager(config)
|
|
79
|
+
manager.addDecision('built the report as .docx')
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
runConfig: { tokenBudget: opts.tokenBudget ?? 0 },
|
|
83
|
+
compactionConfig: config,
|
|
84
|
+
workingStateManager: manager,
|
|
85
|
+
log: makeLogger(),
|
|
86
|
+
runMgr: {
|
|
87
|
+
id: 'run_1' as RunId,
|
|
88
|
+
currentIteration: 3,
|
|
89
|
+
messages: opts.messages,
|
|
90
|
+
},
|
|
91
|
+
} as unknown as IterationContext
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function toolCall(id: string) {
|
|
95
|
+
return { id, type: 'function' as const, function: { name: 'read', arguments: '{}' } }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** How many of the ORIGINAL messages survived the pass, by identity. */
|
|
99
|
+
function survivorCount(before: readonly Message[], after: readonly Message[]): number {
|
|
100
|
+
const kept = new Set<Message>(after)
|
|
101
|
+
return before.filter((m) => kept.has(m)).length
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The exact shape the iteration loop holds when `runCompactionCheck` runs: the
|
|
106
|
+
* user's turn, one assistant that fanned out four parallel tool calls, and the
|
|
107
|
+
* four results that just landed. The next thing that happens is the model call —
|
|
108
|
+
* with whatever this function leaves behind.
|
|
109
|
+
*/
|
|
110
|
+
function buildParallelFanOutTail(): Message[] {
|
|
111
|
+
return [
|
|
112
|
+
createSystemMessage(`STATIC SYSTEM PROMPT ${FILLER}`, 'cache'),
|
|
113
|
+
createUserMessage(`please rename the heading to Q3 ${FILLER}`),
|
|
114
|
+
createAssistantMessage(`reading the sources ${FILLER}`, [
|
|
115
|
+
toolCall('a'),
|
|
116
|
+
toolCall('b'),
|
|
117
|
+
toolCall('c'),
|
|
118
|
+
toolCall('d'),
|
|
119
|
+
]),
|
|
120
|
+
createToolMessage(`result a ${FILLER}`, 'a'),
|
|
121
|
+
createToolMessage(`result b ${FILLER}`, 'b'),
|
|
122
|
+
createToolMessage(`result c ${FILLER}`, 'c'),
|
|
123
|
+
createToolMessage(`result d ${FILLER}`, 'd'),
|
|
124
|
+
]
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
describe('compaction — the unbounded cut', () => {
|
|
128
|
+
it('keeps at least keepRecentMessages messages verbatim when the tail is a parallel tool fan-out', async () => {
|
|
129
|
+
const messages = buildParallelFanOutTail()
|
|
130
|
+
const before = [...messages]
|
|
131
|
+
const ctx = makeCtx({ messages, contextWindowTokens: 100 })
|
|
132
|
+
|
|
133
|
+
await runCompactionCheck(ctx)
|
|
134
|
+
|
|
135
|
+
expect(survivorCount(before, messages)).toBeGreaterThanOrEqual(KEEP_RECENT)
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
it('never leaves a system-only transcript (nothing for the next turn to answer)', async () => {
|
|
139
|
+
const messages = buildParallelFanOutTail()
|
|
140
|
+
const ctx = makeCtx({ messages, contextWindowTokens: 100 })
|
|
141
|
+
|
|
142
|
+
await runCompactionCheck(ctx)
|
|
143
|
+
|
|
144
|
+
const nonSystem = messages.filter((m) => m.role !== 'system')
|
|
145
|
+
expect(nonSystem.length).toBeGreaterThan(0)
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
it('skips the pass, leaving the transcript intact, when no safe cut exists at or below naive', async () => {
|
|
149
|
+
// System prefix, then a single assistant fanning out six parallel calls.
|
|
150
|
+
// Every candidate boundary at or below naive splits that one pair-set, so
|
|
151
|
+
// there is nothing safe to cut to — skipping beats deleting the turn.
|
|
152
|
+
const ids = ['a', 'b', 'c', 'd', 'e', 'f']
|
|
153
|
+
const messages: Message[] = [
|
|
154
|
+
createSystemMessage(`STATIC SYSTEM PROMPT ${FILLER}`, 'cache'),
|
|
155
|
+
createAssistantMessage(`fanning out ${FILLER}`, ids.map(toolCall)),
|
|
156
|
+
...ids.map((id) => createToolMessage(`result ${id} ${FILLER}`, id)),
|
|
157
|
+
]
|
|
158
|
+
const before = [...messages]
|
|
159
|
+
const ctx = makeCtx({ messages, contextWindowTokens: 100 })
|
|
160
|
+
|
|
161
|
+
await runCompactionCheck(ctx)
|
|
162
|
+
|
|
163
|
+
expect(messages).toEqual(before)
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
it('does not duplicate the leading system prompts when the naive cut lands inside them', async () => {
|
|
167
|
+
// Legacy (tokenBudget) path: five leading system messages and only three
|
|
168
|
+
// conversational ones, so naive = 8 - 4 = 4 < systemMessages.length = 5.
|
|
169
|
+
const messages: Message[] = [
|
|
170
|
+
createSystemMessage(`SYS-1 ${FILLER}`, 'cache'),
|
|
171
|
+
createSystemMessage(`SYS-2 ${FILLER}`),
|
|
172
|
+
createSystemMessage(`SYS-3 ${FILLER}`),
|
|
173
|
+
createSystemMessage(`SYS-4 ${FILLER}`),
|
|
174
|
+
createSystemMessage(`SYS-5 UNIQUE-MARKER ${FILLER}`),
|
|
175
|
+
createUserMessage(`user 0 ${FILLER}`),
|
|
176
|
+
createAssistantMessage(`assistant 0 ${FILLER}`),
|
|
177
|
+
createUserMessage(`user 1 ${FILLER}`),
|
|
178
|
+
]
|
|
179
|
+
const ctx = makeCtx({ messages, tokenBudget: 100 })
|
|
180
|
+
|
|
181
|
+
await runCompactionCheck(ctx)
|
|
182
|
+
|
|
183
|
+
const marker = messages.filter((m) => m.content?.includes('UNIQUE-MARKER'))
|
|
184
|
+
expect(marker).toHaveLength(1)
|
|
185
|
+
})
|
|
186
|
+
})
|
|
@@ -94,18 +94,60 @@ export async function runCompactionCheck(ctx: IterationContext): Promise<void> {
|
|
|
94
94
|
}
|
|
95
95
|
if (systemMessages.length === 0) return
|
|
96
96
|
|
|
97
|
-
// Tool-pair atomicity guard
|
|
98
|
-
//
|
|
99
|
-
//
|
|
100
|
-
//
|
|
101
|
-
//
|
|
102
|
-
//
|
|
103
|
-
//
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
//
|
|
107
|
-
//
|
|
108
|
-
|
|
97
|
+
// Tool-pair atomicity guard, taken DOWNWARD.
|
|
98
|
+
//
|
|
99
|
+
// A naive cut at `length - keepRecentMessages` can land BETWEEN an
|
|
100
|
+
// assistant-with-toolCalls (dropped into `olderMessages`) and its `tool`
|
|
101
|
+
// results (kept in `recentMessages`), leaving orphaned `tool_result` blocks at
|
|
102
|
+
// the head of the recent window. The Anthropic provider then emits a
|
|
103
|
+
// `tool_result` with no matching `tool_use` and the API rejects the next turn
|
|
104
|
+
// with a 400 — so compaction, whose whole job is to keep a long run alive,
|
|
105
|
+
// instead kills it.
|
|
106
|
+
//
|
|
107
|
+
// Snapping FORWARD via `findSafeTrimIndex` fixes the orphan and introduces a
|
|
108
|
+
// worse failure. That walk skips leading `tool` messages with no stop short of
|
|
109
|
+
// `messages.length`, so whenever the entire suffix from the naive index is
|
|
110
|
+
// `tool` messages, the boundary lands ON `messages.length`: `recentMessages`
|
|
111
|
+
// comes back EMPTY and `[...preservedSystem, compactionMessage]` replaces the
|
|
112
|
+
// whole recent window. The model is then asked to answer a conversation whose
|
|
113
|
+
// last turn — including the user's own message — was deleted, and it answers a
|
|
114
|
+
// question nobody asked. The shape is routine, not exotic: one assistant turn
|
|
115
|
+
// fanning out `>= keepRecentMessages` parallel tool calls, measured at the
|
|
116
|
+
// start of the very next iteration, which is exactly where this runs. The
|
|
117
|
+
// `olderMessages` floor guard below cannot catch it either — in that shape
|
|
118
|
+
// `olderMessages` is the whole transcript.
|
|
119
|
+
//
|
|
120
|
+
// So take the LARGEST safe boundary AT OR BELOW naive instead. A cut that low
|
|
121
|
+
// removes no more than the naive cut would, so at least `keepRecentMessages`
|
|
122
|
+
// original messages always survive verbatim, and the transcript can never be
|
|
123
|
+
// reduced to system messages alone. `findSafeTrimIndex(m, k) === k` is the
|
|
124
|
+
// safety predicate — reused rather than reimplemented, so the function itself
|
|
125
|
+
// (public API, other callers) is untouched.
|
|
126
|
+
const naiveKeepStart = messages.length - config.keepRecentMessages
|
|
127
|
+
let keepStart = -1
|
|
128
|
+
for (let candidate = naiveKeepStart; candidate > systemMessages.length; candidate--) {
|
|
129
|
+
if (findSafeTrimIndex(messages, candidate) === candidate) {
|
|
130
|
+
keepStart = candidate
|
|
131
|
+
break
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// No safe boundary at or below naive. Either every candidate splits a pair-set
|
|
136
|
+
// (one assistant fanning out more calls than the recent window holds), or naive
|
|
137
|
+
// itself sits inside the leading system prefix — which would otherwise
|
|
138
|
+
// duplicate those prompts into `recentMessages`. Skipping costs one iteration's
|
|
139
|
+
// worth of context headroom; cutting anyway costs the live turn. The condition
|
|
140
|
+
// is self-clearing: the next assistant message moves naive past the tool block.
|
|
141
|
+
if (keepStart < 0) {
|
|
142
|
+
ctx.log.debug('Skipping compaction — no safe cut at or below the naive boundary', {
|
|
143
|
+
runId: ctx.runMgr.id,
|
|
144
|
+
naiveKeepStart,
|
|
145
|
+
systemMessages: systemMessages.length,
|
|
146
|
+
messageCount: messages.length,
|
|
147
|
+
})
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
|
|
109
151
|
const recentMessages = messages.slice(keepStart)
|
|
110
152
|
const olderMessages = messages.slice(systemMessages.length, keepStart)
|
|
111
153
|
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isProviderRequestError } from '../../../provider/errors.js'
|
|
1
2
|
import { mergeTokenUsage } from '../../../types/common/index.js'
|
|
2
3
|
import type { ToolUseId } from '../../../types/ids/index.js'
|
|
3
4
|
import type {
|
|
@@ -111,9 +112,12 @@ export async function* streamProviderTurn(
|
|
|
111
112
|
inputTruncated: boolean
|
|
112
113
|
}
|
|
113
114
|
>()
|
|
114
|
-
let streamError:
|
|
115
|
+
let streamError: Error | undefined
|
|
115
116
|
|
|
116
|
-
const stream = provider.chatStream({
|
|
117
|
+
const stream = provider.chatStream({
|
|
118
|
+
...params,
|
|
119
|
+
stream: true,
|
|
120
|
+
}) as AsyncIterable<StreamChunk>
|
|
117
121
|
|
|
118
122
|
// Drive the stream manually so each `.next()` can be RACED against the run
|
|
119
123
|
// abort: a Stop tears the in-flight model request down (the provider got
|
|
@@ -145,7 +149,7 @@ export async function* streamProviderTurn(
|
|
|
145
149
|
if (res.done) break
|
|
146
150
|
const chunk = res.value
|
|
147
151
|
if (chunk.error) {
|
|
148
|
-
streamError = chunk.error
|
|
152
|
+
streamError = new Error(`Provider stream error: ${chunk.error}`)
|
|
149
153
|
break
|
|
150
154
|
}
|
|
151
155
|
if (!id && chunk.id) id = chunk.id
|
|
@@ -252,7 +256,7 @@ export async function* streamProviderTurn(
|
|
|
252
256
|
// run as cancelled rather than recording a normal (errored) turn. Any
|
|
253
257
|
// other stream error is captured into the synthesized response as before.
|
|
254
258
|
if (signal?.aborted) throw err
|
|
255
|
-
streamError = err instanceof Error ? err
|
|
259
|
+
streamError = err instanceof Error ? err : new Error(String(err))
|
|
256
260
|
} finally {
|
|
257
261
|
if (onAbort) signal?.removeEventListener('abort', onAbort)
|
|
258
262
|
// Release the underlying connection on every exit (natural end, error,
|
|
@@ -355,7 +359,7 @@ export async function* streamProviderTurn(
|
|
|
355
359
|
log.warn('provider stream failed after tool input; surfacing tool call to executor', {
|
|
356
360
|
runId,
|
|
357
361
|
iteration,
|
|
358
|
-
error: streamError,
|
|
362
|
+
error: streamError?.message ?? 'provider stream failed',
|
|
359
363
|
toolCallCount: toolCalls.length,
|
|
360
364
|
})
|
|
361
365
|
}
|
|
@@ -378,7 +382,8 @@ export async function* streamProviderTurn(
|
|
|
378
382
|
yield* drainPending()
|
|
379
383
|
|
|
380
384
|
if (streamError && !recoveredToolInputFromStreamError) {
|
|
381
|
-
|
|
385
|
+
if (isProviderRequestError(streamError)) throw streamError
|
|
386
|
+
throw new Error(`Provider stream error: ${streamError.message}`)
|
|
382
387
|
}
|
|
383
388
|
|
|
384
389
|
const response: ChatCompletionResponse = {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type Span, SpanStatusCode } from '@opentelemetry/api'
|
|
2
2
|
import type { PlanManager } from '../../manager/plan/lifecycle.js'
|
|
3
3
|
import type { RunPersistence } from '../../manager/run/persistence.js'
|
|
4
|
+
import { isProviderRequestError } from '../../provider/errors.js'
|
|
4
5
|
import type { ActivityStore } from '../../store/activity/memory.js'
|
|
5
6
|
import { GENAI, NAMZU } from '../../telemetry/attributes.js'
|
|
6
7
|
import type { Run, RunEvent } from '../../types/run/index.js'
|
|
@@ -61,7 +62,15 @@ export class ResultAssembler {
|
|
|
61
62
|
async *handleError(err: unknown, rootSpan: Span): AsyncGenerator<RunEvent> {
|
|
62
63
|
const { runMgr, planManager, log, emitEvent, drainPending } = this.config
|
|
63
64
|
const errorMessage = toErrorMessage(err)
|
|
64
|
-
|
|
65
|
+
const providerError = isProviderRequestError(err)
|
|
66
|
+
? {
|
|
67
|
+
kind: err.kind,
|
|
68
|
+
providerId: err.providerId,
|
|
69
|
+
...(err.status !== undefined ? { status: err.status } : {}),
|
|
70
|
+
...(err.retryAfterMs !== undefined ? { retryAfterMs: err.retryAfterMs } : {}),
|
|
71
|
+
}
|
|
72
|
+
: undefined
|
|
73
|
+
runMgr.markFailed(errorMessage, providerError)
|
|
65
74
|
|
|
66
75
|
if (planManager.isActive) {
|
|
67
76
|
planManager.failPlan(errorMessage)
|
|
@@ -71,6 +80,7 @@ export class ResultAssembler {
|
|
|
71
80
|
type: 'run_failed',
|
|
72
81
|
runId: runMgr.id,
|
|
73
82
|
error: errorMessage,
|
|
83
|
+
...(providerError ? { providerError } : {}),
|
|
74
84
|
})
|
|
75
85
|
yield* drainPending()
|
|
76
86
|
|