@namzu/sdk 64.4.0 → 65.1.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 (61) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/agents/explore.d.ts +1 -1
  3. package/dist/agents/explore.d.ts.map +1 -1
  4. package/dist/agents/explore.js +3 -2
  5. package/dist/agents/explore.js.map +1 -1
  6. package/dist/agents/plan.d.ts +1 -1
  7. package/dist/agents/plan.d.ts.map +1 -1
  8. package/dist/agents/plan.js +3 -2
  9. package/dist/agents/plan.js.map +1 -1
  10. package/dist/prompt/coding-agent-doctrine.d.ts +2 -2
  11. package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
  12. package/dist/prompt/coding-agent-doctrine.js +39 -44
  13. package/dist/prompt/coding-agent-doctrine.js.map +1 -1
  14. package/dist/provider/errors.d.ts +10 -0
  15. package/dist/provider/errors.d.ts.map +1 -1
  16. package/dist/provider/errors.js +29 -1
  17. package/dist/provider/errors.js.map +1 -1
  18. package/dist/provider/fallback.d.ts.map +1 -1
  19. package/dist/provider/fallback.js +4 -3
  20. package/dist/provider/fallback.js.map +1 -1
  21. package/dist/provider/idle-timeout.js +1 -1
  22. package/dist/provider/idle-timeout.js.map +1 -1
  23. package/dist/provider/retry.js +1 -1
  24. package/dist/provider/retry.js.map +1 -1
  25. package/dist/provider/token-budget.d.ts.map +1 -1
  26. package/dist/provider/token-budget.js +9 -1
  27. package/dist/provider/token-budget.js.map +1 -1
  28. package/dist/runtime/query/iteration/index.d.ts +11 -0
  29. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  30. package/dist/runtime/query/iteration/index.js +93 -13
  31. package/dist/runtime/query/iteration/index.js.map +1 -1
  32. package/dist/runtime/query/turn/stall-monitor.d.ts +26 -0
  33. package/dist/runtime/query/turn/stall-monitor.d.ts.map +1 -1
  34. package/dist/runtime/query/turn/stall-monitor.js +45 -4
  35. package/dist/runtime/query/turn/stall-monitor.js.map +1 -1
  36. package/dist/types/provider/error.d.ts +7 -1
  37. package/dist/types/provider/error.d.ts.map +1 -1
  38. package/dist/types/provider/errors.d.ts.map +1 -1
  39. package/dist/types/provider/errors.js +5 -0
  40. package/dist/types/provider/errors.js.map +1 -1
  41. package/dist/types/provider/interface.d.ts +8 -6
  42. package/dist/types/provider/interface.d.ts.map +1 -1
  43. package/dist/types/session/records.d.ts +6 -0
  44. package/dist/types/session/records.d.ts.map +1 -1
  45. package/dist/types/session/records.js +11 -1
  46. package/dist/types/session/records.js.map +1 -1
  47. package/package.json +1 -1
  48. package/src/agents/explore.ts +3 -2
  49. package/src/agents/plan.ts +3 -2
  50. package/src/prompt/coding-agent-doctrine.ts +40 -45
  51. package/src/provider/errors.ts +32 -1
  52. package/src/provider/fallback.ts +4 -3
  53. package/src/provider/idle-timeout.ts +1 -1
  54. package/src/provider/retry.ts +1 -1
  55. package/src/provider/token-budget.ts +9 -1
  56. package/src/runtime/query/iteration/index.ts +105 -16
  57. package/src/runtime/query/turn/stall-monitor.ts +55 -4
  58. package/src/types/provider/error.ts +6 -0
  59. package/src/types/provider/errors.ts +5 -0
  60. package/src/types/provider/interface.ts +8 -6
  61. package/src/types/session/records.ts +11 -1
@@ -36,71 +36,66 @@ import type { PromptContribution } from './contributions.js'
36
36
 
37
37
  export const CODING_AGENT_WORKING_DOCTRINE = `## How you work
38
38
 
39
- ### Delivering work
40
- - Act when you have enough information. Take established facts and the user's decisions as settled.
41
- - Begin editing once you know the first change, and refine as you go. If you stop before changing anything, the next step starts from the same code.
42
- - The requested scope is the deliverable: deliver it at the size and on the subject it was asked. Read ambiguity the way a careful colleague would; make the routine judgment calls yourself and check in only when different readings would produce materially different work.
43
- - Finish the whole task, not just the easy parts. If one part is blocked — a tool or capability you do not have, an input that is missing — say so plainly instead of improvising a result for it, finish every other part in full, and say explicitly what you left out and why. Scaling the work down is the user's call.
44
- - If you find a real problem with the task as stated, say so in a sentence or two, then keep going under a stated assumption. Reserve blocking questions for cases where proceeding under any assumption would be unsafe or would make the work useless if wrong.
45
- - If the user repeats or reaffirms a request after you raised a concern, that is their decision: say so and do the full request.
39
+ ### Answering a question
40
+ - A question, or a description of a problem, gets an answer or an assessment first. Act only when asked to act, or when the answer needs a fact one look can get.
41
+ - Make that look one step: independent tool calls, such as every search for the fact, go in one response. When it does not give the fact, say what you looked at and what is missing, then stop; look further only when the result itself names where the fact is. When an investigation you were asked for cannot find the cause, report what you ruled out and what would settle it.
42
+ - Open with the answer, not with an apology or with agreement for its own sake.
43
+ - A step that says it will do something does it in that step, and a turn never ends on a promise of a later answer.
44
+
45
+ ### Asking and proceeding
46
+ - Act when you have enough information. Take established facts and the user's decisions as settled; decide routine matters yourself.
47
+ - Ask only when you cannot name the most likely reading of the request, or when proceeding under any assumption would be unsafe or would make the work useless if wrong. Ask once, with your best guess, because ending the turn stops all work.
48
+ - If you find a real problem with the task as stated, say so in a sentence, then keep going under a stated assumption. If the user repeats or reaffirms a request after you raised a concern, that is their decision: say so and do the full request.
49
+ - After a refused or empty result, change the request or report it; do not issue the same call again.
46
50
 
47
51
  ### Reporting
48
- - Report outcomes faithfully. If tests fail, say so and show the output. If you skipped a step, say it was skipped. When something is done and verified, state it plainly without hedging.
49
- - Report identifiers exactly as the evidence spells them, so the user can search for them.
50
- - Name what was actually executed, so a green run on a subset reads as that subset.
51
- - Reference code as \`path:line\` so the user can jump to it.
52
- - Correct an earlier statement only when the error would change the user's code, conclusions or decisions; state it once, plainly, and continue, and keep apologies and tallies of past mistakes out of it, because they spend the reader's attention on the past.
52
+ - Report outcomes faithfully: show failing test output, say what you skipped, and state what is done and verified.
53
+ - Report identifiers exactly as the evidence spells them, and reference code as \`path:line\`. Name what was actually executed, so a green run on a subset reads as that subset.
54
+ - Correct an earlier statement only when the error would change the user's code, conclusions or decisions; state it once, plainly, with no apology or tally of past mistakes, because they spend the reader's attention on the past.
53
55
 
54
56
  ### Using available evidence
55
- - Use what you have. Carry the active task and established facts across turns: a question or status request during ongoing work leaves that work in place unless the user says otherwise, and information already in the conversation needs no repeating. A successful tool result together with its exact inputs is evidence of what happened, and so is content you wrote; an announced action, a proposed call, a failed call or another agent's unsupported claim is not. Reuse evidence still in the conversation instead of observing it again by habit, and when you do observe, ask the narrowest question that resolves the uncertainty (a known file, not the whole working directory). Ask for clarification only when the intended change is genuinely unspecified.
56
- - Re-check what may have changed. Distinguish the last observed state from a guarantee that external state is unchanged, and observe again when evidence is missing, partial or invalidated, when another actor may have changed the target, or when freshness matters to the next action. If a check or exact-match edit reports a mismatch, inspect the current state and revise the action. Recover missing observations with read-only tools, because repeating a state-changing action changes state twice.
57
- - Say plainly when history is unavailable. Match the source to the time the question asks about: for an earlier observation use that observation or its retained original, since a fresh read of a mutable source cannot show what it held earlier. When the historical detail is gone, say so and leave today's value out of the answer.
58
-
59
- ### Reading and editing code
60
- - Before editing, use the relevant file content already available from a successful read or write; if it is unavailable or may be stale, read the needed portion. Read additional surrounding code when needed to match its naming and idiom. Respect project instructions and tool-specific prerequisites even when they require a fresh read.
61
- - Prefer the dedicated tools over shell equivalents (\`read\` over \`cat\`, \`grep\` over a shell grep, \`glob\` over \`find\`, \`edit\` over \`sed -i\`, \`write\` over a shell redirect), because their structured inputs and focused results are easier to check. Use \`bash\` when the task needs a shell; permissions apply the same way.
62
- - Independent tool calls go in one response: reading three files, or running a grep and a glob, does not need three turns. Wait for a mutation to finish before an observation or another action that depends on it; runtime ordering and concurrency limits remain authoritative.
63
- - For a defect, reproduce it first with a small script or a failing test, and keep it. Make the change, then rerun that reproduction. Afterwards run the project's tests and its lint or format check, add tests for behaviour you introduced, and say where any throwaway file you made is. Say in your report what you ran and what you did not run.
64
- - Match verification to the task and its risk. For a simple text-file operation, the successful tool result and known content are enough, so an unrelated project test or a repeated read adds nothing. For code changes, run the relevant tests, typecheck or lint that would catch a mistake, and follow required project checks. Claim only the checks you ran.
65
- - Describe the state you leave the working tree in: say where scratch files are, and which files outside the request you touched.
57
+ - A successful tool result with its exact inputs is evidence of what happened, and so is content you wrote; an announced action, a failed call or another agent's unsupported claim is not. A question or status request during ongoing work leaves that work in place unless the user says otherwise.
58
+ - Reuse evidence still in the conversation instead of observing it again by habit, and when you do observe, ask the narrowest question that resolves the uncertainty (a known file, not a directory). Observe again when evidence is missing, partial or stale, or the target may have changed. Recover missing observations with read-only tools; repeating a state-changing action changes state twice.
59
+ - If a check or an exact-match edit reports a mismatch, inspect the current state and revise the action.
60
+ - For a question about an earlier state, use that observation or its retained original; a fresh read of a mutable source cannot show what it held earlier. When the detail is gone, say so and leave today's value out.
61
+ - Wait for a mutation to finish before an observation or another action that depends on it.
62
+
63
+ ### When the task is to change code
64
+ This section applies only when you were asked to change something.
65
+ - Begin editing once you know the first change, and refine as you go. The requested scope is the deliverable, at the size asked.
66
+ - Finish the whole task, not just the easy parts. If one part is blocked (a tool you do not have, an input that is missing), say so plainly instead of improvising a result for it, finish every other part in full, and say what you left out and why.
67
+ - Before editing, use file content you already read or wrote; if it may be stale, read the needed portion again, and match the surrounding naming and idiom.
68
+ - Prefer the dedicated tools over shell equivalents (\`read\` over \`cat\`, \`grep\` over a shell grep, \`glob\` over \`find\`, \`edit\` over \`sed -i\`, \`write\` over a shell redirect); use \`bash\` for a shell.
69
+ - For a defect, reproduce it first with a small script or a failing test, and keep it; make the change, then rerun that reproduction. Run the project's tests and its lint or format check, and add tests for behaviour you introduced. For a simple text-file operation, the successful tool result and known content are enough. Claim only the checks you ran.
70
+ - Say where any throwaway file you made is, and which files outside the request you touched.
66
71
 
67
72
  ### Working with git
68
73
  - Never push, force-push, reset, rebase, clean, or otherwise discard or rewrite history unless the user explicitly asked for that action. Approval for one push does not extend to the next.
69
74
  - Before any command that could discard uncommitted work, run \`git status\`. If there are changes there that you did not make, stop and ask rather than stashing, committing or discarding somebody else's work.
70
- - Commit only when the user asks, on the branch that is checked out. Create or switch branches only when the user asks or the project's instructions require it, because the checked-out branch is the user's working state.
71
- - After a broad \`git add\`, review what was staged before committing; a file whose name looks harmless can still carry a secret.
75
+ - Commit only when the user asks, on the branch that is checked out, and switch branches only when asked or the project's instructions require it, because the checked-out branch is the user's working state. After a broad \`git add\`, review what was staged.
72
76
  - Never change git configuration or other persistent settings without asking: not \`user.name\` or \`user.email\`, hooks, remotes, credential helpers, or any \`git config\` (local or global), nor a shell profile or a tool's own config file. If a commit fails because no identity is set, stop and tell the user the command to set one; do not invent one.
73
77
 
74
- ### Answering a question
75
- - When the user asks a question or describes a problem, your reply answers or assesses it first. Act only when asked to act, or when the answer needs a fact that one look can get; if it still cannot be had, say what is missing instead of searching on.
76
- - Never open a reply with an apology or with agreement for its own sake. Begin with the answer.
77
- - A step that says it will do something does it in that step, and a turn never ends on a promise of a later answer.
78
- - Reply in the language the user wrote in and keep to the form they asked for, for example money and not tokens.
79
-
80
78
  ### Keeping the user informed
81
- - Before your first tool call, say in one short line what you are about to do and why. While you work, add a one-line update when you find something, change direction or hit a blocker, and after a long stretch without one, say in a few words where you are, then continue. Brief is good and silence is not; the tool rows on screen already show the details. A reply that is itself the answer needs no such line.
82
- - Keep the final reply short and specific: what changed, what was verified, what is left.`
79
+ - For work that takes several calls, say one short line before the first call and one more when you find something, change direction or hit a blocker, and a few words on where you are after a long stretch without one; a question that needs at most one look gets no such line, and no line goes beside each call, because the tool rows on screen show the details.
80
+ - When you changed something, close with what changed, what was verified and what is left. For a question the reply is the answer.`
83
81
 
84
82
  /**
85
83
  * Parent-only: rules about the task list and `Agent`, which a
86
84
  * delegated sub-agent does not have. See the module comment for the split.
87
85
  */
88
86
  export const CODING_AGENT_DELEGATION_DOCTRINE = `### Planning and delegating
89
- - A task list is optional. For work of three or more distinct steps — several files, several separate stages — you may keep one: exactly one step marked in progress at a time, each marked done when it is done rather than at the end, and the list cleared away once everything is done. Do not make one for a single inspect-edit-test cycle or a two-step job; a list of one or two items tells the user nothing. Keeping a list is not progress on the task itself.
90
- - When the \`Agent\` tool is available, do small work, or work whose target you already know, yourself: a file you can name, one search, one edit. A fresh sub-agent starts with none of your context. Delegate work that is independent of your next step, large, or whose output would flood your context, and give each delegation a short, specific description; the user watches those descriptions, not the prompts. Brief each sub-agent with four things: the objective; what is out of bounds; which tools and sources to use; and the shape of the reply you want, such as a short summary with a file path for anything long.
91
- - You keep the understanding. Pass paths, line numbers and what is already ruled out, never a conclusion for the sub-agent to confirm. Once delegated, do not do the work again yourself.
87
+ - A task list is optional. For work of three or more distinct steps you may keep one: one step in progress at a time, each marked done when it is done. Do not make one for a two-step job.
88
+ - When the \`Agent\` tool is available, do small work, or work whose target you already know, yourself: a file you can name, one search, one edit. A fresh sub-agent starts with none of your context. Delegate work that is independent of your next step, large, or whose output would flood your context, with a short description. Brief it with the objective, what is out of bounds, which tools and sources to use, and the shape of the reply you want.
89
+ - You keep the understanding: pass paths, line numbers and what is already ruled out, never a conclusion for the sub-agent to confirm, and once delegated, do not do the work again yourself.
92
90
  - A sub-agent's report is a claim, not a fact. Read any record line shown beside it, and check one claim you will build on against the files. Writers that run in parallel get separate worktrees (\`workspace: "worktree"\`, when the checkout is a git repo) or files that do not overlap, or the later write replaces the earlier one.
93
- - When the \`Agent\` tool lists a \`fork\` type, use \`subagent_type: "fork"\` when a side task would fill your context with output you will not need again, such as an open-ended survey. A fork starts from this conversation under your own instructions, so its prompt is only the directive: what to do and where its scope ends, without the background. Never write or guess what a fork will find before its report arrives. A fork cannot start forks of its own.
94
- - When delegated agents finish, tell the user what each one found in your next message. Their results reach you and not the user, so a result you do not pass on stays unseen.
95
- - Use \`subagent_type: "explore"\` to locate something small — where it is defined, which files reference it; it only reads and searches, and never interrupts the user for permission. It is not for reviewing or auditing whole files. Reserve the default sub-agent for work that changes files or runs commands.
91
+ - When the \`Agent\` tool lists a \`fork\` type, use \`subagent_type: "fork"\` for a side task whose output you will not need again; its prompt is only the directive. Never guess what it will find before its report arrives; a fork cannot start forks.
92
+ - When delegated agents finish, tell the user what each one found in your next message, because their results reach you and not the user.
93
+ - Use \`subagent_type: "explore"\` to locate something small; it only reads and searches, and never asks the user for permission. It is not for reviewing or auditing whole files. Reserve the default sub-agent for work that changes files or runs commands.
96
94
 
97
95
  ### Answering how work is going
98
- - When asked how things stand while background work runs, read the note about running work on your request first if the host gives you one, and add one status read from the tool that started an item only when the note does not say enough. The answer needs no waiting or polling and leaves the work running, because stopping or restarting an item to answer would lose what it has done.
99
- - Give each item the state you were given for it (progressing, waiting, stalled or dead) and how long ago it last moved, so the person can judge it for themselves. Stalled means only quiet for a while, not stuck.
100
- - Group the answer as finished (with its result), running (and where it is), queued, and needing a decision. Lead with the outcome, keep it short, and write in the language the person used, states included.
101
- - Name each item by what it is doing, not by its id: an id means nothing to the person, so give one only when they ask for it or need it for a command.
102
- - A result exists only once its completion message has arrived, so for an unfinished item say it is still running; a predicted result reads as a fact and may be wrong.
103
- - For an item reported dead, say it ended without a result and offer to run it again; starting the same work again unasked could repeat what it already did.`
96
+ - Read the note about running work on your request first if the host gives you one, and add one status read from the tool that started an item only when the note does not say enough. Leave the work running.
97
+ - Give each item the state you were given for it (progressing, waiting, stalled or dead) and how long ago it last moved; stalled means only quiet for a while. Group the answer as finished (with its result), running (and where it is), queued, and needing a decision, lead with the outcome, and name each item by what it is doing, not by its id.
98
+ - A result exists only once its completion message has arrived, so for an unfinished item say it is still running. For an item reported dead, say it ended without a result and offer to run it again.`
104
99
 
105
100
  /**
106
101
  * For a session whose permission layer refuses every mutation. Says what that
@@ -50,6 +50,9 @@ const PROVIDER_ERROR_KINDS: readonly ProviderErrorKind[] = [
50
50
  'context_overflow',
51
51
  'bad_request',
52
52
  'server',
53
+ 'credits',
54
+ 'moderation',
55
+ 'no_endpoints',
53
56
  ]
54
57
 
55
58
  /**
@@ -265,6 +268,9 @@ const KIND_SENTENCE: Record<ProviderErrorKind, string> = {
265
268
  context_overflow: 'the request exceeded the model context window',
266
269
  bad_request: 'the provider rejected the request as invalid',
267
270
  server: 'the provider failed to complete the request',
271
+ credits: 'the account has no credit left',
272
+ moderation: 'the input was flagged by moderation',
273
+ no_endpoints: 'no host is available to serve the request',
268
274
  }
269
275
 
270
276
  function buildProviderErrorMessage(init: ProviderRequestErrorInit): string {
@@ -315,6 +321,27 @@ export function bodySaysContextOverflow(body: string | undefined | null): boolea
315
321
  return OVERFLOW_BODY_PATTERNS.some((re) => re.test(body))
316
322
  }
317
323
 
324
+ /**
325
+ * Does a 403 body say the input was flagged by moderation rather than the key
326
+ * refused? A bare "flagged" does not count: a refusal about a key or an account
327
+ * can use that word too, and the person would then be told the model declined
328
+ * their message. The moderation answer names moderation, the flagged input, or
329
+ * says the input itself was flagged.
330
+ */
331
+ export function bodySaysModeration(body: string | undefined | null): boolean {
332
+ return (
333
+ !!body &&
334
+ /moderation|flagged_input|(?:input|prompt|messages?|content) (?:was |were |is |has been )?flagged|content (?:policy|filter)/i.test(
335
+ body,
336
+ )
337
+ )
338
+ }
339
+
340
+ /** Does a 404 body say no host can serve the request, rather than that a path is unknown? */
341
+ export function bodySaysNoEndpoints(body: string | undefined | null): boolean {
342
+ return !!body && /no endpoints? (?:found|available)/i.test(body)
343
+ }
344
+
318
345
  /**
319
346
  * `Retry-After` in milliseconds. The header is either delta-seconds or an
320
347
  * HTTP-date; both are specified, and vendors use both.
@@ -360,7 +387,11 @@ export function classifyProviderHttpStatus(
360
387
  status: number,
361
388
  body?: string | null,
362
389
  ): ProviderErrorKind {
363
- if (status === 401 || status === 403) return 'auth'
390
+ if (status === 402) return 'credits'
391
+ // A 403 is a refused key unless the body says the input was flagged.
392
+ if (status === 403) return bodySaysModeration(body) ? 'moderation' : 'auth'
393
+ if (status === 404 && bodySaysNoEndpoints(body)) return 'no_endpoints'
394
+ if (status === 401) return 'auth'
364
395
  if (status === 429) return 'throttle'
365
396
  if (status === 408 || status === 425) return 'network'
366
397
  if (status >= 500) return 'server'
@@ -561,8 +561,9 @@ export function withProviderFallback(
561
561
  const serving = members[cursor] ?? first
562
562
  return serving.provider.supportsImageInputFor?.(serving.model ?? model) ?? true
563
563
  },
564
- // A chain takes a forced choice only if every member does: the request may
565
- // be served by any of them, and the one that refuses would fail the step.
564
+ // A chain takes a forced choice only if every member says it does: the
565
+ // request may be served by any of them, and one that refuses (or cannot
566
+ // say) must not be sent a choice it may turn down.
566
567
  acceptsForcedToolChoiceFor: (
567
568
  model: string,
568
569
  thinking?: ThinkingConfig,
@@ -571,7 +572,7 @@ export function withProviderFallback(
571
572
  members.every(
572
573
  (member) =>
573
574
  member.provider.acceptsForcedToolChoiceFor?.(member.model ?? model, thinking, effort) ??
574
- true,
575
+ false,
575
576
  ),
576
577
  reasoningEffortLevelsFor: (model: string, thinking?: ThinkingConfig) =>
577
578
  commonReasoningEffortLevels(members, model, thinking),
@@ -229,7 +229,7 @@ export function withStreamIdleTimeout(
229
229
  model: string,
230
230
  thinking?: Parameters<NonNullable<LLMProvider['acceptsForcedToolChoiceFor']>>[1],
231
231
  effort?: Parameters<NonNullable<LLMProvider['acceptsForcedToolChoiceFor']>>[2],
232
- ) => provider.acceptsForcedToolChoiceFor?.(model, thinking, effort) ?? true,
232
+ ) => provider.acceptsForcedToolChoiceFor?.(model, thinking, effort) ?? false,
233
233
  }
234
234
  : {}),
235
235
  ...(provider.reasoningEffortLevelsFor
@@ -441,7 +441,7 @@ export function withProviderRetry(
441
441
  model: string,
442
442
  thinking?: Parameters<NonNullable<LLMProvider['acceptsForcedToolChoiceFor']>>[1],
443
443
  effort?: Parameters<NonNullable<LLMProvider['acceptsForcedToolChoiceFor']>>[2],
444
- ) => provider.acceptsForcedToolChoiceFor?.(model, thinking, effort) ?? true,
444
+ ) => provider.acceptsForcedToolChoiceFor?.(model, thinking, effort) ?? false,
445
445
  }
446
446
  : {}),
447
447
  ...(provider.reasoningEffortLevelsFor
@@ -21,7 +21,15 @@ export class TokenBudgetAdmissionError extends ProviderError {
21
21
 
22
22
  function rejectedBeforeGeneration(error: unknown): boolean {
23
23
  if (isProviderRequestError(error)) {
24
- return ['auth', 'throttle', 'context_overflow', 'bad_request'].includes(error.kind)
24
+ return [
25
+ 'auth',
26
+ 'throttle',
27
+ 'context_overflow',
28
+ 'bad_request',
29
+ 'credits',
30
+ 'moderation',
31
+ 'no_endpoints',
32
+ ].includes(error.kind)
25
33
  }
26
34
  const classified = classifyProviderError(error)
27
35
  const explicitRejection =
@@ -91,10 +91,13 @@ import { type OutcomeCall, OutcomeLedger, type PendingOutcomeCall } from '../tur
91
91
  import {
92
92
  FORCED_STEP_MESSAGE,
93
93
  REASONING_CAPPED_MESSAGE,
94
+ REASONING_CAPPED_REPORT_MESSAGE,
94
95
  REASONING_ONLY_MESSAGE,
95
96
  StallMonitor,
96
97
  asksQuestion,
97
98
  callChangedState,
99
+ callMadeProgress,
100
+ isSetAsideTool,
98
101
  reasoningCapChars,
99
102
  } from '../turn/stall-monitor.js'
100
103
  import { effortForModel } from './effort-clamp.js'
@@ -356,6 +359,8 @@ export class IterationOrchestrator {
356
359
  private cappedStreak = 0
357
360
  /** A reply that held only reasoning was already answered with one more request. */
358
361
  private reasoningOnlyRetried = false
362
+ /** A reply with nothing in it at all was already asked for again with the same request. */
363
+ private emptyReplyRetried = false
359
364
  /**
360
365
  * The model a refused request moved to. Once set it replaces the model the
361
366
  * step asked for, for the rest of the turn: the request that was refused
@@ -951,6 +956,7 @@ export class IterationOrchestrator {
951
956
  this.ctx.structuredOutput?.mode !== 'native' ||
952
957
  tool.function.name !== STRUCTURED_OUTPUT_TOOL_NAME,
953
958
  )
959
+ this.stepCannotChange = this.toolsCannotChange(llmTools)
954
960
  // The same list the request was built from now also bounds what
955
961
  // may run. Narrowing only the request left the restriction
956
962
  // presentational — the model was shown fewer tools and could
@@ -1232,16 +1238,31 @@ export class IterationOrchestrator {
1232
1238
  forcedAction && requestEffort && (offeredEfforts?.includes('low') ?? false)
1233
1239
  ? 'low'
1234
1240
  : requestEffort
1235
- // A provider that refuses a forced tool choice (some models do, and
1236
- // so does manual extended thinking) is not sent one: the step keeps
1237
- // its low effort and asks in words, on this request only.
1241
+ // A guard's action step sends a forced tool choice only where the
1242
+ // provider says one is safe and thinking is off for the request.
1243
+ // Every other case (a refusal, no answer, thinking on) asks in
1244
+ // words, on this request only, and keeps the step's low effort.
1245
+ //
1246
+ // A choice the step itself set (`step.toolChoice`) is a forced choice
1247
+ // whoever set it: `required` or a named function is dropped, and asked
1248
+ // in words, when the provider says it would refuse it.
1249
+ const stepChoiceForced =
1250
+ step.toolChoice !== undefined &&
1251
+ step.toolChoice !== 'auto' &&
1252
+ step.toolChoice !== 'none'
1253
+ const thinkingOn =
1254
+ turnConfig.thinking !== undefined && turnConfig.thinking.type !== 'disabled'
1255
+ const forcedChoiceAnswer =
1256
+ forcedAction || stepChoiceForced
1257
+ ? this.ctx.provider.acceptsForcedToolChoiceFor?.(
1258
+ stepModel,
1259
+ turnConfig.thinking,
1260
+ stepEffort,
1261
+ )
1262
+ : undefined
1238
1263
  const forcedChoiceRefused =
1239
- forcedAction &&
1240
- this.ctx.provider.acceptsForcedToolChoiceFor?.(
1241
- stepModel,
1242
- turnConfig.thinking,
1243
- stepEffort,
1244
- ) === false
1264
+ (forcedAction && (forcedChoiceAnswer !== true || thinkingOn)) ||
1265
+ (!forcedAction && stepChoiceForced && forcedChoiceAnswer === false)
1245
1266
  const operatorInputAtDispatch = this.latestUserMessage
1246
1267
  const latestReviewUserMessage =
1247
1268
  (this.ctx.reviewAnswer || this.ctx.structuredOutput?.review) && operatorInputAtDispatch
@@ -1285,7 +1306,9 @@ export class IterationOrchestrator {
1285
1306
  : llmTools.length > 0
1286
1307
  ? forcedAction && !forcedChoiceRefused
1287
1308
  ? (step.toolChoice ?? 'required')
1288
- : step.toolChoice
1309
+ : stepChoiceForced && forcedChoiceRefused
1310
+ ? undefined
1311
+ : step.toolChoice
1289
1312
  : undefined,
1290
1313
  temperature: step.temperature ?? turnConfig.temperature,
1291
1314
  maxTokens:
@@ -1638,10 +1661,17 @@ export class IterationOrchestrator {
1638
1661
  [NAMZU.TURN_ID]: recorder.turnId,
1639
1662
  [NAMZU.ITERATION]: iterationNum,
1640
1663
  })
1664
+ // An agent that cannot change anything is asked to report, and its
1665
+ // next step is not forced: a forced step could only be another look.
1641
1666
  recorder.pushMessage(
1642
- createRuntimeContextMessage(REASONING_CAPPED_MESSAGE, 'progress-nudge'),
1667
+ createRuntimeContextMessage(
1668
+ this.stepCannotChange
1669
+ ? REASONING_CAPPED_REPORT_MESSAGE
1670
+ : REASONING_CAPPED_MESSAGE,
1671
+ 'progress-nudge',
1672
+ ),
1643
1673
  )
1644
- this.forceActionNextStep = true
1674
+ if (!this.stepCannotChange) this.forceActionNextStep = true
1645
1675
  this.observeStall(response, [])
1646
1676
  await this.ctx.emitEvent({
1647
1677
  type: 'iteration_completed',
@@ -1938,7 +1968,10 @@ export class IterationOrchestrator {
1938
1968
  ? guardResult.stopReason
1939
1969
  : undefined
1940
1970
  const reasoningOnly = !hasContent && (response.message.reasoning?.length ?? 0) > 0
1941
- if (hasContent) this.reasoningOnlyRetried = false
1971
+ if (hasContent) {
1972
+ this.reasoningOnlyRetried = false
1973
+ this.emptyReplyRetried = false
1974
+ }
1942
1975
  // A reply of reasoning alone is not an end: ask once more, plainly,
1943
1976
  // before the closing request below.
1944
1977
  if (reasoningOnly && !forceFinalize && !this.reasoningOnlyRetried) {
@@ -1959,6 +1992,34 @@ export class IterationOrchestrator {
1959
1992
  yield* this.ctx.drainPending()
1960
1993
  continue
1961
1994
  }
1995
+ // A reply with no text, no reasoning and no call, that the provider
1996
+ // calls a normal stop, is asked for once more with the same request.
1997
+ // The empty entry stays in the history but never reaches the wire
1998
+ // (see withoutVoidAssistantTurns), so the request is unchanged. A
1999
+ // reply cut at the output allowance is not this case: asking again
2000
+ // spends the same allowance. Reasoning alone has its own path above.
2001
+ const emptyReply =
2002
+ !hasContent &&
2003
+ !reasoningOnly &&
2004
+ (response.message.toolCalls?.length ?? 0) === 0 &&
2005
+ response.finishReason === 'stop'
2006
+ if (emptyReply && !forceFinalize && !this.emptyReplyRetried) {
2007
+ this.emptyReplyRetried = true
2008
+ this.ctx.log.warn('Reply was empty — asking again with the same request', {
2009
+ [NAMZU.TURN_ID]: recorder.turnId,
2010
+ [NAMZU.ITERATION]: iterationNum,
2011
+ 'namzu.retry.attempt': 1,
2012
+ 'namzu.retry.reason': 'empty_reply',
2013
+ })
2014
+ await this.ctx.emitEvent({
2015
+ type: 'iteration_completed',
2016
+ turnId: recorder.turnId,
2017
+ iteration: iterationNum,
2018
+ hasToolCalls: false,
2019
+ })
2020
+ yield* this.ctx.drainPending()
2021
+ continue
2022
+ }
1962
2023
  if (!hasContent && !forceFinalize) {
1963
2024
  this.ctx.log.warn('Empty completion detected — requesting final summary', {
1964
2025
  [NAMZU.ITERATION]: iterationNum,
@@ -1972,7 +2033,7 @@ export class IterationOrchestrator {
1972
2033
  // Never end silently: if even the closing request produced nothing,
1973
2034
  // say so in plain words and how to go on.
1974
2035
  if (
1975
- reasoningOnly &&
2036
+ (reasoningOnly || (emptyReply && this.emptyReplyRetried)) &&
1976
2037
  closingStopReason === undefined &&
1977
2038
  !(
1978
2039
  (
@@ -1983,7 +2044,9 @@ export class IterationOrchestrator {
1983
2044
  ).length
1984
2045
  ) {
1985
2046
  recorder.setLastError(
1986
- 'The model stopped after thinking without giving an answer or taking an action, even when asked again. Say "continue" and it will pick the work up from here.',
2047
+ reasoningOnly
2048
+ ? 'The model stopped after thinking without giving an answer or taking an action, even when asked again. Say "continue" and it will pick the work up from here.'
2049
+ : 'The model sent an empty reply twice, without an answer or an action. Say "continue" and it will pick the work up from here.',
1987
2050
  )
1988
2051
  }
1989
2052
  }
@@ -2090,6 +2153,7 @@ export class IterationOrchestrator {
2090
2153
  costBefore,
2091
2154
  })
2092
2155
  this.reasoningOnlyRetried = false
2156
+ this.emptyReplyRetried = false
2093
2157
  this.observeStall(response, reviewOutcome.results)
2094
2158
  this.observeAudit(response, reviewOutcome.results)
2095
2159
  await this.outcomeObserve(iterationNum, response, reviewOutcome.results)
@@ -3616,6 +3680,7 @@ export class IterationOrchestrator {
3616
3680
  const calls = new Map((response.message.toolCalls ?? []).map((c) => [c.id, c]))
3617
3681
  let changedState = false
3618
3682
  const question = asksQuestion(this.latestUserMessage?.content)
3683
+ const cannotChange = this.stepCannotChange
3619
3684
  for (const result of results) {
3620
3685
  const call = calls.get(result.toolCallId)
3621
3686
  let readOnly: boolean | undefined
@@ -3625,7 +3690,7 @@ export class IterationOrchestrator {
3625
3690
  } catch {
3626
3691
  readOnly = undefined
3627
3692
  }
3628
- if (callChangedState(result.toolName, readOnly, result.isError)) {
3693
+ if (callMadeProgress(result.toolName, readOnly, result.isError, cannotChange)) {
3629
3694
  // The same tool with the same input and the same result as an
3630
3695
  // earlier call this turn changed nothing, whatever the tool is,
3631
3696
  // except a file edit: applying, reverting and applying again is
@@ -3646,6 +3711,7 @@ export class IterationOrchestrator {
3646
3711
  reasoningChars,
3647
3712
  changedState,
3648
3713
  question,
3714
+ cannotChange,
3649
3715
  })
3650
3716
  if (directive.kind === 'nudge') {
3651
3717
  this.ctx.log.info('Many steps without a change — nudging the model to act', {
@@ -3660,6 +3726,29 @@ export class IterationOrchestrator {
3660
3726
  }
3661
3727
  }
3662
3728
 
3729
+ /** Whether every tool offered to the step in flight only reads. */
3730
+ private stepCannotChange = false
3731
+
3732
+ /**
3733
+ * Whether an agent given these tools can change nothing: each one declares
3734
+ * itself read-only without being shown an input (the test the read-only
3735
+ * sub-agents' roster uses), task-list tools and `send_message` aside. A tool that does not say,
3736
+ * or that says so only for some inputs, counts as one that can change things.
3737
+ */
3738
+ private toolsCannotChange(llmTools: readonly { function: { name: string } }[]): boolean {
3739
+ let looked = false
3740
+ for (const { function: fn } of llmTools) {
3741
+ if (isSetAsideTool(fn.name)) continue
3742
+ try {
3743
+ if (this.ctx.tools.get(fn.name)?.isReadOnly?.(undefined) !== true) return false
3744
+ } catch {
3745
+ return false
3746
+ }
3747
+ looked = true
3748
+ }
3749
+ return looked
3750
+ }
3751
+
3663
3752
  /** Fingerprints of the calls this turn has finished, for {@link seenAgain}. */
3664
3753
  private readonly finishedCalls = new Set<string>()
3665
3754
 
@@ -14,6 +14,13 @@ import type { ReasoningEffort } from '../../../types/provider/index.js'
14
14
  export const REASONING_CAPPED_MESSAGE =
15
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
+ /**
18
+ * What an agent that cannot change anything is told when a step spent its
19
+ * whole reasoning allowance before acting: it reports, it does not look again.
20
+ */
21
+ export const REASONING_CAPPED_REPORT_MESSAGE =
22
+ 'Your thinking for that step reached its limit before you acted, so it was cut short. Report now what you have found and what is still unknown, using what you have already seen. Look further only to close a gap you can name.'
23
+
17
24
  /** What the model is told when a reply held thinking but no answer and no action. */
18
25
  export const REASONING_ONLY_MESSAGE =
19
26
  'Your last reply held thinking only: no answer and no action. Continue now: give your answer, or make the call that moves the task forward.'
@@ -22,6 +29,13 @@ export const REASONING_ONLY_MESSAGE =
22
29
  export const STALL_NUDGE_MESSAGE =
23
30
  '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
31
 
32
+ /**
33
+ * What an agent that cannot change anything is told when its looks stopped
34
+ * adding anything new: it reports, it does not edit.
35
+ */
36
+ export const STALL_REPORT_MESSAGE =
37
+ '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.'
38
+
25
39
  /**
26
40
  * What the model is told when it was asked a question and several steps have
27
41
  * only looked. It names the way out as the answer, never as another command.
@@ -96,6 +110,34 @@ export function callChangedState(
96
110
  return readOnly !== true
97
111
  }
98
112
 
113
+ /**
114
+ * Whether a finished call moved an agent forward. For an agent that can change
115
+ * things this is {@link callChangedState}. An agent whose every tool only
116
+ * reads has nothing to change, so a successful read that is not a repeat is
117
+ * its progress; repeats are judged by the caller, and a task-list call or a
118
+ * failed call is still none.
119
+ */
120
+ export function callMadeProgress(
121
+ toolName: string,
122
+ readOnly: boolean | undefined,
123
+ isError: boolean | undefined,
124
+ cannotChange: boolean,
125
+ ): boolean {
126
+ if (cannotChange && isSetAsideTool(toolName)) return false
127
+ if (callChangedState(toolName, readOnly, isError)) return true
128
+ if (!cannotChange || isError) return false
129
+ return readOnly === true
130
+ }
131
+
132
+ /**
133
+ * Tools that neither look nor change the work, so they are set aside when
134
+ * deciding whether an agent can change anything: the task list, and the
135
+ * message a sub-agent sends to the conversation that launched it.
136
+ */
137
+ export function isSetAsideTool(toolName: string): boolean {
138
+ return TASK_LIST_TOOLS.has(toolName) || toolName === 'send_message'
139
+ }
140
+
99
141
  /** When the monitor speaks. All counts are of consecutive steps that changed nothing. */
100
142
  export interface StallConfig {
101
143
  /** Steps without a change after which the model is nudged. Default 12. */
@@ -126,6 +168,8 @@ export interface StallObservation {
126
168
  readonly changedState: boolean
127
169
  /** The person's latest message asked a question, so the way out of a stall is an answer. */
128
170
  readonly question?: boolean
171
+ /** Every tool offered to the step only reads: the way out of a stall is a report, not an edit. */
172
+ readonly cannotChange?: boolean
129
173
  }
130
174
 
131
175
  /** The longest message still read as a question; a longer one is a brief. */
@@ -170,6 +214,12 @@ export class StallMonitor {
170
214
  this.idleSteps += 1
171
215
  this.idleChars += step.reasoningChars
172
216
  const question = step.question === true
217
+ const cannotChange = step.cannotChange === true
218
+ const stallText = question
219
+ ? ANSWER_NOW_MESSAGE
220
+ : cannotChange
221
+ ? STALL_REPORT_MESSAGE
222
+ : STALL_NUDGE_MESSAGE
173
223
  if (!this.nudged) {
174
224
  if (question && this.idleSteps >= this.answerAfterSteps) {
175
225
  this.nudged = true
@@ -179,16 +229,17 @@ export class StallMonitor {
179
229
  if (this.idleSteps >= this.nudgeAfterSteps || this.idleChars >= this.nudgeAfterChars) {
180
230
  this.nudged = true
181
231
  this.stepsSinceNudge = 0
182
- return { kind: 'nudge', text: question ? ANSWER_NOW_MESSAGE : STALL_NUDGE_MESSAGE }
232
+ return { kind: 'nudge', text: stallText }
183
233
  }
184
234
  return { kind: 'none' }
185
235
  }
186
236
  this.stepsSinceNudge += 1
187
237
  if (this.stepsSinceNudge >= this.forceAfterSteps) {
188
238
  this.reset()
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' }
239
+ // A question is answered, and an agent that cannot change anything
240
+ // reports: say it again instead of forcing a tool call, which would
241
+ // only buy another look.
242
+ return question || cannotChange ? { kind: 'nudge', text: stallText } : { kind: 'force' }
192
243
  }
193
244
  return { kind: 'none' }
194
245
  }
@@ -6,6 +6,12 @@ export type ProviderErrorKind =
6
6
  | 'context_overflow'
7
7
  | 'bad_request'
8
8
  | 'server'
9
+ /** HTTP 402: the account has no credit left. Resending cannot help until it is topped up. */
10
+ | 'credits'
11
+ /** HTTP 403 whose body says the input was flagged by moderation, as opposed to a refused key (`auth`). */
12
+ | 'moderation'
13
+ /** HTTP 404 whose body says no host can serve the request (for example "No endpoints found"). */
14
+ | 'no_endpoints'
9
15
 
10
16
  /**
11
17
  * Serializable provider-failure metadata carried by failed turns and events.
@@ -572,6 +572,11 @@ const KIND_TO_CODE: Readonly<Record<string, { code: ProviderErrorCode; retryable
572
572
  auth: { code: 'auth', retryable: false },
573
573
  context_overflow: { code: 'context_length_exceeded', retryable: false },
574
574
  bad_request: { code: 'invalid_request', retryable: false },
575
+ // Spent credit is a spent allowance: the same non-retryable code a host
576
+ // already answers by offering another account.
577
+ credits: { code: 'usage_limit', retryable: false },
578
+ moderation: { code: 'content_filter', retryable: false },
579
+ no_endpoints: { code: 'not_found', retryable: false },
575
580
  }
576
581
 
577
582
  function classifyFromProviderRequestError(