@namzu/sdk 67.0.0 → 68.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/pricing/catalogue.generated.d.ts.map +1 -1
  3. package/dist/pricing/catalogue.generated.js +6 -0
  4. package/dist/pricing/catalogue.generated.js.map +1 -1
  5. package/dist/provider/fallback.d.ts.map +1 -1
  6. package/dist/provider/fallback.js +12 -0
  7. package/dist/provider/fallback.js.map +1 -1
  8. package/dist/provider/idle-timeout.d.ts.map +1 -1
  9. package/dist/provider/idle-timeout.js +5 -0
  10. package/dist/provider/idle-timeout.js.map +1 -1
  11. package/dist/provider/model-window-suffix.d.ts.map +1 -1
  12. package/dist/provider/model-window-suffix.js +1 -0
  13. package/dist/provider/model-window-suffix.js.map +1 -1
  14. package/dist/provider/retry.d.ts.map +1 -1
  15. package/dist/provider/retry.js +5 -0
  16. package/dist/provider/retry.js.map +1 -1
  17. package/dist/public-runtime.d.ts +2 -2
  18. package/dist/public-runtime.d.ts.map +1 -1
  19. package/dist/public-runtime.js +2 -2
  20. package/dist/public-runtime.js.map +1 -1
  21. package/dist/public-types.d.ts +3 -3
  22. package/dist/public-types.d.ts.map +1 -1
  23. package/dist/registry/command/kernel-commands.d.ts +11 -1
  24. package/dist/registry/command/kernel-commands.d.ts.map +1 -1
  25. package/dist/registry/command/kernel-commands.js +114 -46
  26. package/dist/registry/command/kernel-commands.js.map +1 -1
  27. package/dist/runtime/query/iteration/index.d.ts +1 -1
  28. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  29. package/dist/runtime/query/iteration/index.js +3 -3
  30. package/dist/runtime/query/iteration/index.js.map +1 -1
  31. package/dist/store/goal/index.d.ts +53 -3
  32. package/dist/store/goal/index.d.ts.map +1 -1
  33. package/dist/store/goal/index.js +245 -9
  34. package/dist/store/goal/index.js.map +1 -1
  35. package/dist/tools/goal/confirmation.d.ts +82 -1
  36. package/dist/tools/goal/confirmation.d.ts.map +1 -1
  37. package/dist/tools/goal/confirmation.js +153 -3
  38. package/dist/tools/goal/confirmation.js.map +1 -1
  39. package/dist/tools/goal/index.d.ts.map +1 -1
  40. package/dist/tools/goal/index.js +34 -3
  41. package/dist/tools/goal/index.js.map +1 -1
  42. package/dist/types/command/index.d.ts +26 -2
  43. package/dist/types/command/index.d.ts.map +1 -1
  44. package/dist/types/command/index.js +5 -2
  45. package/dist/types/command/index.js.map +1 -1
  46. package/dist/types/common/index.d.ts +4 -2
  47. package/dist/types/common/index.d.ts.map +1 -1
  48. package/dist/types/common/index.js.map +1 -1
  49. package/dist/types/goal/index.d.ts +59 -0
  50. package/dist/types/goal/index.d.ts.map +1 -1
  51. package/dist/types/provider/chat.d.ts +10 -5
  52. package/dist/types/provider/chat.d.ts.map +1 -1
  53. package/dist/types/provider/interface.d.ts +7 -0
  54. package/dist/types/provider/interface.d.ts.map +1 -1
  55. package/dist/types/provider/model.d.ts +5 -0
  56. package/dist/types/provider/model.d.ts.map +1 -1
  57. package/dist/types/session/config.d.ts +2 -2
  58. package/dist/types/session/outcome.d.ts +5 -2
  59. package/dist/types/session/outcome.d.ts.map +1 -1
  60. package/dist/types/session/outcome.js.map +1 -1
  61. package/dist/utils/cost.d.ts +1 -1
  62. package/dist/utils/cost.d.ts.map +1 -1
  63. package/dist/utils/cost.js +14 -5
  64. package/dist/utils/cost.js.map +1 -1
  65. package/package.json +1 -1
  66. package/src/pricing/catalogue.generated.ts +6 -0
  67. package/src/pricing/rates.source.json +13 -7
  68. package/src/provider/fallback.ts +11 -0
  69. package/src/provider/idle-timeout.ts +5 -0
  70. package/src/provider/model-window-suffix.ts +1 -0
  71. package/src/provider/retry.ts +5 -0
  72. package/src/public-runtime.ts +9 -0
  73. package/src/public-types.ts +7 -0
  74. package/src/registry/command/kernel-commands.ts +136 -49
  75. package/src/runtime/query/iteration/index.ts +9 -6
  76. package/src/store/goal/index.ts +320 -21
  77. package/src/tools/goal/confirmation.ts +227 -3
  78. package/src/tools/goal/index.ts +40 -4
  79. package/src/types/command/index.ts +27 -2
  80. package/src/types/common/index.ts +4 -2
  81. package/src/types/goal/index.ts +61 -0
  82. package/src/types/provider/chat.ts +10 -5
  83. package/src/types/provider/interface.ts +8 -0
  84. package/src/types/provider/model.ts +5 -0
  85. package/src/types/session/config.ts +2 -2
  86. package/src/types/session/outcome.ts +3 -1
  87. package/src/utils/cost.ts +15 -6
@@ -209,6 +209,83 @@ export function describeGoalEnding(
209
209
  }
210
210
  }
211
211
 
212
+ /** One requirement of a goal and what was done to check it. */
213
+ export interface GoalEvidence {
214
+ readonly requirement: string
215
+ readonly checked: string
216
+ readonly result: string
217
+ }
218
+
219
+ /** What a judge is shown when the model says a goal is complete. */
220
+ export interface GoalJudgeInput {
221
+ /** The conversation and turn the report was made in, for a host that counts the judge's spend there. */
222
+ readonly sessionId: string
223
+ readonly turnId: string
224
+ readonly objective: string
225
+ readonly evidence: readonly GoalEvidence[]
226
+ /** The turn's record in plain words, as {@link recordSentence} writes it. */
227
+ readonly outcome: string
228
+ /** The model's last message of the turn. */
229
+ readonly finalMessage: string
230
+ }
231
+
232
+ /** What a judge found: whether the goal is met and, when it is not, what is missing. */
233
+ export interface GoalJudgement {
234
+ readonly met: boolean
235
+ readonly missing: readonly string[]
236
+ }
237
+
238
+ /**
239
+ * Judges one completion report. Resolves `undefined` when it could not judge
240
+ * (no model, an error, a timeout, a reply that was not an answer); the goal
241
+ * then takes the path it takes without a judge, and is never blocked by it.
242
+ */
243
+ export type GoalJudge = (input: GoalJudgeInput) => Promise<GoalJudgement | undefined>
244
+
245
+ /** Every field a completion report's evidence entries must carry, in the words the model reads. */
246
+ export const GOAL_AUDIT_RUBRIC = [
247
+ 'Before reporting a goal complete: restate each requirement in the objective, check each one against the current state (open the file, run the check, read the output), and list them as evidence with what you checked and what you saw.',
248
+ 'Intent, earlier work or a plausible-looking answer is not proof. If any evidence is weak or missing, keep working instead of reporting.',
249
+ ].join(' ')
250
+
251
+ /** Turns the model's `evidence` input into entries, or says what is wrong with it. */
252
+ export function parseGoalEvidence(
253
+ value: unknown,
254
+ ):
255
+ | { readonly ok: true; readonly evidence: readonly GoalEvidence[] }
256
+ | { readonly ok: false; readonly problem: string } {
257
+ if (!Array.isArray(value) || value.length === 0) {
258
+ return {
259
+ ok: false,
260
+ problem: 'Reporting a goal complete needs evidence: a list with one entry per requirement.',
261
+ }
262
+ }
263
+ const evidence: GoalEvidence[] = []
264
+ for (const entry of value) {
265
+ const item = entry as Partial<Record<keyof GoalEvidence, unknown>> | null
266
+ const text = (field: keyof GoalEvidence): string =>
267
+ typeof item?.[field] === 'string' ? (item[field] as string).trim() : ''
268
+ const requirement = text('requirement')
269
+ const checked = text('checked')
270
+ const result = text('result')
271
+ if (requirement === '' || checked === '' || result === '') {
272
+ return {
273
+ ok: false,
274
+ problem: 'Every evidence entry needs a requirement, what was checked, and the result.',
275
+ }
276
+ }
277
+ evidence.push({ requirement, checked, result })
278
+ }
279
+ return { ok: true, evidence }
280
+ }
281
+
282
+ function sameRequirement(a: string, b: string): boolean {
283
+ const fold = (text: string): string => text.toLowerCase().replace(/\s+/gu, ' ').trim()
284
+ const x = fold(a)
285
+ const y = fold(b)
286
+ return x === y || x.includes(y) || y.includes(x)
287
+ }
288
+
212
289
  export interface GoalConfirmationOptions {
213
290
  readonly store: SessionGoalStore
214
291
  /** The same resolver the goal tools use: the authority of the turn, or none. */
@@ -217,13 +294,30 @@ export interface GoalConfirmationOptions {
217
294
  readonly defaultConfirmedBy?: GoalConfirmedBy
218
295
  /** Refusals a goal may be given. Default {@link DEFAULT_GOAL_REFUSALS}. */
219
296
  readonly maxRefusals?: number
297
+ /**
298
+ * Make `update_goal` with `complete` need evidence, and hold the first such
299
+ * report of a goal once so the model audits itself. Default off: the report
300
+ * ends the goal, as it always has.
301
+ */
302
+ readonly requireEvidence?: boolean
303
+ /** Checks a completion report when {@link judgeActive} says so. */
304
+ readonly judge?: GoalJudge
305
+ /** Whether a judge is in use for the goal now. Default: a judge was given. */
306
+ readonly judgeActive?: () => boolean
220
307
  }
221
308
 
222
309
  interface Claim {
223
310
  readonly statement: GoalStatement
224
311
  readonly reason?: string
312
+ /** Present on a report of a goal the model confirms, with its evidence. */
313
+ readonly evidence?: readonly GoalEvidence[]
225
314
  }
226
315
 
316
+ /** What to do with a completion report when no judge decides it. */
317
+ export type SelfAuditDecision =
318
+ | { readonly kind: 'accept' }
319
+ | { readonly kind: 'hold'; readonly note: string }
320
+
227
321
  /**
228
322
  * Holds, for one session, what the model reported this turn, how many times a
229
323
  * goal was sent back, and whether an earlier round of it changed files. All of
@@ -235,9 +329,64 @@ export class GoalConfirmation {
235
329
  private readonly refusals = new Map<string, number>()
236
330
  private readonly changed = new Set<string>()
237
331
  private readonly endings = new Map<string, GoalEndingReport>()
332
+ /** Requirements listed in the first completion report of a goal, which held it once. */
333
+ private readonly audited = new Map<string, readonly string[]>()
334
+ private readonly judged = new Map<string, number>()
238
335
 
239
336
  constructor(private readonly options: GoalConfirmationOptions) {}
240
337
 
338
+ /** Whether `update_goal` with `complete` needs evidence. */
339
+ get requiresEvidence(): boolean {
340
+ return this.options.requireEvidence === true
341
+ }
342
+
343
+ /** Whether a judge checks the completion reports of a goal the model confirms. */
344
+ get judging(): boolean {
345
+ return (
346
+ this.options.judge !== undefined &&
347
+ (this.options.judgeActive === undefined || this.options.judgeActive())
348
+ )
349
+ }
350
+
351
+ /**
352
+ * A completion report made while no judge decides it. The first report of a
353
+ * goal is handed back once with the rubric; the next is accepted when its
354
+ * evidence covers each requirement the first one listed. No model is asked.
355
+ */
356
+ selfAudit(goalId: string, evidence: readonly GoalEvidence[]): SelfAuditDecision {
357
+ const listed = this.audited.get(goalId)
358
+ if (listed === undefined) {
359
+ this.audited.set(
360
+ goalId,
361
+ evidence.map((entry) => entry.requirement),
362
+ )
363
+ return {
364
+ kind: 'hold',
365
+ note: `Held once for an audit. ${GOAL_AUDIT_RUBRIC} Report complete again with the evidence once every requirement holds.`,
366
+ }
367
+ }
368
+ const uncovered = listed.filter(
369
+ (requirement) => !evidence.some((entry) => sameRequirement(entry.requirement, requirement)),
370
+ )
371
+ if (uncovered.length > 0) {
372
+ return {
373
+ kind: 'hold',
374
+ note: `The evidence does not cover: ${uncovered.join('; ')}. Report complete again with an entry for each requirement you listed before.`,
375
+ }
376
+ }
377
+ this.audited.delete(goalId)
378
+ return { kind: 'accept' }
379
+ }
380
+
381
+ /** Keeps a model-confirmed report until the model finishes its answer and a judge can read it. */
382
+ claimEvidence(goalId: string, evidence: readonly GoalEvidence[], reason?: string): void {
383
+ this.claims.set(goalId, {
384
+ statement: 'met',
385
+ evidence,
386
+ ...(reason !== undefined ? { reason } : {}),
387
+ })
388
+ }
389
+
241
390
  /** What decides this goal: its own choice, else the host's setting, else the model. */
242
391
  confirmedByFor(goal: Pick<SessionGoal, 'confirmedBy'>): GoalConfirmedBy {
243
392
  return goal.confirmedBy ?? this.options.defaultConfirmedBy ?? 'model'
@@ -299,9 +448,79 @@ export class GoalConfirmation {
299
448
  this.claims.delete(goal.id)
300
449
  this.refusals.delete(goal.id)
301
450
  this.changed.delete(goal.id)
451
+ this.audited.delete(goal.id)
452
+ this.judged.delete(goal.id)
302
453
  return report
303
454
  }
304
455
 
456
+ /**
457
+ * A report of a goal the model confirms, read when the model finishes its
458
+ * answer: the judge decides it. Met ends the goal. Not met keeps it active
459
+ * and sends the missing list back while refusals remain; past the bound the
460
+ * turn ends and the list leads the next round. A judge that cannot judge
461
+ * leaves the decision to the self-audit.
462
+ */
463
+ private async judgeClaim(
464
+ authority: GoalRoundAuthority,
465
+ goal: SessionGoal,
466
+ turnId: string,
467
+ read: () => Promise<TurnOutcome | undefined>,
468
+ finalMessage: string,
469
+ ): Promise<string | undefined> {
470
+ const claim = this.claims.get(goal.id)
471
+ this.claims.delete(goal.id)
472
+ if (!claim?.evidence) return undefined
473
+ const { store } = this.options
474
+ const ref = { id: authority.id, revision: authority.revision }
475
+ const evidence = claim.evidence
476
+ let judgement: GoalJudgement | undefined
477
+ if (this.options.judge !== undefined) {
478
+ try {
479
+ judgement = await this.options.judge({
480
+ sessionId: String(authority.sessionId),
481
+ turnId,
482
+ objective: goal.objective,
483
+ evidence,
484
+ outcome: recordSentence(await read()),
485
+ finalMessage,
486
+ })
487
+ } catch {
488
+ judgement = undefined
489
+ }
490
+ }
491
+ const accept = async (): Promise<undefined> => {
492
+ // What an earlier check found missing is moot once the goal is met.
493
+ if ((this.judged.get(goal.id) ?? 0) > 0) {
494
+ await store.recordRound?.(authority.sessionId, authority.tenantId, authority.id, {
495
+ progress: 'unknown',
496
+ missing: [],
497
+ })
498
+ }
499
+ try {
500
+ await store.completeGoal(authority.sessionId, authority.tenantId, ref)
501
+ } catch (error) {
502
+ if (!(error instanceof StaleGoalError)) throw error
503
+ }
504
+ this.judged.delete(goal.id)
505
+ return undefined
506
+ }
507
+ if (judgement === undefined) {
508
+ const decision = this.selfAudit(goal.id, evidence)
509
+ return decision.kind === 'accept' ? await accept() : decision.note
510
+ }
511
+ if (judgement.met) return await accept()
512
+ const missing = judgement.missing.map((line) => line.trim()).filter((line) => line !== '')
513
+ const asked = this.judged.get(goal.id) ?? 0
514
+ this.judged.set(goal.id, asked + 1)
515
+ const list = missing.length > 0 ? missing : ['the evidence does not show the goal is met']
516
+ await store.recordRound?.(authority.sessionId, authority.tenantId, authority.id, {
517
+ progress: 'unknown',
518
+ missing: list,
519
+ })
520
+ if (asked >= this.maxRefusals) return undefined
521
+ return `The check of your completion report found the goal is not met yet. Missing: ${list.join('; ')}. Keep working on these, then report complete again with updated evidence.`
522
+ }
523
+
305
524
  /** Drop a report that was never answered for, when its round ends without the turn finishing an answer. */
306
525
  forget(goalId: string): void {
307
526
  this.claims.delete(goalId)
@@ -314,13 +533,18 @@ export class GoalConfirmation {
314
533
  */
315
534
  beforeEnd(
316
535
  turnId: string,
317
- ): (read: () => Promise<TurnOutcome | undefined>) => Promise<string | undefined> {
318
- return async (read) => {
536
+ ): (
537
+ read: () => Promise<TurnOutcome | undefined>,
538
+ context?: { readonly finalMessage?: string },
539
+ ) => Promise<string | undefined> {
540
+ return async (read, context) => {
319
541
  const authority = this.options.resolveAuthority(turnId)
320
542
  if (!authority) return undefined
321
543
  const goal = await this.options.store.getGoal(authority.sessionId, authority.tenantId)
322
544
  if (!goal || goal.id !== authority.id || goal.phase !== 'active') return undefined
323
- if (this.confirmedByFor(goal) !== 'record') return undefined
545
+ if (this.confirmedByFor(goal) !== 'record') {
546
+ return await this.judgeClaim(authority, goal, turnId, read, context?.finalMessage ?? '')
547
+ }
324
548
 
325
549
  const record = await read()
326
550
  const claim = this.claims.get(goal.id)
@@ -5,7 +5,12 @@ import type { GoalRoundAuthority, SessionGoal } from '../../types/goal/index.js'
5
5
  import type { TurnId } from '../../types/ids/index.js'
6
6
  import type { ToolDefinition } from '../../types/tool/index.js'
7
7
  import { defineTool } from '../defineTool.js'
8
- import { type GoalConfirmation, NO_CHECK_REASON_CODE } from './confirmation.js'
8
+ import {
9
+ GOAL_AUDIT_RUBRIC,
10
+ type GoalConfirmation,
11
+ NO_CHECK_REASON_CODE,
12
+ parseGoalEvidence,
13
+ } from './confirmation.js'
9
14
 
10
15
  export const SESSION_GOAL_TOOL_NAMES = ['get_goal', 'update_goal'] as const
11
16
  export const MIN_GOAL_BLOCK_ROUND = 3
@@ -83,6 +88,12 @@ export function buildSessionGoalTools(
83
88
  round: authority.round,
84
89
  maxGoalRounds: goal.maxGoalRounds,
85
90
  roundsAdmitted: goal.roundsAdmitted,
91
+ tokensUsed: goal.tokensUsed ?? 0,
92
+ costUsd: goal.costUsd ?? 0,
93
+ ...(goal.guards?.tokenBudget !== undefined
94
+ ? { tokenBudget: goal.guards.tokenBudget }
95
+ : {}),
96
+ ...(authority.wrapUp ? { wrapUp: true } : {}),
86
97
  }),
87
98
  data: goal,
88
99
  }
@@ -91,8 +102,7 @@ export function buildSessionGoalTools(
91
102
 
92
103
  const updateGoal = defineTool({
93
104
  name: 'update_goal',
94
- description:
95
- 'Mark this admitted goal complete, or blocked after at least three admitted rounds. This does not end the turn; explain the final state to the operator afterward.',
105
+ description: `Mark this admitted goal complete, or blocked after at least three admitted rounds. Completion takes evidence: one entry per requirement of the objective, with what you checked and the result. ${GOAL_AUDIT_RUBRIC} This does not end the turn; explain the final state to the operator afterward.`,
96
106
  inputSchema: z.object({
97
107
  status: z.enum(['complete', 'blocked']),
98
108
  reasonCode: z
@@ -100,13 +110,23 @@ export function buildSessionGoalTools(
100
110
  .optional()
101
111
  .describe('Lower-kebab-case reason code; required when status is blocked.'),
102
112
  reason: z.string().optional().describe('Operator-readable reason; required when blocked.'),
113
+ evidence: z
114
+ .array(
115
+ z.object({
116
+ requirement: z.string().describe('One requirement of the objective, restated.'),
117
+ checked: z.string().describe('What you did to check it against the current state.'),
118
+ result: z.string().describe('What the check showed.'),
119
+ }),
120
+ )
121
+ .optional()
122
+ .describe('Required when status is complete: one entry per requirement.'),
103
123
  }),
104
124
  category: 'custom',
105
125
  permissions: [],
106
126
  readOnly: false,
107
127
  destructive: false,
108
128
  concurrencySafe: false,
109
- async execute({ status, reasonCode, reason }, context) {
129
+ async execute({ status, reasonCode, reason, evidence }, context) {
110
130
  const authority = authorityFor(resolveAuthority, context.turnId)
111
131
  const current = await currentGoal(store, authority)
112
132
  const ref = { id: authority.id, revision: authority.revision }
@@ -145,6 +165,22 @@ export function buildSessionGoalTools(
145
165
  }
146
166
  }
147
167
  if (status === 'complete') {
168
+ if (confirmation?.requiresEvidence) {
169
+ const parsed = parseGoalEvidence(evidence)
170
+ if (!parsed.ok) throw new TypeError(`${parsed.problem} ${GOAL_AUDIT_RUBRIC}`)
171
+ if (confirmation.judging) {
172
+ // A judge reads the report together with the final answer, so the
173
+ // report is held until the model has given it.
174
+ confirmation.claimEvidence(authority.id, parsed.evidence, reason)
175
+ return {
176
+ success: true,
177
+ output:
178
+ 'Completion reported. The evidence is checked when you finish your answer: give your final answer now, and if something is found missing you will be told what.',
179
+ }
180
+ }
181
+ const decision = confirmation.selfAudit(authority.id, parsed.evidence)
182
+ if (decision.kind === 'hold') throw new Error(decision.note)
183
+ }
148
184
  const goal = await store.completeGoal(authority.sessionId, authority.tenantId, ref)
149
185
  return { success: true, output: 'Goal marked complete.', data: goal }
150
186
  }
@@ -7,13 +7,28 @@
7
7
  * escaped: two non-TUI commands import that array from React-adjacent code
8
8
  * to build a name list, for facts the kernel owns.
9
9
  *
10
- * **Never model-visible.** No descriptor is handed to a provider, no
11
- * dispatch path reaches the LLM, and nothing here is a `ToolDefinition`.
10
+ * **Never model-visible by default.** No descriptor is handed to a provider,
11
+ * no dispatch path reaches the LLM, and nothing here is a `ToolDefinition`.
12
12
  * That separation is the whole point: a `/tasks` readout is a question the
13
13
  * operator asked, and turning it into a tool would let the model call it,
14
14
  * spend a turn on it, and put its output in the transcript as if the model
15
15
  * had discovered something.
16
+ *
17
+ * A host that lets the person ask for a command in plain words reads the
18
+ * `modelRun` declaration below. A command that says nothing is `never`.
19
+ */
20
+
21
+ /**
22
+ * Whether the model may run a command for the person, and on what terms.
23
+ *
24
+ * - `run`: read-only or cosmetic and reversible, no spend, no change of
25
+ * authority. The model runs it at once.
26
+ * - `confirm`: changes the conversation, files, a schedule, the model, the
27
+ * spend rate or stored data. The person approves each call first.
28
+ * - `never`: signs in, widens authority, edits global configuration, reaches
29
+ * other machines or ends the session. The model asks the person to type it.
16
30
  */
31
+ export type HostCommandModelRun = 'run' | 'confirm' | 'never'
17
32
 
18
33
  /**
19
34
  * What a command produces, structured rather than rendered.
@@ -61,6 +76,16 @@ export interface HostCommandDescriptor {
61
76
  readonly hint?: string
62
77
  /** JSON Schema for the arguments, when the command takes any. */
63
78
  readonly args?: Record<string, unknown>
79
+ /**
80
+ * What the model may do with this command. Absent reads as `never`, so a
81
+ * new command is never model-runnable by accident.
82
+ */
83
+ readonly modelRun?: HostCommandModelRun
84
+ /**
85
+ * First argument words whose form only reads, and so runs although
86
+ * `modelRun` is stricter. The empty string names the form with no arguments.
87
+ */
88
+ readonly modelRunReads?: readonly string[]
64
89
  handler(ctx: HostCommandContext): Promise<HostCommandOutcome> | HostCommandOutcome
65
90
  }
66
91
 
@@ -76,7 +76,8 @@ export interface TokenUsage {
76
76
 
77
77
  /**
78
78
  * The speed the provider says served this call, when it says. `'fast'` is a
79
- * premium-priced mode, so pricing reads it per call: a per-call fact like
79
+ * premium-priced mode and `'ultrafast'` a tier above it that has no
80
+ * published per-token price, so pricing reads it per call: a per-call fact like
80
81
  * {@link TokenUsage.cacheTtlMs}, never summed. Absent means standard or
81
82
  * unreported.
82
83
  */
@@ -92,7 +93,8 @@ export interface TokenUsage {
92
93
  /**
93
94
  * The service tier the provider says served this call (`standard`,
94
95
  * `priority`, `batch`). A per-call fact, never summed. Absent means
95
- * unreported.
96
+ * unreported. A driver that reports fast mode through {@link TokenUsage.speed}
97
+ * leaves `priority` out of here.
96
98
  */
97
99
  serviceTier?: string
98
100
 
@@ -48,10 +48,64 @@ export interface SessionGoal extends GoalRef {
48
48
  readonly confirmedBy?: GoalConfirmedBy
49
49
  /** Present exactly while {@link phase} is `blocked`. */
50
50
  readonly blockedReason?: GoalBlockReason
51
+ /** Present while {@link phase} is `paused` because the goal reached a check-in. */
52
+ readonly pauseReason?: GoalBlockReason
53
+ /**
54
+ * Stop rules chosen when the goal was created. Absent means the rule is not
55
+ * applied, which is how every goal created before they existed behaves.
56
+ */
57
+ readonly guards?: GoalGuards
58
+ /** Tokens spent by the goal's automatic turns so far. */
59
+ readonly tokensUsed?: number
60
+ /** What those turns cost, in USD, as far as it could be priced. */
61
+ readonly costUsd?: number
62
+ /** Automatic turns in a row that did nothing the record can show. */
63
+ readonly quietRounds?: number
64
+ /** Automatic turns in a row that ended on the same failure. */
65
+ readonly failureRounds?: number
66
+ /** The failure those turns ended on. */
67
+ readonly failureSignature?: string
68
+ /** What the most recent turn that did something did, in a few words. */
69
+ readonly lastAction?: string
70
+ /** The admitted round at which the last check-in pause was made. */
71
+ readonly checkedInAtRound?: number
72
+ /** The admitted round that was given as the last one because the token budget was reached. */
73
+ readonly wrapUpRound?: number
74
+ /** What a check of the completion report found missing; leads the next round. */
75
+ readonly missing?: readonly string[]
51
76
  readonly createdAt: number
52
77
  readonly updatedAt: number
53
78
  }
54
79
 
80
+ /**
81
+ * The rules that stop a goal that is not getting anywhere or has spent what it
82
+ * was allowed. Every field is optional and an absent one is not applied.
83
+ */
84
+ export interface GoalGuards {
85
+ /** Stop (block) after this many automatic turns in a row that changed nothing, or that ended on the same failure. */
86
+ readonly stallRounds?: number
87
+ /** Pause for a check-in after this many admitted rounds, and again after each further batch. `0` turns it off. */
88
+ readonly checkInEvery?: number
89
+ /** Tokens the goal's automatic turns may spend; one last round is given when it is reached. */
90
+ readonly tokenBudget?: number
91
+ }
92
+
93
+ /** What one finished automatic turn did, as the host read it from the turn's record. */
94
+ export interface GoalRoundOutcome {
95
+ /** Tokens the turn spent, when known. */
96
+ readonly tokens?: number
97
+ /** What the turn cost in USD, when it could be priced. */
98
+ readonly costUsd?: number
99
+ /** `empty`: nothing changed, no check ran, no completion was claimed. `unknown`: the record cannot tell. */
100
+ readonly progress: 'progress' | 'empty' | 'unknown'
101
+ /** The failure the turn ended on, as a stable short string; absent when it did not end on one. */
102
+ readonly failureSignature?: string
103
+ /** What the turn did, in a few words, for the line that says why a goal stopped. */
104
+ readonly action?: string
105
+ /** What a check of the completion report found missing. An empty list clears it. */
106
+ readonly missing?: readonly string[]
107
+ }
108
+
55
109
  /** Immutable authority carried by exactly one admitted automatic turn. */
56
110
  export interface GoalRoundAuthority extends GoalRef {
57
111
  readonly sessionId: SessionId
@@ -60,4 +114,11 @@ export interface GoalRoundAuthority extends GoalRef {
60
114
  /** One-based admitted round number. */
61
115
  readonly round: number
62
116
  readonly maxGoalRounds: number
117
+ /** Tokens and cost (USD) the goal's earlier automatic turns used, when any were recorded. */
118
+ readonly tokensUsed?: number
119
+ readonly costUsd?: number
120
+ /** This round is the last one: the token budget was reached and the model is to wrap up. */
121
+ readonly wrapUp?: boolean
122
+ /** What a check of an earlier completion report found missing; leads this round. */
123
+ readonly missing?: readonly string[]
63
124
  }
@@ -109,10 +109,11 @@ export interface ChatCompletionParams {
109
109
 
110
110
  /**
111
111
  * Inference speed. `'fast'` asks a provider for its premium low-latency
112
- * mode, billed at a multiple of the standard rate; absent and `'standard'`
112
+ * mode, billed at a multiple of the standard rate; `'ultrafast'` asks for
113
+ * a tier above it where a provider offers one. Absent and `'standard'`
113
114
  * are the same request. A driver with no such mode, or a model without it,
114
- * must refuse `'fast'` rather than serve it at standard speed and let the
115
- * caller believe it was honoured.
115
+ * must refuse `'fast'` and `'ultrafast'` rather than serve them at standard
116
+ * speed and let the caller believe they were honoured.
116
117
  */
117
118
  speed?: InferenceSpeed
118
119
  }
@@ -183,8 +184,12 @@ export interface ThinkingConfig {
183
184
  * transport or leave the vendor to refuse an unknown compatible-endpoint
184
185
  * extension explicitly.
185
186
  */
186
- /** `'fast'` is a premium low-latency mode; `'standard'` is the ordinary request. See {@link ChatCompletionParams.speed}. */
187
- export type InferenceSpeed = 'standard' | 'fast'
187
+ /**
188
+ * `'fast'` is a premium low-latency mode; `'ultrafast'` is a tier above it on
189
+ * providers that offer one; `'standard'` is the ordinary request. See
190
+ * {@link ChatCompletionParams.speed}.
191
+ */
192
+ export type InferenceSpeed = 'standard' | 'fast' | 'ultrafast'
188
193
 
189
194
  export type ReasoningEffort =
190
195
  | 'none'
@@ -187,6 +187,14 @@ export interface LLMProvider {
187
187
  * stale on the next model release and goes stale SILENTLY — surfacing as
188
188
  * a vendor rejection rather than a failing build.
189
189
  */
190
+ /**
191
+ * The speed tiers above standard that `model` offers on this route, when the
192
+ * driver learned them from the account's own model listing. `undefined`
193
+ * means unknown (the listing has not answered, or the model is not in it);
194
+ * `[]` means none. Same convention as {@link ModelInfo.speedTiers}.
195
+ */
196
+ speedTiersFor?(model: string): readonly ('fast' | 'ultrafast')[] | undefined
197
+
190
198
  reasoningEffortLevelsFor?(
191
199
  model: string,
192
200
  thinking?: import('./chat.js').ThinkingConfig,
@@ -18,6 +18,11 @@ export interface ModelInfo {
18
18
  reasoningEffortLevels?: readonly import('./chat.js').ReasoningEffort[]
19
19
  /** Published default, when established; must belong to reasoningEffortLevels when both are present. */
20
20
  reasoningEffortDefault?: import('./chat.js').ReasoningEffort
21
+ /**
22
+ * Speed tiers above standard that the listing established for this model
23
+ * and route. Absent means the listing did not say; `[]` means none.
24
+ */
25
+ speedTiers?: readonly ('fast' | 'ultrafast')[]
21
26
  /**
22
27
  * Tokens the model's context holds, when the driver knows.
23
28
  *
@@ -72,10 +72,10 @@ export interface TurnConfig {
72
72
  /**
73
73
  * Inference speed for every model call in the turn: `'fast'` asks for the
74
74
  * provider's premium low-latency mode (billed at a multiple of the standard
75
- * rate), absent and `'standard'` are the ordinary request. Turn-level for
75
+ * rate), `'ultrafast'` for a tier above it where one is offered, absent and `'standard'` are the ordinary request. Turn-level for
76
76
  * the same reason as {@link TurnConfig.effort}: speeds do not share a
77
77
  * prompt-cache prefix, so a value that moves between steps pays for a cache
78
- * miss each time. A driver or model without the mode REFUSES `'fast'`
78
+ * miss each time. A driver or model without the mode REFUSES the tier
79
79
  * rather than serving it slowly.
80
80
  */
81
81
  speed?: import('../provider/index.js').InferenceSpeed
@@ -124,11 +124,13 @@ export interface TurnOutcomeConfig {
124
124
  * sentence goes to the model as a runtime note and the turn goes on; nothing
125
125
  * returned lets the turn end. A turn that is being stopped by a limit, a
126
126
  * cancellation or a forced final answer is not asked, so a limit always wins
127
- * over this hook. At most 16 notes are honoured in one turn. A hook that
127
+ * over this hook. `context.finalMessage` is the answer the model just gave.
128
+ * At most 16 notes are honoured in one turn. A hook that
128
129
  * throws is read as nothing returned.
129
130
  */
130
131
  readonly beforeEnd?: (
131
132
  read: () => Promise<TurnOutcome | undefined>,
133
+ context?: { readonly finalMessage?: string },
132
134
  ) => string | undefined | Promise<string | undefined>
133
135
  }
134
136
 
package/src/utils/cost.ts CHANGED
@@ -43,7 +43,7 @@ export interface ModelPricing {
43
43
  cache?: CacheRates
44
44
  /**
45
45
  * The vendor's published multiple of every rate on this card for a request
46
- * served in fast mode (`TokenUsage.speed === 'fast'`). Absent means there is
46
+ * served in fast mode (`TokenUsage.speed === 'fast'`; it does not apply to `'ultrafast'`). Absent means there is
47
47
  * no published fast price: fast usage is then counted as unpriced, never
48
48
  * charged at the standard rate, which would under-report it.
49
49
  */
@@ -71,22 +71,31 @@ function priceUsage(usage: TokenUsage, pricing: ModelPricing): Priced {
71
71
  const searches = usage.webSearchRequests ?? 0
72
72
  if (searches === 0 || pricing.webSearchCostPer1000 === undefined) return tokens
73
73
  // Per request, so no speed or tier multiple applies to it.
74
- return { ...tokens, cost: tokens.cost + (searches / 1000) * pricing.webSearchCostPer1000 }
74
+ return {
75
+ ...tokens,
76
+ cost: tokens.cost + (searches / 1000) * pricing.webSearchCostPer1000,
77
+ }
75
78
  }
76
79
 
77
80
  /**
78
- * Tiers with a published per-token price (anything but `priority` and `batch`; a compatible endpoint may report `default` or `auto`). The vendor lists none for `priority`
79
- * (a capacity commitment) or `batch` (a different endpoint), so tokens served
80
- * on one are unpriced rather than charged at the standard rate.
81
+ * Tiers with a published per-token price (anything but `priority`, `batch`,
82
+ * `flex` and `scale`; a compatible endpoint may report `default` or `auto`).
83
+ * The vendor lists none for `priority` (a capacity commitment), `batch` (a
84
+ * different endpoint), `flex` or `scale`, so tokens served on one are
85
+ * unpriced rather than charged at the standard rate.
81
86
  */
82
87
  function isStandardTier(tier: string | undefined): boolean {
83
- return tier !== 'priority' && tier !== 'batch'
88
+ return tier !== 'priority' && tier !== 'batch' && tier !== 'flex' && tier !== 'scale'
84
89
  }
85
90
 
86
91
  function priceTokens(usage: TokenUsage, pricing: ModelPricing): Priced {
87
92
  if (!isStandardTier(usage.serviceTier)) {
88
93
  return { cost: 0, cacheDiscount: 0, unpriced: usage.totalTokens }
89
94
  }
95
+ if (usage.speed === 'ultrafast') {
96
+ // No published per-token price: counted as unpriced, never at the standard rate.
97
+ return { cost: 0, cacheDiscount: 0, unpriced: usage.totalTokens }
98
+ }
90
99
  if (usage.speed === 'fast') {
91
100
  const multiplier = pricing.fastMultiplier
92
101
  if (multiplier === undefined) {