@namzu/sdk 64.2.0 → 64.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/advisory/executor.d.ts +2 -1
  3. package/dist/advisory/executor.d.ts.map +1 -1
  4. package/dist/advisory/executor.js +8 -2
  5. package/dist/advisory/executor.js.map +1 -1
  6. package/dist/compaction/context-window.d.ts.map +1 -1
  7. package/dist/compaction/context-window.js +9 -2
  8. package/dist/compaction/context-window.js.map +1 -1
  9. package/dist/eval/judge.d.ts.map +1 -1
  10. package/dist/eval/judge.js +6 -2
  11. package/dist/eval/judge.js.map +1 -1
  12. package/dist/manager/agent/lifecycle.d.ts +1 -0
  13. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  14. package/dist/manager/agent/lifecycle.js +20 -6
  15. package/dist/manager/agent/lifecycle.js.map +1 -1
  16. package/dist/manager/session/turn-recorder.d.ts.map +1 -1
  17. package/dist/manager/session/turn-recorder.js +11 -2
  18. package/dist/manager/session/turn-recorder.js.map +1 -1
  19. package/dist/prompt/coding-agent-doctrine.d.ts +1 -1
  20. package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
  21. package/dist/prompt/coding-agent-doctrine.js +7 -1
  22. package/dist/prompt/coding-agent-doctrine.js.map +1 -1
  23. package/dist/provider/fallback.d.ts.map +1 -1
  24. package/dist/provider/fallback.js +2 -1
  25. package/dist/provider/fallback.js.map +1 -1
  26. package/dist/provider/idle-timeout.d.ts.map +1 -1
  27. package/dist/provider/idle-timeout.js +1 -1
  28. package/dist/provider/idle-timeout.js.map +1 -1
  29. package/dist/provider/instrumentation.js +1 -1
  30. package/dist/provider/instrumentation.js.map +1 -1
  31. package/dist/provider/retry.d.ts.map +1 -1
  32. package/dist/provider/retry.js +1 -1
  33. package/dist/provider/retry.js.map +1 -1
  34. package/dist/provider/side-request-reasoning.d.ts +32 -0
  35. package/dist/provider/side-request-reasoning.d.ts.map +1 -0
  36. package/dist/provider/side-request-reasoning.js +97 -0
  37. package/dist/provider/side-request-reasoning.js.map +1 -0
  38. package/dist/public-runtime.d.ts +3 -1
  39. package/dist/public-runtime.d.ts.map +1 -1
  40. package/dist/public-runtime.js +2 -1
  41. package/dist/public-runtime.js.map +1 -1
  42. package/dist/runtime/query/auto-review/classifier.d.ts.map +1 -1
  43. package/dist/runtime/query/auto-review/classifier.js +8 -2
  44. package/dist/runtime/query/auto-review/classifier.js.map +1 -1
  45. package/dist/runtime/query/callback-inference.d.ts.map +1 -1
  46. package/dist/runtime/query/callback-inference.js +14 -3
  47. package/dist/runtime/query/callback-inference.js.map +1 -1
  48. package/dist/runtime/query/iteration/index.d.ts +8 -0
  49. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  50. package/dist/runtime/query/iteration/index.js +36 -5
  51. package/dist/runtime/query/iteration/index.js.map +1 -1
  52. package/dist/runtime/query/prepare-turn.d.ts.map +1 -1
  53. package/dist/runtime/query/prepare-turn.js +3 -0
  54. package/dist/runtime/query/prepare-turn.js.map +1 -1
  55. package/dist/runtime/query/repeat-call.js +2 -2
  56. package/dist/runtime/query/repeat-call.js.map +1 -1
  57. package/dist/runtime/query/turn/stall-monitor.d.ts +26 -2
  58. package/dist/runtime/query/turn/stall-monitor.d.ts.map +1 -1
  59. package/dist/runtime/query/turn/stall-monitor.js +36 -4
  60. package/dist/runtime/query/turn/stall-monitor.js.map +1 -1
  61. package/dist/turn/evidence-query.d.ts.map +1 -1
  62. package/dist/turn/evidence-query.js +7 -1
  63. package/dist/turn/evidence-query.js.map +1 -1
  64. package/dist/types/common/index.d.ts +14 -0
  65. package/dist/types/common/index.d.ts.map +1 -1
  66. package/dist/types/common/index.js +7 -0
  67. package/dist/types/common/index.js.map +1 -1
  68. package/dist/types/provider/config.d.ts +6 -0
  69. package/dist/types/provider/config.d.ts.map +1 -1
  70. package/dist/types/provider/interface.d.ts +5 -2
  71. package/dist/types/provider/interface.d.ts.map +1 -1
  72. package/dist/types/session/prepare-step.d.ts +7 -0
  73. package/dist/types/session/prepare-step.d.ts.map +1 -1
  74. package/dist/utils/cost.d.ts +14 -0
  75. package/dist/utils/cost.d.ts.map +1 -1
  76. package/dist/utils/cost.js +20 -0
  77. package/dist/utils/cost.js.map +1 -1
  78. package/package.json +1 -1
  79. package/src/advisory/executor.ts +13 -2
  80. package/src/compaction/context-window.ts +9 -2
  81. package/src/eval/judge.ts +16 -9
  82. package/src/manager/agent/lifecycle.ts +19 -6
  83. package/src/manager/session/turn-recorder.ts +12 -1
  84. package/src/prompt/coding-agent-doctrine.ts +7 -1
  85. package/src/provider/fallback.ts +7 -2
  86. package/src/provider/idle-timeout.ts +2 -1
  87. package/src/provider/instrumentation.ts +1 -1
  88. package/src/provider/retry.ts +2 -1
  89. package/src/provider/side-request-reasoning.ts +121 -0
  90. package/src/public-runtime.ts +7 -0
  91. package/src/runtime/query/auto-review/classifier.ts +17 -9
  92. package/src/runtime/query/callback-inference.ts +13 -3
  93. package/src/runtime/query/iteration/index.ts +43 -3
  94. package/src/runtime/query/prepare-turn.ts +2 -0
  95. package/src/runtime/query/repeat-call.ts +2 -2
  96. package/src/runtime/query/turn/stall-monitor.ts +48 -4
  97. package/src/turn/evidence-query.ts +8 -1
  98. package/src/types/common/index.ts +22 -0
  99. package/src/types/provider/config.ts +6 -0
  100. package/src/types/provider/interface.ts +9 -2
  101. package/src/types/session/prepare-step.ts +7 -0
  102. package/src/utils/cost.ts +24 -0
@@ -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,6 +93,7 @@ import {
91
93
  REASONING_CAPPED_MESSAGE,
92
94
  REASONING_ONLY_MESSAGE,
93
95
  StallMonitor,
96
+ asksQuestion,
94
97
  callChangedState,
95
98
  reasoningCapChars,
96
99
  } from '../turn/stall-monitor.js'
@@ -1234,7 +1237,11 @@ export class IterationOrchestrator {
1234
1237
  // its low effort and asks in words, on this request only.
1235
1238
  const forcedChoiceRefused =
1236
1239
  forcedAction &&
1237
- this.ctx.provider.acceptsForcedToolChoiceFor?.(stepModel, turnConfig.thinking) === false
1240
+ this.ctx.provider.acceptsForcedToolChoiceFor?.(
1241
+ stepModel,
1242
+ turnConfig.thinking,
1243
+ stepEffort,
1244
+ ) === false
1238
1245
  const operatorInputAtDispatch = this.latestUserMessage
1239
1246
  const latestReviewUserMessage =
1240
1247
  (this.ctx.reviewAnswer || this.ctx.structuredOutput?.review) && operatorInputAtDispatch
@@ -3608,6 +3615,7 @@ export class IterationOrchestrator {
3608
3615
  if (!monitor) return
3609
3616
  const calls = new Map((response.message.toolCalls ?? []).map((c) => [c.id, c]))
3610
3617
  let changedState = false
3618
+ const question = asksQuestion(this.latestUserMessage?.content)
3611
3619
  for (const result of results) {
3612
3620
  const call = calls.get(result.toolCallId)
3613
3621
  let readOnly: boolean | undefined
@@ -3617,13 +3625,28 @@ export class IterationOrchestrator {
3617
3625
  } catch {
3618
3626
  readOnly = undefined
3619
3627
  }
3620
- if (callChangedState(result.toolName, readOnly, result.isError)) changedState = true
3628
+ if (callChangedState(result.toolName, readOnly, result.isError)) {
3629
+ // The same tool with the same input and the same result as an
3630
+ // earlier call this turn changed nothing, whatever the tool is,
3631
+ // except a file edit: applying, reverting and applying again is
3632
+ // deliberate work whose reply is the same each time.
3633
+ if (
3634
+ EDIT_TOOLS.has(result.toolName) ||
3635
+ !this.seenAgain(result.toolName, call, result.output)
3636
+ ) {
3637
+ changedState = true
3638
+ }
3639
+ }
3621
3640
  }
3622
3641
  const reasoningChars = (response.message.reasoning ?? []).reduce(
3623
3642
  (n, block) => n + (block.text?.length ?? 0),
3624
3643
  0,
3625
3644
  )
3626
- const directive = monitor.observe({ reasoningChars, changedState })
3645
+ const directive = monitor.observe({
3646
+ reasoningChars,
3647
+ changedState,
3648
+ question,
3649
+ })
3627
3650
  if (directive.kind === 'nudge') {
3628
3651
  this.ctx.log.info('Many steps without a change — nudging the model to act', {
3629
3652
  [NAMZU.TURN_ID]: this.ctx.recorder.turnId,
@@ -3637,6 +3660,23 @@ export class IterationOrchestrator {
3637
3660
  }
3638
3661
  }
3639
3662
 
3663
+ /** Fingerprints of the calls this turn has finished, for {@link seenAgain}. */
3664
+ private readonly finishedCalls = new Set<string>()
3665
+
3666
+ /**
3667
+ * Whether this call, with this input and this output, was already finished
3668
+ * earlier in the turn; records it either way. A call that gave the same
3669
+ * answer twice did not move anything the second time.
3670
+ */
3671
+ private seenAgain(toolName: string, call: ToolCall | undefined, output: string): boolean {
3672
+ const key = createHash('sha256')
3673
+ .update(`${toolName}\0${call?.function.arguments ?? ''}\0${output}`)
3674
+ .digest('hex')
3675
+ if (this.finishedCalls.has(key)) return true
3676
+ this.finishedCalls.add(key)
3677
+ return false
3678
+ }
3679
+
3640
3680
  private async requestFinalResponse(
3641
3681
  model: string,
3642
3682
  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 blocking you.`,
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, changing the arguments is more likely to help than repeating them.`,
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 run the one command that tells you what you still need. Refine as you go; do not plan the whole task again.'
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,14 @@ 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, or run the one check that settles what you are unsure of. Reading more or planning again will not move the task.'
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 the model is told when it was asked a question and several steps have
27
+ * only looked. It names the way out as the answer, never as another command.
28
+ */
29
+ export const ANSWER_NOW_MESSAGE =
30
+ '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
31
 
25
32
  /**
26
33
  * Said again, on one request only, when a step must act but the provider
@@ -97,6 +104,14 @@ export interface StallConfig {
97
104
  readonly nudgeAfterReasoningChars?: number
98
105
  /** Further steps without a change after the nudge that make the next step an action step. Default 5. */
99
106
  readonly forceAfterSteps?: number
107
+ /**
108
+ * Steps that only looked, in a turn the person opened with a question,
109
+ * after which the model is told to answer. Default 6: half of the general
110
+ * threshold, because a question is usually settled by two or three looks,
111
+ * and six looks that settled nothing are a model circling rather than
112
+ * gathering. It is a nudge only; a question never forces a tool call.
113
+ */
114
+ readonly answerAfterSteps?: number
100
115
  }
101
116
 
102
117
  /** What the monitor wants done after a step. */
@@ -109,12 +124,32 @@ export type StallDirective =
109
124
  export interface StallObservation {
110
125
  readonly reasoningChars: number
111
126
  readonly changedState: boolean
127
+ /** The person's latest message asked a question, so the way out of a stall is an answer. */
128
+ readonly question?: boolean
129
+ }
130
+
131
+ /** The longest message still read as a question; a longer one is a brief. */
132
+ const QUESTION_MAX_CHARS = 400
133
+
134
+ /**
135
+ * Whether a person's message is mainly a question: short, and holding a
136
+ * question mark that ends a sentence. A mark inside a web address or a
137
+ * query string does not end one, and a long message is a task description
138
+ * that happens to ask something. A question without a mark is held to the
139
+ * general threshold.
140
+ */
141
+ export function asksQuestion(text: string | undefined): boolean {
142
+ if (text === undefined) return false
143
+ const trimmed = text.trim()
144
+ if (trimmed.length === 0 || trimmed.length > QUESTION_MAX_CHARS) return false
145
+ return /[?\uFF1F\u061F](?=$|[\s"'\u201D\u2019)\]])/.test(trimmed)
112
146
  }
113
147
 
114
148
  export class StallMonitor {
115
149
  private readonly nudgeAfterSteps: number
116
150
  private readonly nudgeAfterChars: number
117
151
  private readonly forceAfterSteps: number
152
+ private readonly answerAfterSteps: number
118
153
  private idleSteps = 0
119
154
  private idleChars = 0
120
155
  private nudged = false
@@ -124,6 +159,7 @@ export class StallMonitor {
124
159
  this.nudgeAfterSteps = config?.nudgeAfterSteps ?? 12
125
160
  this.nudgeAfterChars = config?.nudgeAfterReasoningChars ?? 80_000
126
161
  this.forceAfterSteps = config?.forceAfterSteps ?? 5
162
+ this.answerAfterSteps = config?.answerAfterSteps ?? 6
127
163
  }
128
164
 
129
165
  observe(step: StallObservation): StallDirective {
@@ -133,18 +169,26 @@ export class StallMonitor {
133
169
  }
134
170
  this.idleSteps += 1
135
171
  this.idleChars += step.reasoningChars
172
+ const question = step.question === true
136
173
  if (!this.nudged) {
174
+ if (question && this.idleSteps >= this.answerAfterSteps) {
175
+ this.nudged = true
176
+ this.stepsSinceNudge = 0
177
+ return { kind: 'nudge', text: ANSWER_NOW_MESSAGE }
178
+ }
137
179
  if (this.idleSteps >= this.nudgeAfterSteps || this.idleChars >= this.nudgeAfterChars) {
138
180
  this.nudged = true
139
181
  this.stepsSinceNudge = 0
140
- return { kind: 'nudge', text: STALL_NUDGE_MESSAGE }
182
+ return { kind: 'nudge', text: question ? ANSWER_NOW_MESSAGE : STALL_NUDGE_MESSAGE }
141
183
  }
142
184
  return { kind: 'none' }
143
185
  }
144
186
  this.stepsSinceNudge += 1
145
187
  if (this.stepsSinceNudge >= this.forceAfterSteps) {
146
188
  this.reset()
147
- return { kind: 'force' }
189
+ // A question is answered, not acted on: say it again instead of
190
+ // forcing a tool call, which would only buy another command.
191
+ return question ? { kind: 'nudge', text: ANSWER_NOW_MESSAGE } : { kind: 'force' }
148
192
  }
149
193
  return { kind: 'none' }
150
194
  }
@@ -344,7 +344,14 @@ export function createEvidenceQueryResolver() {
344
344
  maxTokens: 512,
345
345
  signal: context.signal,
346
346
  })
347
- .then(({ text }) => validateEvidenceQueryResolution(text, current, history))
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,
@@ -185,12 +185,19 @@ export interface LLMProvider {
185
185
  *
186
186
  * The kernel asks before it requires a tool call on a step it wants to act,
187
187
  * and when the answer is `false` it keeps the step at low effort and asks the
188
- * model in words instead of sending a choice the driver would refuse. Optional:
188
+ * model in words instead of sending a choice the driver would refuse. `effort`
189
+ * is the level the request will carry, for a driver where the level also
190
+ * decides whether thinking is on (a provider that does not need it ignores
191
+ * it). Optional:
189
192
  * a provider that does not declare it is treated as taking the choice, so
190
193
  * every existing driver behaves as before. A wrapper that rebuilds a provider
191
194
  * forwards it.
192
195
  */
193
- acceptsForcedToolChoiceFor?(model: string, thinking?: import('./chat.js').ThinkingConfig): boolean
196
+ acceptsForcedToolChoiceFor?(
197
+ model: string,
198
+ thinking?: import('./chat.js').ThinkingConfig,
199
+ effort?: import('./chat.js').ReasoningEffort,
200
+ ): boolean
194
201
 
195
202
  /**
196
203
  * The effort a model uses when a request omits an explicit level.
@@ -33,6 +33,13 @@ export interface PreparationTextResult {
33
33
  readonly text: string
34
34
  readonly usage: TokenUsage
35
35
  readonly servedBy: StepProvenance
36
+ /**
37
+ * Why the provider stopped. `'length'` means the answer allowance ran out,
38
+ * which on a reasoning model can leave `text` empty or cut off mid-way; a
39
+ * caller that needs complete text treats it as no answer. Absent when the
40
+ * provider reported none.
41
+ */
42
+ readonly finishReason?: 'stop' | 'tool_calls' | 'length' | 'content_filter'
36
43
  }
37
44
 
38
45
  /**
package/src/utils/cost.ts CHANGED
@@ -241,6 +241,30 @@ export function accumulateUnpricedCost(current: CostInfo, additionalUsage: Token
241
241
  }
242
242
  }
243
243
 
244
+ /**
245
+ * Record a call whose cost the provider reported.
246
+ *
247
+ * The vendor's figure is what the account was charged, so it wins over a rate
248
+ * card: a card is an estimate of one model at one list price, while the report
249
+ * already includes the route that served the call, the cache discount and any
250
+ * tier. The rate fields go, as for unpriced tokens: no single card describes
251
+ * a total that holds a reported figure.
252
+ */
253
+ export function accumulateReportedCost(current: CostInfo, reportedCostUsd: number): CostInfo {
254
+ return {
255
+ totalCost: current.totalCost + reportedCostUsd,
256
+ cacheDiscount: current.cacheDiscount,
257
+ unpricedTokens: current.unpricedTokens,
258
+ }
259
+ }
260
+
261
+ /** Whether a usage frame carries a usable vendor-reported cost. */
262
+ export function hasReportedCost(
263
+ usage: TokenUsage,
264
+ ): usage is TokenUsage & { reportedCostUsd: number } {
265
+ return Number.isFinite(usage.reportedCostUsd) && (usage.reportedCostUsd as number) >= 0
266
+ }
267
+
244
268
  export function formatCost(usd: number): string {
245
269
  if (usd === 0) return '$0.00'
246
270
  if (usd < 0.01) return `$${usd.toFixed(4)}`