nanoPyCodeAgent 0.8.0__py3-none-any.whl → 0.10.0__py3-none-any.whl

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.
nanopycodeagent/agent.py CHANGED
@@ -11,18 +11,18 @@ or overwrite them, an ``edit`` tool to replace part of one, and a ``bash``
11
11
  tool to run shell commands; every call and its output are echoed to the
12
12
  terminal as they happen.
13
13
 
14
- The interactive loop handles only the happy path: anything unexpected — a
15
- network error, a Ctrl-C mid-turn — crashes the session, and restarting it is
16
- the recovery. That trade keeps the core flow readable; the hardened variant
17
- it replaced is preserved at the ``hardened-agent-loop`` tag. A headless run
18
- has no one to restart it, so it catches API errors, reports them verbatim,
19
- and turns them into an exit code.
14
+ Both modes retry interrupted response streams before changing conversation
15
+ history or running tools. Other unexpected failures and Ctrl-C mid-turn still
16
+ end an interactive session. Headless mode catches exhausted API/transport
17
+ errors, reports them verbatim, and turns them into an exit code.
20
18
  """
21
19
 
20
+ import json
22
21
  import os
23
22
  import sys
24
23
  import time
25
24
  import uuid
25
+ from copy import copy
26
26
  from importlib.metadata import PackageNotFoundError, version
27
27
  from pathlib import Path
28
28
 
@@ -37,34 +37,53 @@ except ImportError: # pragma: no cover - platform without readline
37
37
  pass
38
38
 
39
39
  import anthropic
40
- import httpx
41
40
  from anthropic.types import MessageParam, ToolResultBlockParam, ToolUseBlock
42
41
 
43
42
  from .atif import project_atif, write_atif
44
- from .bash_tool import BASH_TOOL, run_bash
43
+ from .bash_tool import run_bash
45
44
  from .cost import (
45
+ estimated_cost,
46
46
  pending_cost,
47
47
  resolve_generation_cost,
48
48
  usage_cost,
49
49
  )
50
- from .edit_tool import EDIT_TOOL, edit_preview, run_edit
50
+ from .edit_tool import edit_preview, run_edit
51
+ from .deadline import DeadlineExceeded, check_deadline_support, wall_clock_limit
51
52
  from .event_journal import (
52
53
  EventEmitter,
53
54
  EventJournal,
54
55
  JsonObject,
55
56
  JsonValue,
56
57
  NativeEvent,
58
+ RunOutcome,
57
59
  utc_now,
58
60
  )
59
- from .read_tool import READ_TOOL, run_read
60
- from .settings import load_settings_env
61
+ from .read_tool import run_read
62
+ from .settings import DEFAULT_MAX_TOKENS, load_settings_env, resolve_max_tokens
61
63
  from .terminal import Spinner, print_tool_output, print_tool_use
62
- from .write_tool import WRITE_TOOL, content_preview, run_write
64
+ from .tool_validation import TOOLS, tool_input_error
65
+ from .transport import HTTP_ERRORS, RETRYABLE_STREAM_ERRORS
66
+ from .write_tool import content_preview, run_write
63
67
 
64
68
  # The model used when ANTHROPIC_MODEL is set in neither the environment nor
65
69
  # the config file.
66
70
  DEFAULT_MODEL = "claude-sonnet-4-6"
67
- MAX_TOKENS = 8192
71
+
72
+ # The SDK retries failures before streaming begins. Recover interrupted response
73
+ # bodies here, before committing a reply to history or executing any of its tools.
74
+ STREAM_RETRY_DELAYS = (1.0, 2.0)
75
+ STREAM_RETRY_WINDOW_SECONDS = 300.0
76
+
77
+ _TRUNCATION_NOTICE = (
78
+ "[response truncated: reached max_tokens before finishing the task. "
79
+ "Tool calls from this response were not executed.]"
80
+ )
81
+ _TRUNCATION_RECOVERY_NOTE = (
82
+ "The previous response reached its output limit without finishing the task. "
83
+ "No tool calls from that response were executed. Continue from the last "
84
+ "confirmed tool results and current files within the remaining budget. "
85
+ "This is the only automatic truncation recovery for this run."
86
+ )
68
87
 
69
88
  # How many model replies one headless task may spend before the run stops on
70
89
  # its own. The interactive loop needs no such cap — a human watching the
@@ -73,6 +92,91 @@ MAX_TOKENS = 8192
73
92
  # refuses it.
74
93
  DEFAULT_MAX_TURNS = 50
75
94
 
95
+ # A headless run may also be given a wall-clock budget. When it is, the loop
96
+ # tells the model how much time is left and stops before the harness's own
97
+ # timeout can kill the process with nothing written. The last stretch is
98
+ # reserved so the model still has room to write the task's output file.
99
+ _FINALIZATION_RESERVE_SECONDS = 180
100
+ _FINALIZATION_RESERVE_FRACTION = 0.15
101
+ _FINALIZATION_RESERVE_TURNS = 10
102
+ _COST_RECONCILIATION_SECONDS = 30
103
+
104
+
105
+ def _format_duration(total_seconds: float) -> str:
106
+ total = max(0, int(total_seconds))
107
+ return f"{total // 60}:{total % 60:02d}"
108
+
109
+
110
+ def _time_budget_note(
111
+ *, turn: int, elapsed: float, budget: float | None, remaining: float | None,
112
+ max_turns: int | None = None,
113
+ ) -> str:
114
+ """Tell the model about both limits before either prevents finalization."""
115
+ replies_left = None if max_turns is None else max_turns - turn + 1
116
+ turn_note = f"Turn {turn}. " if max_turns is None else (
117
+ f"Turn {turn} of {max_turns}; {replies_left} replies remaining including "
118
+ "this one. The last reply must be a final summary: its tool calls "
119
+ "will not execute. "
120
+ )
121
+ time_low = remaining is not None and remaining <= max(
122
+ _FINALIZATION_RESERVE_FRACTION * budget, _FINALIZATION_RESERVE_SECONDS
123
+ )
124
+ note = "[runtime budget] " + turn_note
125
+ if remaining is not None:
126
+ note += (
127
+ f"Only {_format_duration(remaining)} of {_format_duration(budget)} left. "
128
+ if time_low else
129
+ f"Elapsed {_format_duration(elapsed)} of {_format_duration(budget)}; "
130
+ f"{_format_duration(remaining)} remaining. "
131
+ )
132
+ if time_low or (replies_left is not None and replies_left <= _FINALIZATION_RESERVE_TURNS):
133
+ note += (
134
+ "Finalize now. Stop investigating new approaches. Complete and save "
135
+ "the required deliverables, perform only the necessary checks, then "
136
+ "reply with a short summary and no further tool calls. If incomplete, "
137
+ "save useful progress and state the remaining limitation honestly."
138
+ )
139
+ else:
140
+ note += (
141
+ "Keep required deliverables up to date. Once the requirements are "
142
+ "satisfied and checked, finish immediately; unused budget is not "
143
+ "a reason to continue investigating."
144
+ )
145
+ return note
146
+
147
+
148
+ def _append_budget_note(
149
+ messages: list[MessageParam],
150
+ note: str,
151
+ *,
152
+ emitter: EventEmitter,
153
+ model_call_id: str,
154
+ reason: str = "time_budget",
155
+ ) -> None:
156
+ """Append a wall-clock reminder to the tail of the conversation.
157
+
158
+ The reminder goes into the most recent user message — the initial task, or
159
+ the tool results — rather than the system prompt. Rewriting the system
160
+ prompt each turn changes the very first tokens of every request and defeats
161
+ the provider's prefix cache; appending to the tail keeps each request an
162
+ extension of the previous one, so the cached prefix survives.
163
+ """
164
+ last = messages[-1]
165
+ content = last["content"]
166
+ if isinstance(content, str):
167
+ last["content"] = f"{content}\n\n{note}"
168
+ else:
169
+ content.append({"type": "text", "text": note})
170
+ emitter.emit(
171
+ "input.injected",
172
+ {
173
+ "model_call_id": model_call_id,
174
+ "content": note,
175
+ "reason": reason,
176
+ "source_timestamp": utc_now(),
177
+ },
178
+ )
179
+
76
180
  # Shared by both system prompts: which tool to reach for is the same question
77
181
  # whoever is asking.
78
182
  _TOOL_GUIDANCE = (
@@ -98,13 +202,35 @@ HEADLESS_SYSTEM_PROMPT = (
98
202
  "out. Work the task through to the end, then check the result with the "
99
203
  "tools instead of assuming it worked. When it is done, answer with a "
100
204
  "short summary and no further tool calls: that reply is what ends the "
101
- "run. "
205
+ "run. Runtime budget reminders report remaining time and model replies; "
206
+ "when either is running low, prioritize saving the required deliverables, "
207
+ "necessary verification, and a final summary. Do not start optional work "
208
+ "after the requirements are satisfied.\n\n"
209
+ "Identify the required deliverables, interfaces, and constraints. Treat "
210
+ "examples as evidence, not as the full contract unless the task says so. "
211
+ "Inspect relevant files, dependencies, and existing checks instead of "
212
+ "guessing. Task-supplied workspace files, including source, executables, "
213
+ "and tests, are available references unless the task restricts their use. "
214
+ "Consult general documentation as needed. Do not seek or use task-specific "
215
+ "reference solutions or hidden evaluation tests from outside the supplied "
216
+ "materials unless the task explicitly requests them. Derive checks from "
217
+ "the stated requirements.\n\n"
218
+ "Verify the requested behavior through the real entry point when feasible. "
219
+ "Check the content and meaning of outputs, not only command success or "
220
+ "file existence. For logic or numerical work, choose a few representative "
221
+ "and boundary cases justified by the task, using an independent reference, "
222
+ "invariant, or consistency check when available. Do not derive every "
223
+ "expectation from the implementation being tested or weaken requirements "
224
+ "to make a check pass. Keep verification proportional to the task and "
225
+ "remaining budget.\n\n"
226
+ "When a check fails, inspect the error and relevant output, revise the "
227
+ "underlying assumption or implementation, and rerun the affected check. "
228
+ "Keep the task's constraints intact. Once appropriate checks support the "
229
+ "required behavior, save the deliverables and finish. State what was "
230
+ "verified and any remaining limitation without claiming unobserved "
231
+ "success.\n\n"
102
232
  ) + _TOOL_GUIDANCE
103
233
 
104
- # Every tool offered to the model on each request.
105
- TOOLS = [READ_TOOL, WRITE_TOOL, EDIT_TOOL, BASH_TOOL]
106
-
107
-
108
234
  def _json_value(value: object) -> JsonValue:
109
235
  """Convert an SDK value into the provider-neutral event representation."""
110
236
  if value is None or isinstance(value, bool | int | float | str):
@@ -139,12 +265,19 @@ def _native_content_blocks(value: object) -> list[JsonValue]:
139
265
  if source_type == "text":
140
266
  content.append({"type": "text", "text": source_block.get("text", "")})
141
267
  elif source_type == "tool_use":
268
+ arguments = source_block.get("input")
142
269
  content.append(
143
270
  {
144
271
  "type": "tool_call",
145
272
  "tool_call_id": source_block.get("id"),
146
273
  "tool_name": source_block.get("name"),
147
- "input": source_block.get("input"),
274
+ # Journal/ATIF require object arguments. Keep rejected
275
+ # non-object input separately instead of discarding it.
276
+ "input": arguments if isinstance(arguments, dict) else {},
277
+ **(
278
+ {"raw_input": arguments}
279
+ if not isinstance(arguments, dict) else {}
280
+ ),
148
281
  }
149
282
  )
150
283
  else:
@@ -192,12 +325,27 @@ class _TextOutputProjector:
192
325
  model_call_id = str(event.payload["model_call_id"])
193
326
  if model_call_id in self._model_calls_with_text:
194
327
  print()
328
+ if event.payload["stop_reason"] == "max_tokens":
329
+ print(_TRUNCATION_NOTICE, file=sys.stderr)
330
+ elif event.type == "input.injected" and event.payload["reason"] == "truncation_recovery":
331
+ print("[continuing after response truncation; recovery 1/1]", file=sys.stderr)
332
+ elif event.type == "model.failed" and event.payload["will_retry"]:
333
+ if str(event.payload["model_call_id"]) in self._model_calls_with_text:
334
+ print()
335
+ print(
336
+ f"[response interrupted: {event.payload['error_type']}; "
337
+ f"retrying in {event.payload['retry_delay_seconds']:g}s]",
338
+ file=sys.stderr,
339
+ )
195
340
  elif event.type == "tool.started":
196
341
  tool_name = str(event.payload["tool_name"])
197
342
  arguments = event.payload["input"]
198
- if not isinstance(arguments, dict):
199
- raise TypeError("tool input event payload must be an object")
200
- if tool_name == "read":
343
+ error = event.payload.get("input_error") or tool_input_error(
344
+ tool_name, arguments
345
+ )
346
+ if error:
347
+ print_tool_use(f"[{tool_name}] (invalid arguments; not executed)")
348
+ elif tool_name == "read":
201
349
  print_tool_use(f"[read] {arguments['path']}")
202
350
  elif tool_name == "write":
203
351
  content = str(arguments["content"])
@@ -211,7 +359,7 @@ class _TextOutputProjector:
211
359
  f"[edit] {arguments['path']}\n"
212
360
  f"{edit_preview(old_text, new_text)}"
213
361
  )
214
- else:
362
+ elif tool_name == "bash":
215
363
  print_tool_use(f"[bash]$ {arguments['command']}")
216
364
  elif event.type == "tool.completed":
217
365
  result = event.payload["result"]
@@ -237,24 +385,29 @@ def _run_one_tool(
237
385
  block: ToolUseBlock,
238
386
  emitter: EventEmitter,
239
387
  model_call_id: str,
388
+ *,
389
+ input_error: str | None = None,
390
+ remaining_seconds: float | None = None,
240
391
  ) -> ToolResultBlockParam:
241
392
  """Execute one ``tool_use`` block and emit its runtime facts."""
242
393
  tool_input = _json_value(block.input)
243
- if not isinstance(tool_input, dict):
244
- raise TypeError("tool input must be an object")
394
+ input_error = input_error or tool_input_error(block.name, tool_input)
245
395
  emitter.emit(
246
396
  "tool.started",
247
397
  {
248
398
  "model_call_id": model_call_id,
249
399
  "tool_call_id": block.id,
250
400
  "tool_name": block.name,
251
- "input": tool_input,
401
+ "input": tool_input if isinstance(tool_input, dict) else {},
402
+ **({"input_error": input_error} if input_error else {}),
252
403
  "source_timestamp": utc_now(),
253
404
  },
254
405
  )
255
406
  tool_started_ns = time.perf_counter_ns()
256
407
  try:
257
- if block.name == "read":
408
+ if input_error:
409
+ output, is_error = input_error, True
410
+ elif block.name == "read":
258
411
  path = block.input["path"]
259
412
  output, is_error = run_read(
260
413
  path,
@@ -275,10 +428,13 @@ def _run_one_tool(
275
428
  new_text,
276
429
  replace_all=block.input.get("replace_all", False),
277
430
  )
278
- else: # bash — the only other tool offered
431
+ else: # bash; unknown names have already been rejected
279
432
  command = block.input["command"]
280
433
  with Spinner("Running..."):
281
- output, is_error = run_bash(command)
434
+ output, is_error = run_bash(command, **(
435
+ {"timeout_seconds": remaining_seconds}
436
+ if remaining_seconds is not None else {}
437
+ ))
282
438
  except BaseException as exc:
283
439
  emitter.emit(
284
440
  "tool.completed",
@@ -303,6 +459,10 @@ def _run_one_tool(
303
459
  "tool_name": block.name,
304
460
  "result": output,
305
461
  "is_error": is_error,
462
+ **(
463
+ {"error": {"type": "ToolInputError", "message": input_error}}
464
+ if input_error else {}
465
+ ),
306
466
  "duration_ms": (time.perf_counter_ns() - tool_started_ns) / 1_000_000,
307
467
  "source_timestamp": utc_now(),
308
468
  },
@@ -352,17 +512,22 @@ def _run_exchange(
352
512
  system: str,
353
513
  *,
354
514
  max_turns: int | None = None,
515
+ max_tokens: int = DEFAULT_MAX_TOKENS,
516
+ time_budget_seconds: int | None = None,
355
517
  reply_prefix: str = "\nAgent> ",
356
518
  trajectory_path: Path | None = None,
357
- ) -> bool:
519
+ ) -> RunOutcome:
358
520
  """Reply to the conversation so far, running tools until the model stops.
359
521
 
360
- Appends every assistant reply and tool result to ``messages`` in place.
361
- Returns True when the model ended a reply without asking for tools, and
362
- False when ``max_turns`` replies were spent while it was still calling
363
- them — the caller decides what an exhausted budget means.
522
+ Appends assistant replies and tool results to ``messages`` in place.
523
+ A truncated reply retains only its text and a notice in request history;
524
+ the original response is kept in the journal. Headless runs may recover
525
+ once within the original budgets. Returns the stopping outcome,
526
+ distinguishing completion, turn-budget exhaustion, and response truncation.
364
527
  """
365
528
  run_id = f"run-{uuid.uuid4()}"
529
+ if time_budget_seconds is not None:
530
+ check_deadline_support()
366
531
  run_started_ns = time.perf_counter_ns()
367
532
  projector = _TextOutputProjector(reply_prefix)
368
533
  with EventJournal.create(run_id) as journal:
@@ -370,9 +535,15 @@ def _run_exchange(
370
535
  emitter.emit(
371
536
  "run.started",
372
537
  {
373
- "mode": "headless" if max_turns is not None else "interactive",
538
+ "mode": (
539
+ "headless"
540
+ if max_turns is not None or time_budget_seconds is not None
541
+ else "interactive"
542
+ ),
374
543
  "model": model,
375
544
  "max_turns": max_turns,
545
+ "max_tokens": max_tokens,
546
+ "time_budget_seconds": time_budget_seconds,
376
547
  "producer": {
377
548
  "name": "nanoPyCodeAgent",
378
549
  "version": _package_version(),
@@ -390,16 +561,21 @@ def _run_exchange(
390
561
  },
391
562
  )
392
563
  try:
393
- finished = _run_model_loop(
564
+ outcome = _run_model_loop(
394
565
  client,
395
566
  model,
396
567
  messages,
397
568
  system,
398
569
  emitter=emitter,
399
570
  max_turns=max_turns,
571
+ max_tokens=max_tokens,
572
+ time_budget_seconds=time_budget_seconds,
400
573
  )
401
574
  except BaseException as exc:
402
- cost_reconciliation = _reconcile_costs(client, journal, emitter)
575
+ cost_reconciliation = _reconcile_costs(
576
+ client, journal, emitter,
577
+ max_seconds=_COST_RECONCILIATION_SECONDS if time_budget_seconds else None,
578
+ )
403
579
  emitter.emit(
404
580
  "run.failed",
405
581
  {
@@ -417,11 +593,14 @@ def _run_exchange(
417
593
  )
418
594
  raise
419
595
  else:
420
- cost_reconciliation = _reconcile_costs(client, journal, emitter)
596
+ cost_reconciliation = _reconcile_costs(
597
+ client, journal, emitter,
598
+ max_seconds=_COST_RECONCILIATION_SECONDS if time_budget_seconds else None,
599
+ )
421
600
  emitter.emit(
422
601
  "run.completed",
423
602
  {
424
- "outcome": "completed" if finished else "max_turns_exhausted",
603
+ "outcome": outcome,
425
604
  "duration_ms": (time.perf_counter_ns() - run_started_ns)
426
605
  / 1_000_000,
427
606
  **(
@@ -438,7 +617,7 @@ def _run_exchange(
438
617
  project_atif(EventJournal.replay(journal.path)),
439
618
  trajectory_path,
440
619
  )
441
- return finished
620
+ return outcome
442
621
 
443
622
 
444
623
  def _run_model_loop(
@@ -449,14 +628,53 @@ def _run_model_loop(
449
628
  *,
450
629
  emitter: EventEmitter,
451
630
  max_turns: int | None,
452
- ) -> bool:
631
+ max_tokens: int,
632
+ time_budget_seconds: int | None = None,
633
+ ) -> RunOutcome:
453
634
  """Run model replies and tool calls for an already-started Agent Run."""
454
635
  turns = 0
636
+ retries = 0
637
+ retry_deadline = None
638
+ truncation_recovered = False
639
+ recovery_pending = False
640
+ deadline = (
641
+ time.monotonic() + time_budget_seconds
642
+ if time_budget_seconds is not None and time_budget_seconds > 0
643
+ else None
644
+ )
455
645
  while True:
646
+ model_call_id = f"model-{uuid.uuid4()}"
647
+ remaining = None
648
+ if deadline is not None:
649
+ remaining = deadline - time.monotonic()
650
+ if remaining <= 0:
651
+ return "time_budget_exhausted"
652
+ if recovery_pending:
653
+ messages.append({"role": "user", "content": _TRUNCATION_RECOVERY_NOTE})
654
+ emitter.emit("input.injected", {
655
+ "model_call_id": model_call_id,
656
+ "content": _TRUNCATION_RECOVERY_NOTE,
657
+ "reason": "truncation_recovery",
658
+ "source_timestamp": utc_now(),
659
+ })
660
+ recovery_pending = False
661
+ if deadline is not None or (max_turns is not None and retries == 0):
662
+ _append_budget_note(
663
+ messages,
664
+ _time_budget_note(
665
+ turn=turns + 1,
666
+ elapsed=time_budget_seconds - remaining if deadline is not None else 0,
667
+ budget=time_budget_seconds,
668
+ remaining=remaining,
669
+ max_turns=max_turns,
670
+ ),
671
+ emitter=emitter,
672
+ model_call_id=model_call_id,
673
+ reason="time_budget" if deadline is not None else "turn_budget",
674
+ )
456
675
  # A spinner marks the wait for the reply; the first streamed
457
676
  # token replaces it with the reply prefix. A tool-only reply
458
677
  # streams no text, so the prefix is skipped for it entirely.
459
- model_call_id = f"model-{uuid.uuid4()}"
460
678
  emitter.emit(
461
679
  "model.started",
462
680
  {
@@ -468,28 +686,111 @@ def _run_model_loop(
468
686
  model_started_ns = time.perf_counter_ns()
469
687
  # Stream the reply so text shows up as it is generated, then grab
470
688
  # the accumulated message for the conversation history.
471
- with Spinner() as spinner, client.messages.stream(
472
- model=model,
473
- max_tokens=MAX_TOKENS,
474
- system=system,
475
- tools=TOOLS,
476
- messages=messages,
477
- ) as stream:
478
- for text in stream.text_stream:
479
- spinner.stop()
480
- emitter.emit(
481
- "model.output_delta",
482
- {
483
- "model_call_id": model_call_id,
484
- "delta": text,
485
- "source_timestamp": utc_now(),
486
- },
487
- )
488
- message = stream.get_final_message()
489
- generation_id = _response_header(stream, "x-generation-id")
490
- model_completed_ns = time.perf_counter_ns()
689
+ generation_id = None
690
+ stream_entered = False
691
+ try:
692
+ with wall_clock_limit(remaining), Spinner() as spinner, client.messages.stream(
693
+ model=model,
694
+ max_tokens=max_tokens,
695
+ system=system,
696
+ tools=TOOLS,
697
+ messages=messages,
698
+ **({"timeout": remaining} if remaining is not None else {}),
699
+ ) as stream:
700
+ stream_entered = True
701
+ generation_id = _response_header(stream, "x-generation-id")
702
+ input_json: dict[int, list[str]] = {}
703
+ for event in stream:
704
+ if event.type == "text":
705
+ spinner.stop()
706
+ emitter.emit(
707
+ "model.output_delta",
708
+ {
709
+ "model_call_id": model_call_id,
710
+ "delta": event.text,
711
+ "source_timestamp": utc_now(),
712
+ },
713
+ )
714
+ elif (
715
+ event.type == "content_block_delta"
716
+ and event.delta.type == "input_json_delta"
717
+ ):
718
+ input_json.setdefault(event.index, []).append(
719
+ event.delta.partial_json
720
+ )
721
+ message = stream.get_final_message()
722
+ model_completed_ns = time.perf_counter_ns()
723
+ except DeadlineExceeded as exc:
724
+ emitter.emit("model.failed", {
725
+ "model_call_id": model_call_id,
726
+ "error_type": type(exc).__name__, "message": str(exc),
727
+ "generation_id": generation_id,
728
+ "duration_ms": (time.perf_counter_ns() - model_started_ns) / 1_000_000,
729
+ "will_retry": False, "retry_delay_seconds": 0,
730
+ "source_timestamp": utc_now(),
731
+ })
732
+ return "time_budget_exhausted"
733
+ except (anthropic.APIError, *HTTP_ERRORS) as exc:
734
+ now = time.monotonic()
735
+ if retry_deadline is None:
736
+ retry_deadline = now + STREAM_RETRY_WINDOW_SECONDS
737
+ delay = STREAM_RETRY_DELAYS[retries] if retries < len(STREAM_RETRY_DELAYS) else 0
738
+ retryable = (
739
+ stream_entered
740
+ and isinstance(exc, RETRYABLE_STREAM_ERRORS)
741
+ and retries < len(STREAM_RETRY_DELAYS)
742
+ and now + delay <= retry_deadline
743
+ )
744
+ will_retry = retryable and (deadline is None or now + delay < deadline)
745
+ emitter.emit(
746
+ "model.failed",
747
+ {
748
+ "model_call_id": model_call_id,
749
+ "error_type": type(exc).__name__,
750
+ "message": str(exc),
751
+ "generation_id": generation_id,
752
+ "duration_ms": (time.perf_counter_ns() - model_started_ns) / 1_000_000,
753
+ "will_retry": will_retry,
754
+ "retry_delay_seconds": delay if will_retry else 0,
755
+ "source_timestamp": utc_now(),
756
+ },
757
+ )
758
+ if not will_retry:
759
+ if deadline is not None and (now >= deadline or (retryable and now + delay >= deadline)):
760
+ return "time_budget_exhausted"
761
+ raise
762
+ # The retry delay fits inside both the recovery window and budget.
763
+ time.sleep(delay)
764
+ retries += 1
765
+ continue
766
+
767
+ retries = 0
768
+ retry_deadline = None
491
769
 
492
770
  content = _native_content_blocks(message.content)
771
+ input_errors: dict[str, str] = {}
772
+ invalid_json_ids: set[str] = set()
773
+ for index, block in enumerate(message.content):
774
+ if block.type != "tool_use":
775
+ continue
776
+ error = tool_input_error(block.name, block.input)
777
+ if index in input_json:
778
+ raw_json = "".join(input_json[index])
779
+ try:
780
+ json.loads(raw_json)
781
+ except json.JSONDecodeError:
782
+ # The SDK parses partial JSON while streaming. Even a
783
+ # complete-looking dict is not permission to execute an
784
+ # unfinished call after a provider reports tool_use.
785
+ error = (
786
+ "Invalid tool argument JSON: incomplete or malformed. "
787
+ "Resend a complete JSON object."
788
+ )
789
+ invalid_json_ids.add(block.id)
790
+ content[index]["input_json"] = raw_json
791
+ if error:
792
+ input_errors[block.id] = error
793
+ content[index]["input_error"] = error
493
794
  tool_calls = [
494
795
  item
495
796
  for item in content
@@ -510,6 +811,10 @@ def _run_model_loop(
510
811
  ),
511
812
  "generation_id": generation_id,
512
813
  "cost": usage_cost(usage if isinstance(usage, dict) else None)
814
+ or estimated_cost(
815
+ str(getattr(message, "model", None) or model),
816
+ usage if isinstance(usage, dict) else None,
817
+ )
513
818
  or pending_cost(generation_id),
514
819
  "duration_ms": (model_completed_ns - model_started_ns) / 1_000_000,
515
820
  "source_timestamp": utc_now(),
@@ -517,20 +822,66 @@ def _run_model_loop(
517
822
  emitter.emit("model.completed", payload)
518
823
 
519
824
  turns += 1
520
- messages.append({"role": "assistant", "content": message.content})
825
+ if deadline is not None and time.monotonic() >= deadline:
826
+ return "time_budget_exhausted"
827
+ if message.stop_reason == "max_tokens":
828
+ # Do not execute partial tool calls or replay them without results.
829
+ # Thinking may also be cut off before its signature arrives. Keep
830
+ # visible text and an explicit notice for a safe follow-up request.
831
+ text = "".join(
832
+ block.text for block in message.content if block.type == "text"
833
+ )
834
+ messages.append(
835
+ {
836
+ "role": "assistant",
837
+ "content": (f"{text}\n\n" if text else "") + _TRUNCATION_NOTICE,
838
+ }
839
+ )
840
+ if (
841
+ not truncation_recovered
842
+ and (max_turns is not None or time_budget_seconds is not None)
843
+ and (max_turns is None or turns < max_turns)
844
+ ):
845
+ truncation_recovered = True
846
+ recovery_pending = True
847
+ continue
848
+ return "response_truncated"
849
+ request_content = []
850
+ for block in message.content:
851
+ if block.type == "tool_use" and (
852
+ block.id in invalid_json_ids or not isinstance(block.input, dict)
853
+ ):
854
+ block = copy(block)
855
+ block.input = {}
856
+ request_content.append(block)
857
+ messages.append({"role": "assistant", "content": request_content})
521
858
  if message.stop_reason != "tool_use":
522
- return True
859
+ return "completed"
523
860
  if max_turns is not None and turns >= max_turns:
524
861
  # Stop before running the tools: their results would only be
525
862
  # useful to a reply this budget can no longer pay for.
526
- return False
863
+ return "max_turns_exhausted"
527
864
  # Every tool_use block needs a matching tool_result in the next
528
865
  # user message, or the API rejects the request.
529
- results = [
530
- _run_one_tool(block, emitter, model_call_id)
531
- for block in message.content
532
- if block.type == "tool_use"
533
- ]
866
+ results = []
867
+ for block in message.content:
868
+ if block.type != "tool_use":
869
+ continue
870
+ if deadline is not None and time.monotonic() >= deadline:
871
+ # The reply or a preceding tool consumed the remaining time.
872
+ # Stop the run without starting another tool or model call.
873
+ return "time_budget_exhausted"
874
+ remaining = None if deadline is None else deadline - time.monotonic()
875
+ try:
876
+ with wall_clock_limit(remaining):
877
+ result = _run_one_tool(
878
+ block, emitter, model_call_id,
879
+ input_error=input_errors.get(block.id),
880
+ remaining_seconds=remaining,
881
+ )
882
+ except DeadlineExceeded:
883
+ return "time_budget_exhausted"
884
+ results.append(result)
534
885
  messages.append({"role": "user", "content": results})
535
886
 
536
887
 
@@ -538,13 +889,16 @@ def _reconcile_costs(
538
889
  client: anthropic.Anthropic,
539
890
  journal: EventJournal,
540
891
  emitter: EventEmitter,
892
+ *,
893
+ max_seconds: float | None = None,
541
894
  ) -> list[JsonObject]:
542
- """Append resolved OpenRouter costs without affecting the run outcome."""
895
+ """Reconcile pending or estimated costs without affecting the run outcome."""
543
896
  base_url = getattr(client, "base_url", "")
544
897
  credential = client.api_key or client.auth_token
545
898
  if not isinstance(credential, str) or not credential:
546
899
  return []
547
900
  outcomes: list[JsonObject] = []
901
+ deadline = None if max_seconds is None else time.monotonic() + max_seconds
548
902
  entries = EventJournal.replay(journal.path)
549
903
  already_resolved = {
550
904
  str(entry.payload["generation_id"])
@@ -552,24 +906,33 @@ def _reconcile_costs(
552
906
  if entry.type == "model.cost_resolved"
553
907
  }
554
908
  for entry in entries:
555
- if entry.type != "model.completed":
909
+ if entry.type not in {"model.completed", "model.failed"}:
556
910
  continue
557
911
  generation_id = entry.payload.get("generation_id")
558
- cost = entry.payload.get("cost")
912
+ cost = (
913
+ pending_cost(generation_id)
914
+ if entry.type == "model.failed"
915
+ else entry.payload.get("cost")
916
+ )
559
917
  if (
560
918
  not isinstance(generation_id, str)
561
919
  or generation_id in already_resolved
562
920
  or not isinstance(cost, dict)
563
- or cost.get("status") != "pending"
921
+ or (cost.get("status") != "pending" and cost.get("kind") != "estimated")
564
922
  ):
565
923
  continue
566
924
  diagnostics: list[JsonObject] = []
567
- resolved = resolve_generation_cost(
568
- base_url,
569
- generation_id,
570
- credential,
571
- diagnostics=diagnostics,
572
- )
925
+ if deadline is not None and time.monotonic() >= deadline:
926
+ break
927
+ try:
928
+ with wall_clock_limit(None if deadline is None else deadline - time.monotonic()):
929
+ resolved = resolve_generation_cost(
930
+ base_url, generation_id, credential, diagnostics=diagnostics,
931
+ )
932
+ except DeadlineExceeded:
933
+ outcomes.append({"generation_id": generation_id, "status": "unresolved",
934
+ "attempts": diagnostics, "reason": "finalization_deadline"})
935
+ break
573
936
  if resolved is not None:
574
937
  resolved["source_timestamp"] = utc_now()
575
938
  emitter.emit("model.cost_resolved", resolved)
@@ -583,20 +946,22 @@ def _reconcile_costs(
583
946
  return outcomes
584
947
 
585
948
 
586
- def run() -> int:
949
+ def run(*, max_tokens: int | None = None) -> int:
587
950
  """Start the read → ask → answer loop until the user types ``/exit``.
588
951
 
589
952
  A reply may include tool calls; they are executed and their results
590
953
  fed back to the model until it finishes the turn without tool use.
591
954
  Returns the process exit code.
592
955
  """
956
+ max_tokens = resolve_max_tokens(max_tokens)
593
957
  client = _create_client()
594
958
  if client is None:
595
959
  return 1
596
960
 
597
961
  model = _resolve_model()
598
962
  print(
599
- f"nanoPyCodeAgent v{_package_version()} — model {model} "
963
+ f"nanoPyCodeAgent v{_package_version()} — model {model}, "
964
+ f"max tokens {max_tokens} "
600
965
  "(set ANTHROPIC_MODEL to override)."
601
966
  )
602
967
  print("Type a message to chat, or /exit to quit.")
@@ -618,7 +983,7 @@ def run() -> int:
618
983
  break
619
984
 
620
985
  messages.append({"role": "user", "content": user_input})
621
- _run_exchange(client, model, messages, SYSTEM_PROMPT)
986
+ _run_exchange(client, model, messages, SYSTEM_PROMPT, max_tokens=max_tokens)
622
987
 
623
988
  print("Bye!")
624
989
  return 0
@@ -628,6 +993,8 @@ def run_headless(
628
993
  task: str,
629
994
  *,
630
995
  max_turns: int = DEFAULT_MAX_TURNS,
996
+ max_tokens: int | None = None,
997
+ time_budget_seconds: int | None = None,
631
998
  trajectory_path: Path | None = None,
632
999
  ) -> int:
633
1000
  """Work ``task`` to completion without a user, and return the exit code.
@@ -640,6 +1007,7 @@ def run_headless(
640
1007
  scores the result. Only a run that could not happen at all — no
641
1008
  credentials, an API that keeps refusing — exits non-zero.
642
1009
  """
1010
+ max_tokens = resolve_max_tokens(max_tokens)
643
1011
  client = _create_client()
644
1012
  if client is None:
645
1013
  return 1
@@ -649,32 +1017,41 @@ def run_headless(
649
1017
  # model's prose and the echoed tool calls, nothing else.
650
1018
  print(
651
1019
  f"nanoPyCodeAgent v{_package_version()} — model {model}, "
652
- f"max turns {max_turns}",
1020
+ f"max turns {max_turns}, max tokens {max_tokens}, "
1021
+ f"time budget {time_budget_seconds if time_budget_seconds else 'none'}",
653
1022
  file=sys.stderr,
654
1023
  )
655
1024
 
656
1025
  messages: list[MessageParam] = [{"role": "user", "content": task}]
657
1026
  try:
658
- finished = _run_exchange(
1027
+ outcome = _run_exchange(
659
1028
  client,
660
1029
  model,
661
1030
  messages,
662
1031
  HEADLESS_SYSTEM_PROMPT,
663
1032
  max_turns=max_turns,
1033
+ max_tokens=max_tokens,
1034
+ time_budget_seconds=time_budget_seconds,
664
1035
  reply_prefix="",
665
1036
  trajectory_path=trajectory_path,
666
1037
  )
667
- except (anthropic.APIError, httpx.HTTPError) as exc:
1038
+ except (anthropic.APIError, *HTTP_ERRORS) as exc:
668
1039
  # Printed verbatim on purpose: a harness classifies a failed run by
669
1040
  # pattern-matching this text (rate limit, overloaded, context length,
670
1041
  # …) to decide whether retrying is worth anything. Rewording it, or
671
1042
  # swallowing it, throws that away.
672
1043
  print(f"API error: {exc}", file=sys.stderr)
673
1044
  return 1
674
- if not finished:
1045
+ if outcome == "max_turns_exhausted":
675
1046
  turns = "turn" if max_turns == 1 else "turns"
676
1047
  print(
677
1048
  f"[stopped after {max_turns} {turns} without finishing the task]",
678
1049
  file=sys.stderr,
679
1050
  )
1051
+ elif outcome == "time_budget_exhausted":
1052
+ print(
1053
+ f"[stopped after the {time_budget_seconds}s time budget without "
1054
+ "finishing the task]",
1055
+ file=sys.stderr,
1056
+ )
680
1057
  return 0