@namzu/sdk 64.3.0 → 65.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 +24 -0
- package/dist/advisory/executor.d.ts +2 -1
- package/dist/advisory/executor.d.ts.map +1 -1
- package/dist/advisory/executor.js +8 -2
- package/dist/advisory/executor.js.map +1 -1
- package/dist/agents/explore.js +1 -1
- package/dist/agents/explore.js.map +1 -1
- package/dist/agents/plan.js +1 -1
- package/dist/agents/plan.js.map +1 -1
- package/dist/compaction/context-window.d.ts.map +1 -1
- package/dist/compaction/context-window.js +9 -2
- package/dist/compaction/context-window.js.map +1 -1
- package/dist/eval/judge.d.ts.map +1 -1
- package/dist/eval/judge.js +6 -2
- package/dist/eval/judge.js.map +1 -1
- package/dist/manager/agent/lifecycle.d.ts +1 -0
- package/dist/manager/agent/lifecycle.d.ts.map +1 -1
- package/dist/manager/agent/lifecycle.js +20 -6
- package/dist/manager/agent/lifecycle.js.map +1 -1
- package/dist/manager/session/turn-recorder.d.ts.map +1 -1
- package/dist/manager/session/turn-recorder.js +11 -2
- package/dist/manager/session/turn-recorder.js.map +1 -1
- package/dist/prompt/coding-agent-doctrine.d.ts +2 -2
- package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
- package/dist/prompt/coding-agent-doctrine.js +39 -38
- package/dist/prompt/coding-agent-doctrine.js.map +1 -1
- package/dist/provider/fallback.d.ts.map +1 -1
- package/dist/provider/fallback.js +4 -3
- package/dist/provider/fallback.js.map +1 -1
- package/dist/provider/idle-timeout.js +1 -1
- package/dist/provider/idle-timeout.js.map +1 -1
- package/dist/provider/instrumentation.js +1 -1
- package/dist/provider/instrumentation.js.map +1 -1
- package/dist/provider/retry.js +1 -1
- package/dist/provider/retry.js.map +1 -1
- package/dist/provider/side-request-reasoning.d.ts +32 -0
- package/dist/provider/side-request-reasoning.d.ts.map +1 -0
- package/dist/provider/side-request-reasoning.js +97 -0
- package/dist/provider/side-request-reasoning.js.map +1 -0
- package/dist/public-runtime.d.ts +3 -1
- package/dist/public-runtime.d.ts.map +1 -1
- package/dist/public-runtime.js +2 -1
- package/dist/public-runtime.js.map +1 -1
- package/dist/runtime/query/auto-review/classifier.d.ts.map +1 -1
- package/dist/runtime/query/auto-review/classifier.js +8 -2
- package/dist/runtime/query/auto-review/classifier.js.map +1 -1
- package/dist/runtime/query/callback-inference.d.ts.map +1 -1
- package/dist/runtime/query/callback-inference.js +14 -3
- package/dist/runtime/query/callback-inference.js.map +1 -1
- package/dist/runtime/query/iteration/index.d.ts +17 -0
- package/dist/runtime/query/iteration/index.d.ts.map +1 -1
- package/dist/runtime/query/iteration/index.js +82 -10
- package/dist/runtime/query/iteration/index.js.map +1 -1
- package/dist/runtime/query/prepare-turn.d.ts.map +1 -1
- package/dist/runtime/query/prepare-turn.js +3 -0
- package/dist/runtime/query/prepare-turn.js.map +1 -1
- package/dist/runtime/query/repeat-call.js +2 -2
- package/dist/runtime/query/repeat-call.js.map +1 -1
- package/dist/runtime/query/turn/stall-monitor.d.ts +47 -2
- package/dist/runtime/query/turn/stall-monitor.d.ts.map +1 -1
- package/dist/runtime/query/turn/stall-monitor.js +72 -4
- package/dist/runtime/query/turn/stall-monitor.js.map +1 -1
- package/dist/turn/evidence-query.d.ts.map +1 -1
- package/dist/turn/evidence-query.js +7 -1
- package/dist/turn/evidence-query.js.map +1 -1
- package/dist/types/common/index.d.ts +14 -0
- package/dist/types/common/index.d.ts.map +1 -1
- package/dist/types/common/index.js +7 -0
- package/dist/types/common/index.js.map +1 -1
- package/dist/types/provider/config.d.ts +6 -0
- package/dist/types/provider/config.d.ts.map +1 -1
- package/dist/types/provider/interface.d.ts +8 -6
- package/dist/types/provider/interface.d.ts.map +1 -1
- package/dist/types/session/prepare-step.d.ts +7 -0
- package/dist/types/session/prepare-step.d.ts.map +1 -1
- package/dist/utils/cost.d.ts +14 -0
- package/dist/utils/cost.d.ts.map +1 -1
- package/dist/utils/cost.js +20 -0
- package/dist/utils/cost.js.map +1 -1
- package/package.json +1 -1
- package/src/advisory/executor.ts +13 -2
- package/src/agents/explore.ts +1 -1
- package/src/agents/plan.ts +1 -1
- package/src/compaction/context-window.ts +9 -2
- package/src/eval/judge.ts +16 -9
- package/src/manager/agent/lifecycle.ts +19 -6
- package/src/manager/session/turn-recorder.ts +12 -1
- package/src/prompt/coding-agent-doctrine.ts +40 -39
- package/src/provider/fallback.ts +4 -3
- package/src/provider/idle-timeout.ts +1 -1
- package/src/provider/instrumentation.ts +1 -1
- package/src/provider/retry.ts +1 -1
- package/src/provider/side-request-reasoning.ts +121 -0
- package/src/public-runtime.ts +7 -0
- package/src/runtime/query/auto-review/classifier.ts +17 -9
- package/src/runtime/query/callback-inference.ts +13 -3
- package/src/runtime/query/iteration/index.ts +93 -12
- package/src/runtime/query/prepare-turn.ts +2 -0
- package/src/runtime/query/repeat-call.ts +2 -2
- package/src/runtime/query/turn/stall-monitor.ts +92 -4
- package/src/turn/evidence-query.ts +8 -1
- package/src/types/common/index.ts +22 -0
- package/src/types/provider/config.ts +6 -0
- package/src/types/provider/interface.ts +8 -6
- package/src/types/session/prepare-step.ts +7 -0
- package/src/utils/cost.ts +24 -0
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ChatCompletionParams,
|
|
3
|
+
LLMProvider,
|
|
4
|
+
ReasoningEffort,
|
|
5
|
+
StreamChunk,
|
|
6
|
+
ThinkingConfig,
|
|
7
|
+
} from '../types/provider/index.js'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Room added to a side request's answer allowance when the provider could not
|
|
11
|
+
* promise that reasoning is off. A thinking model spends tokens on reasoning
|
|
12
|
+
* before the first word of the answer, and a small answer allowance is gone by
|
|
13
|
+
* then: the reply is cut off with nothing in it.
|
|
14
|
+
*/
|
|
15
|
+
export const SIDE_REQUEST_REASONING_HEADROOM = 2048
|
|
16
|
+
|
|
17
|
+
const DISABLED: ThinkingConfig = { type: 'disabled' }
|
|
18
|
+
|
|
19
|
+
/** Efforts a driver may offer for "as little as possible", cheapest first. */
|
|
20
|
+
const LOWEST_FIRST: readonly ReasoningEffort[] = ['none', 'minimal', 'low', 'medium']
|
|
21
|
+
|
|
22
|
+
/** The request fields a side request sets: thinking, effort and the answer allowance. */
|
|
23
|
+
export type SideReasoningFields = Pick<ChatCompletionParams, 'thinking' | 'effort' | 'maxTokens'>
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The reasoning settings for a small request made beside a turn (a lookup, a
|
|
27
|
+
* label, a title, a classifier): ask the provider for no reasoning where it can
|
|
28
|
+
* switch it off for one request, and where it cannot, leave room in the answer
|
|
29
|
+
* allowance for the reasoning it will spend.
|
|
30
|
+
*
|
|
31
|
+
* The turn's own thinking and effort are never inherited: a side request is not
|
|
32
|
+
* the turn, and a high effort chosen for the turn's work would starve a
|
|
33
|
+
* 60-token label. The turn's own requests are not touched by this.
|
|
34
|
+
*
|
|
35
|
+
* Each driver answers through `reasoningEffortLevelsFor(model, disabled)`:
|
|
36
|
+
* - a list that holds `none`: send thinking disabled and effort `none`;
|
|
37
|
+
* - a list without `none` (effort is still offered beside a disabled body): send
|
|
38
|
+
* thinking disabled and the lowest level it offers, and add headroom;
|
|
39
|
+
* - no answer: send thinking disabled, which every driver either carries or
|
|
40
|
+
* leaves out, and add headroom because nothing confirms it took effect.
|
|
41
|
+
*/
|
|
42
|
+
export function sideRequestReasoning(
|
|
43
|
+
provider: Pick<LLMProvider, 'reasoningEffortLevelsFor'>,
|
|
44
|
+
model: string,
|
|
45
|
+
maxTokens: number,
|
|
46
|
+
): SideReasoningFields {
|
|
47
|
+
let levels: readonly ReasoningEffort[] | undefined
|
|
48
|
+
try {
|
|
49
|
+
levels = provider.reasoningEffortLevelsFor?.(model, DISABLED)
|
|
50
|
+
} catch {
|
|
51
|
+
levels = undefined
|
|
52
|
+
}
|
|
53
|
+
if (levels?.includes('none')) {
|
|
54
|
+
return { thinking: DISABLED, effort: 'none', maxTokens }
|
|
55
|
+
}
|
|
56
|
+
const roomy = maxTokens + SIDE_REQUEST_REASONING_HEADROOM
|
|
57
|
+
if (levels !== undefined && levels.length > 0) {
|
|
58
|
+
const lowest = LOWEST_FIRST.find((level) => levels.includes(level)) ?? levels[0]
|
|
59
|
+
// The levels were asked with thinking disabled, so the driver accepts a
|
|
60
|
+
// disabled body here; send it so reasoning is off, not merely cheap.
|
|
61
|
+
return { thinking: DISABLED, ...(lowest ? { effort: lowest } : {}), maxTokens: roomy }
|
|
62
|
+
}
|
|
63
|
+
return { thinking: DISABLED, maxTokens: roomy }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A refusal of the reasoning controls themselves, before any output. */
|
|
67
|
+
function refusesReasoningControls(error: unknown): boolean {
|
|
68
|
+
const text = error instanceof Error ? error.message : String(error)
|
|
69
|
+
// An error that merely mentions the words (a rate limit, an overload, a
|
|
70
|
+
// timeout) is not a refusal of the controls: it must neither cost an extra
|
|
71
|
+
// request nor switch the controls off for the model.
|
|
72
|
+
if (/rate.?limit|too many requests|overloaded|timed? ?out|\b(429|5\d\d)\b/i.test(text))
|
|
73
|
+
return false
|
|
74
|
+
const names = /\b(thinking|reasoning|effort)\b/i.test(text)
|
|
75
|
+
const rejects =
|
|
76
|
+
/unsupported|not supported|unsupport|invalid|unknown|unrecogni[sz]ed|unexpected|not allowed|not permitted|does not (?:accept|support|allow)|not accept|extra inputs|bad request|\b400\b|\b422\b/i.test(
|
|
77
|
+
text,
|
|
78
|
+
)
|
|
79
|
+
return names && rejects
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Stream a side request with {@link sideRequestReasoning} applied. A driver that
|
|
84
|
+
* refuses the reasoning controls before sending anything gets the request again
|
|
85
|
+
* without them, at the roomy allowance, and the model is remembered so the next
|
|
86
|
+
* request does not ask again. Any other failure is thrown unchanged.
|
|
87
|
+
*/
|
|
88
|
+
const noControls = new WeakMap<object, Set<string>>()
|
|
89
|
+
|
|
90
|
+
export async function* chatStreamForSideRequest(
|
|
91
|
+
provider: LLMProvider,
|
|
92
|
+
params: Omit<ChatCompletionParams, 'thinking' | 'effort'>,
|
|
93
|
+
/** How the request is sent; a caller with its own repair layer passes it. */
|
|
94
|
+
send: (request: ChatCompletionParams) => AsyncIterable<StreamChunk> = (request) =>
|
|
95
|
+
provider.chatStream(request),
|
|
96
|
+
): AsyncGenerator<StreamChunk> {
|
|
97
|
+
const base = params.maxTokens ?? 256
|
|
98
|
+
const skip = noControls.get(provider)?.has(params.model) === true
|
|
99
|
+
const fields = sideRequestReasoning(provider, params.model, base)
|
|
100
|
+
const plain: ChatCompletionParams = {
|
|
101
|
+
...params,
|
|
102
|
+
maxTokens: base + SIDE_REQUEST_REASONING_HEADROOM,
|
|
103
|
+
}
|
|
104
|
+
if (skip) {
|
|
105
|
+
yield* send(plain)
|
|
106
|
+
return
|
|
107
|
+
}
|
|
108
|
+
let yielded = false
|
|
109
|
+
try {
|
|
110
|
+
for await (const chunk of send({ ...params, ...fields })) {
|
|
111
|
+
yielded = true
|
|
112
|
+
yield chunk
|
|
113
|
+
}
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (yielded || params.signal?.aborted || !refusesReasoningControls(error)) throw error
|
|
116
|
+
const seen = noControls.get(provider) ?? new Set<string>()
|
|
117
|
+
seen.add(params.model)
|
|
118
|
+
noControls.set(provider, seen)
|
|
119
|
+
yield* send(plain)
|
|
120
|
+
}
|
|
121
|
+
}
|
package/src/public-runtime.ts
CHANGED
|
@@ -126,6 +126,7 @@ export * from './utils/id.js'
|
|
|
126
126
|
|
|
127
127
|
export {
|
|
128
128
|
accumulateCost,
|
|
129
|
+
accumulateReportedCost,
|
|
129
130
|
accumulateUnpricedCost,
|
|
130
131
|
calculateCost,
|
|
131
132
|
describeCost,
|
|
@@ -1196,6 +1197,12 @@ export { wrapProviderWithProbes } from './provider/instrumentation.js'
|
|
|
1196
1197
|
export type { ProviderInstrumentationOptions } from './provider/instrumentation.js'
|
|
1197
1198
|
export type { ResolvedProviderCapabilities } from './provider/capabilities.js'
|
|
1198
1199
|
export { collectChatCompletion } from './provider/collect-chat-completion.js'
|
|
1200
|
+
export {
|
|
1201
|
+
chatStreamForSideRequest,
|
|
1202
|
+
sideRequestReasoning,
|
|
1203
|
+
SIDE_REQUEST_REASONING_HEADROOM,
|
|
1204
|
+
} from './provider/side-request-reasoning.js'
|
|
1205
|
+
export type { SideReasoningFields } from './provider/side-request-reasoning.js'
|
|
1199
1206
|
export { withModelWindowSuffixStripped } from './provider/model-window-suffix.js'
|
|
1200
1207
|
|
|
1201
1208
|
// Old spellings of renamed exports, still live for one deprecation window.
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
|
|
22
22
|
import { GENAI } from '../../../constants/telemetry/index.js'
|
|
23
23
|
import { collectChatCompletion } from '../../../provider/collect-chat-completion.js'
|
|
24
|
+
import { chatStreamForSideRequest } from '../../../provider/side-request-reasoning.js'
|
|
24
25
|
import type { ToolManager } from '../../../toolsets/manager.js'
|
|
25
26
|
import type { TokenUsage } from '../../../types/common/index.js'
|
|
26
27
|
import type { LaunchedScript, ToolCallSummary } from '../../../types/hitl/index.js'
|
|
@@ -216,16 +217,23 @@ export function createAutoReviewClassifier(
|
|
|
216
217
|
// Raced against the abort, not only handed the signal: a provider that
|
|
217
218
|
// ignores it would otherwise hold the call open past its deadline, and
|
|
218
219
|
// a turn cancelled while it waits would wait with it.
|
|
220
|
+
const request = {
|
|
221
|
+
model: options.model,
|
|
222
|
+
messages,
|
|
223
|
+
maxTokens: stage === 1 ? 64 : 8_192,
|
|
224
|
+
temperature: options.temperature ?? 0,
|
|
225
|
+
...(stage === 1 ? { stop: [VERDICT_STOP] } : {}),
|
|
226
|
+
cacheControl: { type: 'auto' as const },
|
|
227
|
+
signal: controller.signal,
|
|
228
|
+
}
|
|
229
|
+
// The quick pass answers in 64 tokens, so it asks for no reasoning
|
|
230
|
+
// (or leaves room for it); the reasoned pass has its own large budget.
|
|
219
231
|
const collected = collectChatCompletion(
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
...(stage === 1 ? { stop: [VERDICT_STOP] } : {}),
|
|
226
|
-
cacheControl: { type: 'auto' },
|
|
227
|
-
signal: controller.signal,
|
|
228
|
-
}),
|
|
232
|
+
stage === 1
|
|
233
|
+
? chatStreamForSideRequest(options.provider, request, (sent) =>
|
|
234
|
+
chatStreamWithSamplingRepair(options.provider, sent),
|
|
235
|
+
)
|
|
236
|
+
: chatStreamWithSamplingRepair(options.provider, request),
|
|
229
237
|
)
|
|
230
238
|
collected.catch(() => {})
|
|
231
239
|
const cutOff = new Promise<never>((_resolve, reject) => {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
|
+
import { chatStreamForSideRequest } from '../../provider/side-request-reasoning.js'
|
|
2
3
|
import { StreamTextAccumulator } from '../../provider/stream-text.js'
|
|
3
4
|
import { type TokenUsage, mergeTokenUsage } from '../../types/common/index.js'
|
|
4
5
|
import { createSystemMessage, createUserMessage } from '../../types/message/index.js'
|
|
@@ -69,15 +70,19 @@ export function createCallbackInference(
|
|
|
69
70
|
const text = new StreamTextAccumulator()
|
|
70
71
|
let invalidOutput: string | undefined
|
|
71
72
|
let usage: TokenUsage | undefined
|
|
73
|
+
let finishReason: PreparationTextResult['finishReason']
|
|
72
74
|
try {
|
|
73
|
-
|
|
75
|
+
// A small request beside the turn: reasoning off where the driver
|
|
76
|
+
// can switch it off for one request, room for it where it cannot.
|
|
77
|
+
// The turn's own thinking and effort stay the turn's.
|
|
78
|
+
for await (const chunk of chatStreamForSideRequest(ctx.provider, {
|
|
74
79
|
model,
|
|
75
80
|
providerRoute: route(),
|
|
76
81
|
messages: [createSystemMessage(input.system), createUserMessage(input.prompt)],
|
|
77
82
|
maxTokens: input.maxTokens,
|
|
78
|
-
...(ctx.turnConfig.effort ? { effort: ctx.turnConfig.effort } : {}),
|
|
79
83
|
signal,
|
|
80
84
|
})) {
|
|
85
|
+
if (chunk.finishReason) finishReason = chunk.finishReason
|
|
81
86
|
if (chunk.usage) usage = usage ? mergeTokenUsage(usage, chunk.usage) : { ...chunk.usage }
|
|
82
87
|
if (chunk.error) throw new Error(chunk.error)
|
|
83
88
|
signal.throwIfAborted()
|
|
@@ -91,7 +96,12 @@ export function createCallbackInference(
|
|
|
91
96
|
signal.throwIfAborted()
|
|
92
97
|
if (!usage) throw new Error(`${label} inference ended without usage.`)
|
|
93
98
|
if (invalidOutput) throw new Error(invalidOutput)
|
|
94
|
-
return {
|
|
99
|
+
return {
|
|
100
|
+
text: text.text,
|
|
101
|
+
usage,
|
|
102
|
+
servedBy: route(),
|
|
103
|
+
...(finishReason ? { finishReason } : {}),
|
|
104
|
+
}
|
|
95
105
|
} finally {
|
|
96
106
|
if (usage) ctx.recorder.accumulateUsage(usage, route())
|
|
97
107
|
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
1
2
|
import { type Span, SpanStatusCode } from '@opentelemetry/api'
|
|
2
3
|
import {
|
|
3
4
|
extractFromAssistantMessage,
|
|
4
5
|
extractFromUserMessage,
|
|
5
6
|
} from '../../../compaction/extractor.js'
|
|
6
7
|
import { estimateMessageTokens } from '../../../compaction/token-estimate.js'
|
|
8
|
+
import { EDIT_TOOLS } from '../../../constants/compaction/index.js'
|
|
7
9
|
import {
|
|
8
10
|
AUTO_CONTINUATION_USER_MESSAGE,
|
|
9
11
|
REASONING_CUT_USER_MESSAGE,
|
|
@@ -91,7 +93,10 @@ import {
|
|
|
91
93
|
REASONING_CAPPED_MESSAGE,
|
|
92
94
|
REASONING_ONLY_MESSAGE,
|
|
93
95
|
StallMonitor,
|
|
96
|
+
asksQuestion,
|
|
94
97
|
callChangedState,
|
|
98
|
+
callMadeProgress,
|
|
99
|
+
isSetAsideTool,
|
|
95
100
|
reasoningCapChars,
|
|
96
101
|
} from '../turn/stall-monitor.js'
|
|
97
102
|
import { effortForModel } from './effort-clamp.js'
|
|
@@ -948,6 +953,7 @@ export class IterationOrchestrator {
|
|
|
948
953
|
this.ctx.structuredOutput?.mode !== 'native' ||
|
|
949
954
|
tool.function.name !== STRUCTURED_OUTPUT_TOOL_NAME,
|
|
950
955
|
)
|
|
956
|
+
this.stepCannotChange = this.toolsCannotChange(llmTools)
|
|
951
957
|
// The same list the request was built from now also bounds what
|
|
952
958
|
// may run. Narrowing only the request left the restriction
|
|
953
959
|
// presentational — the model was shown fewer tools and could
|
|
@@ -1229,16 +1235,31 @@ export class IterationOrchestrator {
|
|
|
1229
1235
|
forcedAction && requestEffort && (offeredEfforts?.includes('low') ?? false)
|
|
1230
1236
|
? 'low'
|
|
1231
1237
|
: requestEffort
|
|
1232
|
-
// A
|
|
1233
|
-
//
|
|
1234
|
-
//
|
|
1238
|
+
// A guard's action step sends a forced tool choice only where the
|
|
1239
|
+
// provider says one is safe and thinking is off for the request.
|
|
1240
|
+
// Every other case (a refusal, no answer, thinking on) asks in
|
|
1241
|
+
// words, on this request only, and keeps the step's low effort.
|
|
1242
|
+
//
|
|
1243
|
+
// A choice the step itself set (`step.toolChoice`) is a forced choice
|
|
1244
|
+
// whoever set it: `required` or a named function is dropped, and asked
|
|
1245
|
+
// in words, when the provider says it would refuse it.
|
|
1246
|
+
const stepChoiceForced =
|
|
1247
|
+
step.toolChoice !== undefined &&
|
|
1248
|
+
step.toolChoice !== 'auto' &&
|
|
1249
|
+
step.toolChoice !== 'none'
|
|
1250
|
+
const thinkingOn =
|
|
1251
|
+
turnConfig.thinking !== undefined && turnConfig.thinking.type !== 'disabled'
|
|
1252
|
+
const forcedChoiceAnswer =
|
|
1253
|
+
forcedAction || stepChoiceForced
|
|
1254
|
+
? this.ctx.provider.acceptsForcedToolChoiceFor?.(
|
|
1255
|
+
stepModel,
|
|
1256
|
+
turnConfig.thinking,
|
|
1257
|
+
stepEffort,
|
|
1258
|
+
)
|
|
1259
|
+
: undefined
|
|
1235
1260
|
const forcedChoiceRefused =
|
|
1236
|
-
forcedAction &&
|
|
1237
|
-
|
|
1238
|
-
stepModel,
|
|
1239
|
-
turnConfig.thinking,
|
|
1240
|
-
stepEffort,
|
|
1241
|
-
) === false
|
|
1261
|
+
(forcedAction && (forcedChoiceAnswer !== true || thinkingOn)) ||
|
|
1262
|
+
(!forcedAction && stepChoiceForced && forcedChoiceAnswer === false)
|
|
1242
1263
|
const operatorInputAtDispatch = this.latestUserMessage
|
|
1243
1264
|
const latestReviewUserMessage =
|
|
1244
1265
|
(this.ctx.reviewAnswer || this.ctx.structuredOutput?.review) && operatorInputAtDispatch
|
|
@@ -1282,7 +1303,9 @@ export class IterationOrchestrator {
|
|
|
1282
1303
|
: llmTools.length > 0
|
|
1283
1304
|
? forcedAction && !forcedChoiceRefused
|
|
1284
1305
|
? (step.toolChoice ?? 'required')
|
|
1285
|
-
:
|
|
1306
|
+
: stepChoiceForced && forcedChoiceRefused
|
|
1307
|
+
? undefined
|
|
1308
|
+
: step.toolChoice
|
|
1286
1309
|
: undefined,
|
|
1287
1310
|
temperature: step.temperature ?? turnConfig.temperature,
|
|
1288
1311
|
maxTokens:
|
|
@@ -3612,6 +3635,8 @@ export class IterationOrchestrator {
|
|
|
3612
3635
|
if (!monitor) return
|
|
3613
3636
|
const calls = new Map((response.message.toolCalls ?? []).map((c) => [c.id, c]))
|
|
3614
3637
|
let changedState = false
|
|
3638
|
+
const question = asksQuestion(this.latestUserMessage?.content)
|
|
3639
|
+
const cannotChange = this.stepCannotChange
|
|
3615
3640
|
for (const result of results) {
|
|
3616
3641
|
const call = calls.get(result.toolCallId)
|
|
3617
3642
|
let readOnly: boolean | undefined
|
|
@@ -3621,13 +3646,29 @@ export class IterationOrchestrator {
|
|
|
3621
3646
|
} catch {
|
|
3622
3647
|
readOnly = undefined
|
|
3623
3648
|
}
|
|
3624
|
-
if (
|
|
3649
|
+
if (callMadeProgress(result.toolName, readOnly, result.isError, cannotChange)) {
|
|
3650
|
+
// The same tool with the same input and the same result as an
|
|
3651
|
+
// earlier call this turn changed nothing, whatever the tool is,
|
|
3652
|
+
// except a file edit: applying, reverting and applying again is
|
|
3653
|
+
// deliberate work whose reply is the same each time.
|
|
3654
|
+
if (
|
|
3655
|
+
EDIT_TOOLS.has(result.toolName) ||
|
|
3656
|
+
!this.seenAgain(result.toolName, call, result.output)
|
|
3657
|
+
) {
|
|
3658
|
+
changedState = true
|
|
3659
|
+
}
|
|
3660
|
+
}
|
|
3625
3661
|
}
|
|
3626
3662
|
const reasoningChars = (response.message.reasoning ?? []).reduce(
|
|
3627
3663
|
(n, block) => n + (block.text?.length ?? 0),
|
|
3628
3664
|
0,
|
|
3629
3665
|
)
|
|
3630
|
-
const directive = monitor.observe({
|
|
3666
|
+
const directive = monitor.observe({
|
|
3667
|
+
reasoningChars,
|
|
3668
|
+
changedState,
|
|
3669
|
+
question,
|
|
3670
|
+
cannotChange,
|
|
3671
|
+
})
|
|
3631
3672
|
if (directive.kind === 'nudge') {
|
|
3632
3673
|
this.ctx.log.info('Many steps without a change — nudging the model to act', {
|
|
3633
3674
|
[NAMZU.TURN_ID]: this.ctx.recorder.turnId,
|
|
@@ -3641,6 +3682,46 @@ export class IterationOrchestrator {
|
|
|
3641
3682
|
}
|
|
3642
3683
|
}
|
|
3643
3684
|
|
|
3685
|
+
/** Whether every tool offered to the step in flight only reads. */
|
|
3686
|
+
private stepCannotChange = false
|
|
3687
|
+
|
|
3688
|
+
/**
|
|
3689
|
+
* Whether an agent given these tools can change nothing: each one declares
|
|
3690
|
+
* itself read-only without being shown an input (the test the read-only
|
|
3691
|
+
* sub-agents' roster uses), task-list tools and `send_message` aside. A tool that does not say,
|
|
3692
|
+
* or that says so only for some inputs, counts as one that can change things.
|
|
3693
|
+
*/
|
|
3694
|
+
private toolsCannotChange(llmTools: readonly { function: { name: string } }[]): boolean {
|
|
3695
|
+
let looked = false
|
|
3696
|
+
for (const { function: fn } of llmTools) {
|
|
3697
|
+
if (isSetAsideTool(fn.name)) continue
|
|
3698
|
+
try {
|
|
3699
|
+
if (this.ctx.tools.get(fn.name)?.isReadOnly?.(undefined) !== true) return false
|
|
3700
|
+
} catch {
|
|
3701
|
+
return false
|
|
3702
|
+
}
|
|
3703
|
+
looked = true
|
|
3704
|
+
}
|
|
3705
|
+
return looked
|
|
3706
|
+
}
|
|
3707
|
+
|
|
3708
|
+
/** Fingerprints of the calls this turn has finished, for {@link seenAgain}. */
|
|
3709
|
+
private readonly finishedCalls = new Set<string>()
|
|
3710
|
+
|
|
3711
|
+
/**
|
|
3712
|
+
* Whether this call, with this input and this output, was already finished
|
|
3713
|
+
* earlier in the turn; records it either way. A call that gave the same
|
|
3714
|
+
* answer twice did not move anything the second time.
|
|
3715
|
+
*/
|
|
3716
|
+
private seenAgain(toolName: string, call: ToolCall | undefined, output: string): boolean {
|
|
3717
|
+
const key = createHash('sha256')
|
|
3718
|
+
.update(`${toolName}\0${call?.function.arguments ?? ''}\0${output}`)
|
|
3719
|
+
.digest('hex')
|
|
3720
|
+
if (this.finishedCalls.has(key)) return true
|
|
3721
|
+
this.finishedCalls.add(key)
|
|
3722
|
+
return false
|
|
3723
|
+
}
|
|
3724
|
+
|
|
3644
3725
|
private async requestFinalResponse(
|
|
3645
3726
|
model: string,
|
|
3646
3727
|
reason: StopReason,
|
|
@@ -189,6 +189,8 @@ function assertBudgetIsMeasurable(params: QueryParams): void {
|
|
|
189
189
|
// A host-supplied table prices whatever it is pointed at, so a caller who
|
|
190
190
|
// brought one has answered the question themselves.
|
|
191
191
|
if (params.pricing !== undefined) return
|
|
192
|
+
// A driver that reports each call's billed cost measures the limit itself.
|
|
193
|
+
if (params.provider.capabilities?.reportsRequestCost === true) return
|
|
192
194
|
const model = params.turnConfig.model
|
|
193
195
|
if (resolveModelPricing(params.provider.id, model) !== undefined) return
|
|
194
196
|
|
|
@@ -95,7 +95,7 @@ export class RepeatCallTracker {
|
|
|
95
95
|
toolName,
|
|
96
96
|
count,
|
|
97
97
|
level: 'escalated',
|
|
98
|
-
text: `You have now called \`${toolName}\` with identical arguments ${count} times in this turn. Check whether the results or the state have changed. If there is no progress, change the approach or tell the user what is
|
|
98
|
+
text: `You have now called \`${toolName}\` with identical arguments ${count} times in this turn. Check whether the results or the state have changed. If there is no progress, change the approach, or answer with what you have and tell the user what is missing.`,
|
|
99
99
|
}
|
|
100
100
|
}
|
|
101
101
|
if (count >= this.thresholds.notifyAfter && already === undefined) {
|
|
@@ -104,7 +104,7 @@ export class RepeatCallTracker {
|
|
|
104
104
|
toolName,
|
|
105
105
|
count,
|
|
106
106
|
level: 'notice',
|
|
107
|
-
text: `Note: this is call ${count} of \`${toolName}\` with identical arguments in this turn. If the previous results were not what you needed,
|
|
107
|
+
text: `Note: this is call ${count} of \`${toolName}\` with identical arguments in this turn. If the previous results were not what you needed, change the arguments, or answer with what you already have and say what is missing.`,
|
|
108
108
|
}
|
|
109
109
|
}
|
|
110
110
|
return undefined
|
|
@@ -12,7 +12,7 @@ import type { ReasoningEffort } from '../../../types/provider/index.js'
|
|
|
12
12
|
|
|
13
13
|
/** What the model is told when a step spent its whole reasoning allowance before acting. */
|
|
14
14
|
export const REASONING_CAPPED_MESSAGE =
|
|
15
|
-
'Your thinking for that step reached its limit before you acted, so it was cut short. Act now on what you already know: make the first change, or
|
|
15
|
+
'Your thinking for that step reached its limit before you acted, so it was cut short. Act now on what you already know: make the first change, or, if you were asked a question, answer with what you have and say what is missing. Refine as you go; do not plan the whole task again.'
|
|
16
16
|
|
|
17
17
|
/** What the model is told when a reply held thinking but no answer and no action. */
|
|
18
18
|
export const REASONING_ONLY_MESSAGE =
|
|
@@ -20,7 +20,21 @@ export const REASONING_ONLY_MESSAGE =
|
|
|
20
20
|
|
|
21
21
|
/** What the model is told when several steps passed with nothing changed. */
|
|
22
22
|
export const STALL_NUDGE_MESSAGE =
|
|
23
|
-
'Several steps have passed and nothing has changed yet. Begin changing things now: make the first edit you are sure of
|
|
23
|
+
'Several steps have passed and nothing has changed yet. Begin changing things now: make the first edit you are sure of. If you were asked a question, answer it now with what you have and say what is missing. Reading more or planning again will not move the task.'
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* What an agent that cannot change anything is told when its looks stopped
|
|
27
|
+
* adding anything new: it reports, it does not edit.
|
|
28
|
+
*/
|
|
29
|
+
export const STALL_REPORT_MESSAGE =
|
|
30
|
+
'The last steps have not turned up anything new. Report now what you have found and what is still unknown, using what you have already seen. Do not repeat a look you have already made.'
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* What the model is told when it was asked a question and several steps have
|
|
34
|
+
* only looked. It names the way out as the answer, never as another command.
|
|
35
|
+
*/
|
|
36
|
+
export const ANSWER_NOW_MESSAGE =
|
|
37
|
+
'You were asked a question and the last steps only looked around. Answer it now, in the language the person used and within what they asked for, using what you have already seen. If something is still missing, say what it is instead of running another command. Do not open with an apology.'
|
|
24
38
|
|
|
25
39
|
/**
|
|
26
40
|
* Said again, on one request only, when a step must act but the provider
|
|
@@ -89,6 +103,34 @@ export function callChangedState(
|
|
|
89
103
|
return readOnly !== true
|
|
90
104
|
}
|
|
91
105
|
|
|
106
|
+
/**
|
|
107
|
+
* Whether a finished call moved an agent forward. For an agent that can change
|
|
108
|
+
* things this is {@link callChangedState}. An agent whose every tool only
|
|
109
|
+
* reads has nothing to change, so a successful read that is not a repeat is
|
|
110
|
+
* its progress; repeats are judged by the caller, and a task-list call or a
|
|
111
|
+
* failed call is still none.
|
|
112
|
+
*/
|
|
113
|
+
export function callMadeProgress(
|
|
114
|
+
toolName: string,
|
|
115
|
+
readOnly: boolean | undefined,
|
|
116
|
+
isError: boolean | undefined,
|
|
117
|
+
cannotChange: boolean,
|
|
118
|
+
): boolean {
|
|
119
|
+
if (cannotChange && isSetAsideTool(toolName)) return false
|
|
120
|
+
if (callChangedState(toolName, readOnly, isError)) return true
|
|
121
|
+
if (!cannotChange || isError) return false
|
|
122
|
+
return readOnly === true
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Tools that neither look nor change the work, so they are set aside when
|
|
127
|
+
* deciding whether an agent can change anything: the task list, and the
|
|
128
|
+
* message a sub-agent sends to the conversation that launched it.
|
|
129
|
+
*/
|
|
130
|
+
export function isSetAsideTool(toolName: string): boolean {
|
|
131
|
+
return TASK_LIST_TOOLS.has(toolName) || toolName === 'send_message'
|
|
132
|
+
}
|
|
133
|
+
|
|
92
134
|
/** When the monitor speaks. All counts are of consecutive steps that changed nothing. */
|
|
93
135
|
export interface StallConfig {
|
|
94
136
|
/** Steps without a change after which the model is nudged. Default 12. */
|
|
@@ -97,6 +139,14 @@ export interface StallConfig {
|
|
|
97
139
|
readonly nudgeAfterReasoningChars?: number
|
|
98
140
|
/** Further steps without a change after the nudge that make the next step an action step. Default 5. */
|
|
99
141
|
readonly forceAfterSteps?: number
|
|
142
|
+
/**
|
|
143
|
+
* Steps that only looked, in a turn the person opened with a question,
|
|
144
|
+
* after which the model is told to answer. Default 6: half of the general
|
|
145
|
+
* threshold, because a question is usually settled by two or three looks,
|
|
146
|
+
* and six looks that settled nothing are a model circling rather than
|
|
147
|
+
* gathering. It is a nudge only; a question never forces a tool call.
|
|
148
|
+
*/
|
|
149
|
+
readonly answerAfterSteps?: number
|
|
100
150
|
}
|
|
101
151
|
|
|
102
152
|
/** What the monitor wants done after a step. */
|
|
@@ -109,12 +159,34 @@ export type StallDirective =
|
|
|
109
159
|
export interface StallObservation {
|
|
110
160
|
readonly reasoningChars: number
|
|
111
161
|
readonly changedState: boolean
|
|
162
|
+
/** The person's latest message asked a question, so the way out of a stall is an answer. */
|
|
163
|
+
readonly question?: boolean
|
|
164
|
+
/** Every tool offered to the step only reads: the way out of a stall is a report, not an edit. */
|
|
165
|
+
readonly cannotChange?: boolean
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The longest message still read as a question; a longer one is a brief. */
|
|
169
|
+
const QUESTION_MAX_CHARS = 400
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Whether a person's message is mainly a question: short, and holding a
|
|
173
|
+
* question mark that ends a sentence. A mark inside a web address or a
|
|
174
|
+
* query string does not end one, and a long message is a task description
|
|
175
|
+
* that happens to ask something. A question without a mark is held to the
|
|
176
|
+
* general threshold.
|
|
177
|
+
*/
|
|
178
|
+
export function asksQuestion(text: string | undefined): boolean {
|
|
179
|
+
if (text === undefined) return false
|
|
180
|
+
const trimmed = text.trim()
|
|
181
|
+
if (trimmed.length === 0 || trimmed.length > QUESTION_MAX_CHARS) return false
|
|
182
|
+
return /[?\uFF1F\u061F](?=$|[\s"'\u201D\u2019)\]])/.test(trimmed)
|
|
112
183
|
}
|
|
113
184
|
|
|
114
185
|
export class StallMonitor {
|
|
115
186
|
private readonly nudgeAfterSteps: number
|
|
116
187
|
private readonly nudgeAfterChars: number
|
|
117
188
|
private readonly forceAfterSteps: number
|
|
189
|
+
private readonly answerAfterSteps: number
|
|
118
190
|
private idleSteps = 0
|
|
119
191
|
private idleChars = 0
|
|
120
192
|
private nudged = false
|
|
@@ -124,6 +196,7 @@ export class StallMonitor {
|
|
|
124
196
|
this.nudgeAfterSteps = config?.nudgeAfterSteps ?? 12
|
|
125
197
|
this.nudgeAfterChars = config?.nudgeAfterReasoningChars ?? 80_000
|
|
126
198
|
this.forceAfterSteps = config?.forceAfterSteps ?? 5
|
|
199
|
+
this.answerAfterSteps = config?.answerAfterSteps ?? 6
|
|
127
200
|
}
|
|
128
201
|
|
|
129
202
|
observe(step: StallObservation): StallDirective {
|
|
@@ -133,18 +206,33 @@ export class StallMonitor {
|
|
|
133
206
|
}
|
|
134
207
|
this.idleSteps += 1
|
|
135
208
|
this.idleChars += step.reasoningChars
|
|
209
|
+
const question = step.question === true
|
|
210
|
+
const cannotChange = step.cannotChange === true
|
|
211
|
+
const stallText = question
|
|
212
|
+
? ANSWER_NOW_MESSAGE
|
|
213
|
+
: cannotChange
|
|
214
|
+
? STALL_REPORT_MESSAGE
|
|
215
|
+
: STALL_NUDGE_MESSAGE
|
|
136
216
|
if (!this.nudged) {
|
|
217
|
+
if (question && this.idleSteps >= this.answerAfterSteps) {
|
|
218
|
+
this.nudged = true
|
|
219
|
+
this.stepsSinceNudge = 0
|
|
220
|
+
return { kind: 'nudge', text: ANSWER_NOW_MESSAGE }
|
|
221
|
+
}
|
|
137
222
|
if (this.idleSteps >= this.nudgeAfterSteps || this.idleChars >= this.nudgeAfterChars) {
|
|
138
223
|
this.nudged = true
|
|
139
224
|
this.stepsSinceNudge = 0
|
|
140
|
-
return { kind: 'nudge', text:
|
|
225
|
+
return { kind: 'nudge', text: stallText }
|
|
141
226
|
}
|
|
142
227
|
return { kind: 'none' }
|
|
143
228
|
}
|
|
144
229
|
this.stepsSinceNudge += 1
|
|
145
230
|
if (this.stepsSinceNudge >= this.forceAfterSteps) {
|
|
146
231
|
this.reset()
|
|
147
|
-
|
|
232
|
+
// A question is answered, and an agent that cannot change anything
|
|
233
|
+
// reports: say it again instead of forcing a tool call, which would
|
|
234
|
+
// only buy another look.
|
|
235
|
+
return question || cannotChange ? { kind: 'nudge', text: stallText } : { kind: 'force' }
|
|
148
236
|
}
|
|
149
237
|
return { kind: 'none' }
|
|
150
238
|
}
|
|
@@ -344,7 +344,14 @@ export function createEvidenceQueryResolver() {
|
|
|
344
344
|
maxTokens: 512,
|
|
345
345
|
signal: context.signal,
|
|
346
346
|
})
|
|
347
|
-
.then(({ text }) =>
|
|
347
|
+
.then(({ text, finishReason }) =>
|
|
348
|
+
// A planner that came back empty, or ran out of tokens before it
|
|
349
|
+
// finished, said nothing about the question. That is not a failed
|
|
350
|
+
// plan to report to the model: the lookup adds nothing this turn.
|
|
351
|
+
!text.trim() || finishReason === 'length'
|
|
352
|
+
? null
|
|
353
|
+
: validateEvidenceQueryResolution(text, current, history),
|
|
354
|
+
)
|
|
348
355
|
cached = { turnId: context.turnId, query, operator: identity, plan }
|
|
349
356
|
return plan
|
|
350
357
|
}
|
|
@@ -41,6 +41,21 @@ export interface TokenUsage {
|
|
|
41
41
|
*/
|
|
42
42
|
reasoningTokens?: number
|
|
43
43
|
|
|
44
|
+
/**
|
|
45
|
+
* What the provider says this call cost, in US dollars, when it says.
|
|
46
|
+
*
|
|
47
|
+
* A BILLED figure the vendor reported, as opposed to one the kernel worked
|
|
48
|
+
* out from a rate card: it already reflects the route that served the call,
|
|
49
|
+
* the cache discount and any tier. Where it is present the kernel records it
|
|
50
|
+
* as the call's cost and does not price the tokens again (see
|
|
51
|
+
* {@link accumulateReportedCost}); where it is absent the rate card is the
|
|
52
|
+
* fallback. Summed across calls like {@link TokenUsage.webSearchRequests},
|
|
53
|
+
* since it is money spent; a sum over calls that did not all report is a
|
|
54
|
+
* floor. Absent means the provider did not say, not that the call was free;
|
|
55
|
+
* a reported `0` is a real zero.
|
|
56
|
+
*/
|
|
57
|
+
reportedCostUsd?: number
|
|
58
|
+
|
|
44
59
|
/**
|
|
45
60
|
* How long the provider keeps the prompt cache this call used, in
|
|
46
61
|
* milliseconds, as the call itself reported or requested it.
|
|
@@ -126,6 +141,9 @@ export function accumulateTokenUsage(current: TokenUsage, addition: TokenUsage):
|
|
|
126
141
|
...(current.webSearchRequests !== undefined || addition.webSearchRequests !== undefined
|
|
127
142
|
? { webSearchRequests: (current.webSearchRequests ?? 0) + (addition.webSearchRequests ?? 0) }
|
|
128
143
|
: {}),
|
|
144
|
+
...(current.reportedCostUsd !== undefined || addition.reportedCostUsd !== undefined
|
|
145
|
+
? { reportedCostUsd: (current.reportedCostUsd ?? 0) + (addition.reportedCostUsd ?? 0) }
|
|
146
|
+
: {}),
|
|
129
147
|
// `fullPromptTokens`, `cacheTtlMs`, `cacheWriteTtlTokens`, `speed`, `serviceTier`,
|
|
130
148
|
// `inferenceGeo` and `cacheMiss` are per-call facts and are deliberately
|
|
131
149
|
// not carried into a sum.
|
|
@@ -179,6 +197,10 @@ export function mergeTokenUsage(current: TokenUsage, next: TokenUsage): TokenUsa
|
|
|
179
197
|
...(next.webSearchRequests !== undefined || current.webSearchRequests !== undefined
|
|
180
198
|
? { webSearchRequests: Math.max(current.webSearchRequests ?? 0, next.webSearchRequests ?? 0) }
|
|
181
199
|
: {}),
|
|
200
|
+
// Cumulative within one call, like the token counts.
|
|
201
|
+
...(next.reportedCostUsd !== undefined || current.reportedCostUsd !== undefined
|
|
202
|
+
? { reportedCostUsd: Math.max(current.reportedCostUsd ?? 0, next.reportedCostUsd ?? 0) }
|
|
203
|
+
: {}),
|
|
182
204
|
...(next.serviceTier !== undefined || current.serviceTier !== undefined
|
|
183
205
|
? { serviceTier: next.serviceTier ?? current.serviceTier }
|
|
184
206
|
: {}),
|
|
@@ -164,6 +164,12 @@ export interface ProviderCapabilities {
|
|
|
164
164
|
/** Whether the driver maps document blocks returned by tools onto its result wire. */
|
|
165
165
|
supportsToolResultDocuments?: boolean
|
|
166
166
|
maxOutputTokens?: number
|
|
167
|
+
/**
|
|
168
|
+
* Whether every call's usage carries the cost the provider billed
|
|
169
|
+
* (`TokenUsage.reportedCostUsd`). A cost limit is then measurable for a
|
|
170
|
+
* model no rate card names. Absent means the driver reports no cost.
|
|
171
|
+
*/
|
|
172
|
+
reportsRequestCost?: boolean
|
|
167
173
|
/**
|
|
168
174
|
* Prompt-cache lifetimes the driver can be asked for through
|
|
169
175
|
* `cacheControl.ttl`. Absent means the driver offers none (it has no cache,
|