tether-sdk 0.2.4__tar.gz → 0.2.5__tar.gz

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 (191) hide show
  1. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/AGENTS.md +6 -5
  2. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/PKG-INFO +4 -2
  3. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/README.md +3 -1
  4. tether_sdk-0.2.5/bench/README.md +37 -0
  5. tether_sdk-0.2.5/bench/grade.py +148 -0
  6. tether_sdk-0.2.5/bench/naive_agent.py +92 -0
  7. tether_sdk-0.2.5/bench/run.py +173 -0
  8. tether_sdk-0.2.5/bench/tasks/code-hard/goal.txt +1 -0
  9. tether_sdk-0.2.5/bench/tasks/code-hard/hidden/test_hidden.py +31 -0
  10. tether_sdk-0.2.5/bench/tasks/code-hard/ref/calc/__init__.py +10 -0
  11. tether_sdk-0.2.5/bench/tasks/code-hard/ref/calc/errors.py +2 -0
  12. tether_sdk-0.2.5/bench/tasks/code-hard/ref/calc/evaluator.py +44 -0
  13. tether_sdk-0.2.5/bench/tasks/code-hard/ref/calc/parser.py +78 -0
  14. tether_sdk-0.2.5/bench/tasks/code-hard/ref/calc/tokenizer.py +24 -0
  15. tether_sdk-0.2.5/bench/tasks/code-hard/ws/calc/__init__.py +10 -0
  16. tether_sdk-0.2.5/bench/tasks/code-hard/ws/calc/errors.py +2 -0
  17. tether_sdk-0.2.5/bench/tasks/code-hard/ws/calc/evaluator.py +42 -0
  18. tether_sdk-0.2.5/bench/tasks/code-hard/ws/calc/parser.py +78 -0
  19. tether_sdk-0.2.5/bench/tasks/code-hard/ws/calc/tokenizer.py +24 -0
  20. tether_sdk-0.2.5/bench/tasks/code-hard/ws/tests/test_calc.py +24 -0
  21. tether_sdk-0.2.5/bench/tasks/code-medium/goal.txt +8 -0
  22. tether_sdk-0.2.5/bench/tasks/code-medium/hidden/test_hidden.py +51 -0
  23. tether_sdk-0.2.5/bench/tasks/code-medium/ws/cli.py +9 -0
  24. tether_sdk-0.2.5/bench/tasks/code-medium/ws/ledger/__init__.py +0 -0
  25. tether_sdk-0.2.5/bench/tasks/code-medium/ws/ledger/parser.py +14 -0
  26. tether_sdk-0.2.5/bench/tasks/code-medium/ws/ledger/report.py +10 -0
  27. tether_sdk-0.2.5/bench/tasks/code-medium/ws/sample.csv +6 -0
  28. tether_sdk-0.2.5/bench/tasks/code-medium/ws/tests/__init__.py +0 -0
  29. tether_sdk-0.2.5/bench/tasks/code-medium/ws/tests/test_report.py +15 -0
  30. tether_sdk-0.2.5/bench/tasks/code-simple/goal.txt +1 -0
  31. tether_sdk-0.2.5/bench/tasks/code-simple/hidden/test_hidden.py +14 -0
  32. tether_sdk-0.2.5/bench/tasks/code-simple/ws/tests/__init__.py +0 -0
  33. tether_sdk-0.2.5/bench/tasks/code-simple/ws/tests/test_textutils.py +20 -0
  34. tether_sdk-0.2.5/bench/tasks/code-simple/ws/textutils.py +14 -0
  35. tether_sdk-0.2.5/bench/tasks/content/goal.txt +1 -0
  36. tether_sdk-0.2.5/bench/tasks/content/ws/.keep +0 -0
  37. tether_sdk-0.2.5/bench/tasks/focus/goal.txt +1 -0
  38. tether_sdk-0.2.5/bench/tasks/focus/hidden/test_hidden.py +39 -0
  39. tether_sdk-0.2.5/bench/tasks/focus/ws/AGENTS.md +57 -0
  40. tether_sdk-0.2.5/bench/tasks/focus/ws/README.md +5 -0
  41. tether_sdk-0.2.5/bench/tasks/focus/ws/docs/architecture.md +80 -0
  42. tether_sdk-0.2.5/bench/tasks/focus/ws/docs/style.md +60 -0
  43. tether_sdk-0.2.5/bench/tasks/focus/ws/mini/__init__.py +1 -0
  44. tether_sdk-0.2.5/bench/tasks/focus/ws/mini/cli.py +23 -0
  45. tether_sdk-0.2.5/bench/tasks/focus/ws/mini/fmt.py +5 -0
  46. tether_sdk-0.2.5/bench/tasks/focus/ws/mini/stats.py +13 -0
  47. tether_sdk-0.2.5/bench/tasks/focus/ws/mini/textio.py +6 -0
  48. tether_sdk-0.2.5/bench/tasks/focus/ws/tests/__init__.py +0 -0
  49. tether_sdk-0.2.5/bench/tasks/focus/ws/tests/test_stats.py +11 -0
  50. tether_sdk-0.2.5/bench/tasks/qa/goal.txt +7 -0
  51. tether_sdk-0.2.5/bench/tasks/qa/ws/.keep +0 -0
  52. tether_sdk-0.2.5/bench/tasks/review/goal.txt +1 -0
  53. tether_sdk-0.2.5/bench/tasks/review/ws/paper.md +13 -0
  54. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/architecture.md +1 -1
  55. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/extending.md +13 -0
  56. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/reference/agent-interface.md +5 -3
  57. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/reference/context-and-store.md +1 -1
  58. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/reference/providers.md +34 -1
  59. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/release-notes.md +33 -0
  60. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/testing.md +9 -0
  61. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/troubleshooting.md +2 -0
  62. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/tutorial/cli-and-headless.md +6 -2
  63. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/tutorial/security-and-sandbox.md +1 -1
  64. tether_sdk-0.2.5/e2e/__init__.py +0 -0
  65. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/e2e/test_limits.py +27 -3
  66. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/e2e/test_quirks.py +29 -4
  67. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/e2e/test_sandbox.py +12 -0
  68. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/e2e/test_surface.py +7 -0
  69. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/pyproject.toml +1 -0
  70. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/golden/done_nudge.snap.json +5 -5
  71. tether_sdk-0.2.5/tests/golden/shell_wrappers.json +29 -0
  72. tether_sdk-0.2.5/tests/golden/shell_wrappers.snap.json +105 -0
  73. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/providers/test_base.py +24 -0
  74. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/providers/test_declarative.py +20 -0
  75. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/providers/test_retry.py +53 -0
  76. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_agent_interface.py +33 -0
  77. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_cli.py +22 -0
  78. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_context.py +56 -0
  79. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_context_config.py +1 -1
  80. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_edit_tool.py +108 -0
  81. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_harness.py +78 -1
  82. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_multiplexer.py +52 -0
  83. tether_sdk-0.2.5/tests/test_params.py +127 -0
  84. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_release_hardening.py +5 -2
  85. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_sandbox.py +52 -0
  86. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_tether.py +1 -1
  87. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/__init__.py +3 -1
  88. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/api.py +6 -0
  89. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/cli.py +36 -1
  90. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/context.py +35 -3
  91. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/harness.py +101 -5
  92. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/mcp.py +5 -0
  93. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/multiplexer.py +81 -12
  94. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/providers/__init__.py +8 -5
  95. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/providers/anthropic.py +9 -2
  96. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/providers/base.py +112 -0
  97. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/providers/declarative.py +14 -3
  98. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/providers/ollama.py +16 -11
  99. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/providers/openai.py +9 -3
  100. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/sandbox.py +30 -0
  101. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/tools/edit.py +128 -0
  102. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/.claude/feature-context/active/.gitkeep +0 -0
  103. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/.claude/feature-context/active/v0-2-bugs.md +0 -0
  104. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/.claude/feature-context/archive/.gitkeep +0 -0
  105. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/.github/workflows/ci.yml +0 -0
  106. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/.github/workflows/delivery.yml +0 -0
  107. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/.github/workflows/docs.yml +0 -0
  108. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/.gitignore +0 -0
  109. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/LICENSE +0 -0
  110. {tether_sdk-0.2.4/e2e → tether_sdk-0.2.5/bench/tasks/code-hard/ws/tests}/__init__.py +0 -0
  111. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/benchmarks.md +0 -0
  112. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/index.md +0 -0
  113. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/javascripts/mathjax.js +0 -0
  114. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/reference/harness.md +0 -0
  115. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/reference/index.md +0 -0
  116. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/reference/multiplexer-and-decorator.md +0 -0
  117. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/reference/sandbox-and-skills.md +0 -0
  118. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/reference/tools.md +0 -0
  119. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/releasing.md +0 -0
  120. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/tutorial/agent-interface.md +0 -0
  121. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/tutorial/built-in-tools.md +0 -0
  122. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/tutorial/index.md +0 -0
  123. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/tutorial/multi-agent.md +0 -0
  124. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/tutorial/sdk-and-custom-tools.md +0 -0
  125. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/tutorial/skills.md +0 -0
  126. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/docs/tutorial/workflows-and-telemetry.md +0 -0
  127. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/e2e/conftest.py +0 -0
  128. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/e2e/proxy.py +0 -0
  129. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/e2e/test_agents.py +0 -0
  130. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/e2e/test_defaults.py +0 -0
  131. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/e2e/test_faults.py +0 -0
  132. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/e2e/test_lifecycle.py +0 -0
  133. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/examples/course/README.md +0 -0
  134. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/examples/course/checks.py +0 -0
  135. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/examples/course/course.yaml +0 -0
  136. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/examples/course/ruff.toml +0 -0
  137. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/examples/course/skills/planner/SKILL.md +0 -0
  138. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/examples/course/skills/searcher/SKILL.md +0 -0
  139. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/examples/course/skills/searcher/tools.py +0 -0
  140. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/examples/course/skills/writer/SKILL.md +0 -0
  141. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/examples/course/skills/writer/tools.py +0 -0
  142. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/mkdocs.yml +0 -0
  143. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/scripts/record_golden.py +0 -0
  144. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/skills/researcher/SKILL.md +0 -0
  145. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/__init__.py +0 -0
  146. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/conftest.py +0 -0
  147. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/fixtures/dialects.jsonl +0 -0
  148. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/golden/coding_edit_failure_modes.json +0 -0
  149. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/golden/coding_edit_failure_modes.snap.json +0 -0
  150. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/golden/done_nudge.json +0 -0
  151. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/golden/read_range_pingpong.json +0 -0
  152. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/golden/read_range_pingpong.snap.json +0 -0
  153. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/golden/research_web.json +0 -0
  154. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/golden/research_web.snap.json +0 -0
  155. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/golden/waiting_input_resume.json +0 -0
  156. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/golden/waiting_input_resume.snap.json +0 -0
  157. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/providers/__init__.py +0 -0
  158. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/providers/test_anthropic.py +0 -0
  159. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/providers/test_dialects.py +0 -0
  160. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/providers/test_ollama.py +0 -0
  161. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/providers/test_openai.py +0 -0
  162. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_decorator.py +0 -0
  163. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_golden.py +0 -0
  164. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_integration.py +0 -0
  165. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_misses.py +0 -0
  166. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_pipeline.py +0 -0
  167. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_retro.py +0 -0
  168. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_security_hardening.py +0 -0
  169. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_skills.py +0 -0
  170. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_store.py +0 -0
  171. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/test_structured_history.py +0 -0
  172. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/tools/__init__.py +0 -0
  173. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/tools/test_agent.py +0 -0
  174. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/tools/test_bash.py +0 -0
  175. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/tools/test_done.py +0 -0
  176. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/tools/test_edit.py +0 -0
  177. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/tools/test_mem.py +0 -0
  178. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tests/tools/test_web.py +0 -0
  179. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/decorator.py +0 -0
  180. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/pipeline.py +0 -0
  181. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/retro.py +0 -0
  182. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/schema.py +0 -0
  183. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/skills.py +0 -0
  184. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/store.py +0 -0
  185. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/tools/__init__.py +0 -0
  186. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/tools/agent.py +0 -0
  187. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/tools/bash.py +0 -0
  188. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/tools/done.py +0 -0
  189. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/tools/mem.py +0 -0
  190. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/tether/tools/web.py +0 -0
  191. {tether_sdk-0.2.4 → tether_sdk-0.2.5}/uv.lock +0 -0
@@ -45,7 +45,7 @@ Reviewers and the Team Leader cite the failing line when they reject a change.
45
45
  - Sessions do **not** terminate simply because the model emitted a text response without a tool call (small 9B models frequently "think out loud" before acting).
46
46
  - A task only completes when the agent explicitly calls `act("done", stdin="<final deliverable>")` (or `act("done '<short answer>'")`), pauses for human/parent input via `act("done --ask", stdin="<question>")` (transitioning the session to `WAITING_INPUT` and releasing the worker process until resumed via `send`), or hits `max_steps`.
47
47
  - If the model emits plain text without calling `act`, the harness appends a brief deterministic nudge reminding it to either execute a command or call `done`.
48
- - After 6 consecutive read-only/verification steps following a change, the harness appends a one-shot `[NUDGE]` to that step's observation reminding the model to call `done` if the task is complete (0 static prompt tokens, #74).
48
+ - After 6 consecutive read-only/verification steps following a change, the harness appends a one-shot `[NUDGE]` to that step's observation reminding the model to call `done` if the task is complete (0 static prompt tokens, #74). Seven reads of one file in a row with no change are a `cycle_stall`, and 4 stall warnings without a change end the session `FAILED` as `Stalled` (#92); `tether stop <id>` terminates a detached worker (#89).
49
49
  - When `verify` gate commands are configured (via `Harness(verify=[...])`, CLI `--verify`, or Skill YAML `verify: [...]`), `Harness.execute_session` deterministically executes each command inside the session's `SandboxPolicy` before allowing `done` to transition to `COMPLETED` (consuming 0 static prompt tokens until a gate fails). A gate that errors instead of failing (sandbox violation, exit 124/126/127) ends the session `FAILED` at once as `gate_error` ("gate misconfigured"), without counting toward the consecutive-failure abort.
50
50
 
51
51
  ### Rule 4: Progressive `--help` (JIT Schema Disclosure)
@@ -62,7 +62,7 @@ Reviewers and the Team Leader cite the failing line when they reject a change.
62
62
  ```text
63
63
  [obs_3 folded: `web fetch https://...` (3,420 chars) | use `mem recall obs_3` to expand]
64
64
  ```
65
- - Exception: the latest read of each of the last 8 files (`edit view <p>`, `bash cat/head/tail/sed -n <p>`; paths normalized against the workspace) is not folded until `<p>` is edited (`edit write|replace`, or any other bash command naming it: `sed -i`, `tee`, redirects, `python -c`) or re-read. The 2,400-char head+tail elision still applies, and the hard context budget remains #81. The `mem recall` hint is shown only when `mem` is enabled (else "re-run the command").
65
+ - Exception: the latest read of each of the last 8 files (`edit view <p>`, `bash cat/head/tail/sed -n <p>`; paths normalized against the workspace) is not folded until `<p>` is edited (`edit write|replace`, or any other bash command naming it: `sed -i`, `tee`, redirects, `python -c`) or re-read. The 2,400-char head+tail elision still applies, and under `max_context_tokens` pressure it is folded like any other (oldest first). The `mem recall` hint is shown only when `mem` is enabled (else "re-run the command").
66
66
  - History is replayed as structured `tool_calls` + `tool` results (providers with `structured_history = True`; textual `act('...')` form only as fallback), with `stdin` replayed as a real 400-char prefix, never a `<N chars>` placeholder. A call and its result are trimmed together.
67
67
 
68
68
  ### Rule 6: Deterministic Security Envelope (Never Trust the LLM for Safety)
@@ -71,7 +71,7 @@ Reviewers and the Team Leader cite the failing line when they reject a change.
71
71
  - All `edit` and `bash` paths are canonicalized (`Path.resolve()`) and confined to `workspace_root`.
72
72
  - Sensitive files/directories (`.env*`, `.git/config`, `.git/hooks`, `~/.ssh`, `.tether/`) are deterministically protected from mutation or read exfiltration.
73
73
  - `bash` subprocesses get an allowlisted environment only (secrets with any name are dropped; opt-in via `TETHER_ENV_PASSTHROUGH`). `web fetch` blocks loopback/private/metadata addresses (SSRF guard). `SandboxPolicy(network=False)` / `--no-network` adds `--unshare-net` (fails closed without `bwrap`; children can only narrow it).
74
- - On Linux, `bash` automatically uses **`bwrap` (Bubblewrap) / `unshare`** when available (read-only `/`, hidden `/home` and `/var/tmp` tmpfs, `/run` unix sockets such as `docker.sock` masked, read-write bind on `workspace_root` with secret-looking files at any depth (`.env*`, `*.pem`, `*.key`, ...), `.tether/`, `.git/config` and `.git/hooks` masked at the mount level, `PR_SET_NO_NEW_PRIVS`), falling back to a strict deterministic command allowlist/denylist (`rm -rf /`, `sudo`, `dd`, `mkfs`, `chmod 777`, etc. blocked).
74
+ - On Linux, `bash` automatically uses **`bwrap` (Bubblewrap) / `unshare`** when available (read-only `/`, hidden `/home` and `/var/tmp` tmpfs (existing `PATH` dirs under them, e.g. `~/.local/bin`, are re-bound read-only so `uv`/`node` still run, #76), `/run` unix sockets such as `docker.sock` masked, read-write bind on `workspace_root` with secret-looking files at any depth (`.env*`, `*.pem`, `*.key`, ...), `.tether/`, `.git/config` and `.git/hooks` masked at the mount level, `PR_SET_NO_NEW_PRIVS`), falling back to a strict deterministic command allowlist/denylist (`rm -rf /`, `sudo`, `dd`, `mkfs`, `chmod 777`, etc. blocked).
75
75
  - Sub-agents spawned via `agent spawn` strictly inherit or narrow their parent session's `SandboxPolicy` (no privilege escalation).
76
76
 
77
77
  ### Rule 7: Zero Framework Bloat
@@ -85,7 +85,7 @@ Reviewers and the Team Leader cite the failing line when they reject a change.
85
85
  ```text
86
86
  tether/
87
87
  ├── __init__.py # Public SDK exports: Harness, Pipeline, Session, Skill, SandboxPolicy, tool
88
- ├── cli.py # Headless-capable CLI: `tether run|pipeline|status|read|query|send|list|wait|stats|retro|events|misses|mcp` (`--json` + documented exit codes)
88
+ ├── cli.py # Headless-capable CLI: `tether run|pipeline|status|read|query|send|list|wait|stop|stats|retro|events|misses|mcp` (`--json` + documented exit codes)
89
89
  ├── harness.py # Control Plane: bounded agent loop, pipelines, SQLite inbox, worker spawn
90
90
  ├── pipeline.py # Workflow Plane: declarative multi-stage YAML pipelines & model routing
91
91
  ├── api.py # Agent-facing JSON session view, exit codes, events (`--json`)
@@ -166,6 +166,7 @@ tether/
166
166
  - If no provider prefix is given, defaults to `ollama/<model>`.
167
167
  - Custom SDK transports (e.g., internal corporate gateways, custom local runners, or test harnesses) can be injected via `Harness(provider=...)` or registered under a custom `<prefix>/<model>` via `register_provider(prefix, factory)`.
168
168
  - Declarative providers: `~/.tether/providers.yaml` (override with `TETHER_PROVIDERS`, never read from the workspace) maps a model-id prefix to a `kind` (`openai`, `ollama`, `anthropic` or `command`); `claude-cli/sonnet` uses the entry `claude-cli`. The `command` kind runs `argv` directly (never through a shell) with `{model}`, `{system}` and `{conversation}` placeholders, and reads the reply and usage from JSON paths. Built-in prefixes (`ollama`, `openai`, `anthropic`, `claude`) cannot be shadowed, keys are env var names (never values), and an invalid file raises `ValueError: providers.yaml: ...`. Implementation in `tether/providers/declarative.py`; docs in `docs/reference/providers.md`.
169
+ - `providers.yaml` entries may set `params` (request-body parameters for HTTP kinds, overridable per call via `--param`, `Harness(params=)`, MCP `params`, stored in `sandbox_json`, #112) and `rpm` (requests per minute cap for HTTP kinds, sliding window shared across processes via a lock file, #110).
169
170
  - Environment variables:
170
171
  - `OLLAMA_HOST` (default `http://localhost:11434`); `TETHER_OLLAMA_FALLBACK=1` opts in to substituting an installed model when the requested one 404s (default: fail loudly with the installed list)
171
172
  - `OPENAI_API_KEY`, `OPENAI_BASE_URL` (default `https://api.openai.com/v1` — works with OpenRouter, vLLM, Groq, etc.)
@@ -204,7 +205,7 @@ uv run mypy tether/
204
205
  2. **Async-First Design:**
205
206
  - All model calls and I/O-bound tool executions must be `async`/`await` native, while seamlessly wrapping synchronous user `@tool` functions.
206
207
  3. **Graceful Degradation on 9B Hallucinations:**
207
- - Small models occasionally emit `cmd` with minor quirks (e.g., leading `$`, wrapping backticks, or calling a tool name directly instead of `act`). The multiplexer must normalize trivial syntax quirks deterministically before failing. This includes unescaping literal `\n`/`\t` in one-line `stdin` for `edit write`/`edit replace` and `done` (never `bash`), and turning a trailing shell heredoc in `cmd` (`edit write f <<'EOF' ... EOF`) into `stdin` (never for `bash`).
208
+ - Small models occasionally emit `cmd` with minor quirks (e.g., leading `$`, wrapping backticks, or calling a tool name directly instead of `act`). The multiplexer must normalize trivial syntax quirks deterministically before failing. This includes unescaping literal `\n`/`\t` in one-line `stdin` for `edit write`/`edit replace` and `done` (never `bash`), turning a trailing shell heredoc in `cmd` (`edit write f <<'EOF' ... EOF`) into `stdin` (never for `bash`), unwrapping `bash -c/-lc '<cmd>'` and `sh -c` wrappers, running an unknown first word through the enabled `bash` tool (never for disabled built-ins), registering extra quirk fixers with `register_normalizer`, mapping a native tool call named other than `act` to `<name> --k 'v'` so the JIT usage answers it, inferring the `edit` verb (`edit <path>` -> view/replace/write) and accepting `apply_patch` (`*** Begin Patch` or unified-diff patches, also when a diff arrives as `edit <path>` stdin) as an `edit` verb.
208
209
  4. **Golden traces:** behaviour the model sees (framing, folding, nudges, tool output) is locked by `tests/golden/*.snap.json`. A PR that changes it runs `UPDATE_GOLDEN=1 pytest tests/test_golden.py` and the snapshot diff is part of the review; unrelated traces must not change. See `docs/testing.md`.
209
210
  5. **E2E scenarios:** every feature or bug fix ships with a scenario in `e2e/` (real CLI, real ollama behind a fault-injecting proxy, local only, `TETHER_E2E=1 uv run pytest e2e`). Assert on what tether sends and records, never on the model's skill; script the reply or inject the fault so the test does not depend on model potency. **Before merging any PR, run `TETHER_E2E=1 uv run pytest e2e` locally and put the result in the PR description (CI cannot run it). Every failure must be mitigated before merge: fix the code, or fix a wrong scenario, or record in the PR why it is acceptable and what follows up. A PR is not merged with an unexplained red scenario.** See `docs/testing.md`.
210
211
  6. **Documentation Integrity:**
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: tether-sdk
3
- Version: 0.2.4
3
+ Version: 0.2.5
4
4
  Summary: General-purpose, headless-first LLM-Native micro-harness for small language models
5
5
  Project-URL: Homepage, https://github.com/igormcsouza/tether
6
6
  Project-URL: Repository, https://github.com/igormcsouza/tether
@@ -265,8 +265,10 @@ $ tether stats
265
265
  # 7. Post-mortem: distill friction into <=2 short rules (diff; --apply writes ## Learned Rules)
266
266
  $ tether retro ses_8f92a1 [--apply]
267
267
 
268
- # 8. Call Tether from another agent: JSON output, exit codes (0 ok, 2 needs input, 3 gate, 4 max steps, 5 error)
268
+ # 8. Call Tether from another agent: JSON output, exit codes (0 ok, 2 needs input, 3 gate, 4 max steps or stalled, 5 error)
269
269
  $ tether run --json --output-schema out.json "goal"
270
+ $ tether stop ses_8f92a1 # terminate a running detached session
271
+ $ tether run --param temperature=0 --param think=false "goal" # per-call model parameters
270
272
  $ claude mcp add tether -- tether mcp --workspace "$PWD" # MCP server (needs: pip install "tether-sdk[mcp]")
271
273
  ```
272
274
 
@@ -244,8 +244,10 @@ $ tether stats
244
244
  # 7. Post-mortem: distill friction into <=2 short rules (diff; --apply writes ## Learned Rules)
245
245
  $ tether retro ses_8f92a1 [--apply]
246
246
 
247
- # 8. Call Tether from another agent: JSON output, exit codes (0 ok, 2 needs input, 3 gate, 4 max steps, 5 error)
247
+ # 8. Call Tether from another agent: JSON output, exit codes (0 ok, 2 needs input, 3 gate, 4 max steps or stalled, 5 error)
248
248
  $ tether run --json --output-schema out.json "goal"
249
+ $ tether stop ses_8f92a1 # terminate a running detached session
250
+ $ tether run --param temperature=0 --param think=false "goal" # per-call model parameters
249
251
  $ claude mcp add tether -- tether mcp --workspace "$PWD" # MCP server (needs: pip install "tether-sdk[mcp]")
250
252
  ```
251
253
 
@@ -0,0 +1,37 @@
1
+ # bench: model-in-the-loop checks (developers only)
2
+
3
+ Not part of the `tether` package, not run in CI. Use it to onboard a new model or to check a
4
+ release for regressions that deterministic tests cannot see (unit, golden and e2e tests stay the
5
+ gate; see `docs/testing.md`).
6
+
7
+ Seven tasks in `tasks/<name>/` (workspace in `ws/`, goal in `goal.txt`, hidden tests in `hidden/`):
8
+ `focus` (one exact edit in a distractor-heavy repo, scope-checked), `code-simple`, `code-medium`, `code-hard` (graded by hidden unit tests; editing the visible tests
9
+ scores 0), `qa`, `content`, `review` (graded by constraint counts and keyword checks, so they are
10
+ a smoke test for quality, not a judge).
11
+
12
+ Three runners, so a gap can be attributed:
13
+
14
+ | runner | what it is |
15
+ |---|---|
16
+ | `tether` | the CLI under test (`--tether-bin` picks a version or a venv) |
17
+ | `naive` | `naive_agent.py`, a plain OpenAI-compatible tool loop (bash/read/write) with the same model |
18
+ | `claude` | Claude Code in print mode, as a frontier baseline (`--models cc/sonnet`) |
19
+
20
+ ```bash
21
+ export NVIDIA_API_KEY=... # only for nvidia/* models; OLLAMA_HOST defaults to :11435
22
+ uv run python bench/run.py --runners tether,naive --models ollama/qwen3.5:9b \
23
+ --tasks code-simple,qa --trials 2 --out /tmp/bench
24
+ uv run python bench/run.py --runners tether --tether-bin /path/to/venv/bin/tether \
25
+ --models ollama/qwen3.5:9b --param think=false --out /tmp/bench-v0.2.3
26
+ ```
27
+
28
+ Each run lands in `<out>/<runner>__<model>__<task>__t<k>/` with the workspace, stdout, the
29
+ session DB (`t.db`) and `done.json`; `results.jsonl` collects them. Re-running skips finished
30
+ cells; `--redo-infra` reruns cells that failed on provider errors (429, 503, timeouts).
31
+
32
+ Read results with the friction events (`syntax_error`, `loop_stall`, `nudge`, ...) next to the
33
+ score: a low score with many events is a harness problem, a low score with none is the model.
34
+ Rate limits (NVIDIA: 40 requests/min) invalidate results silently; set `rpm:` in `providers.yaml`
35
+ and keep parallelism low (`--par nvidia=2`).
36
+
37
+ Caveats: one run per cell is noisy (about 0.1); the scores are regex and hidden-test based.
@@ -0,0 +1,148 @@
1
+ """Deterministic graders. grade(task, ws, result_text) -> {"score": 0..1, "pass": bool, "detail": {...}}"""
2
+ import ast
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+
12
+ HERE = os.path.dirname(os.path.abspath(__file__))
13
+ TASKS = os.path.join(HERE, "tasks")
14
+
15
+
16
+ def _tree_hash(path):
17
+ h = hashlib.sha256()
18
+ for root, _, files in sorted(os.walk(path)):
19
+ for f in sorted(files):
20
+ if f.endswith(".pyc"):
21
+ continue
22
+ p = os.path.join(root, f)
23
+ h.update(os.path.relpath(p, path).encode())
24
+ h.update(open(p, "rb").read())
25
+ return h.hexdigest()
26
+
27
+
28
+ def _code(task, ws, _result):
29
+ tmp = tempfile.mkdtemp(prefix="g_")
30
+ try:
31
+ shutil.copytree(ws, tmp, dirs_exist_ok=True)
32
+ orig_tests = os.path.join(TASKS, task, "ws", "tests")
33
+ tampered = os.path.isdir(orig_tests) and _tree_hash(orig_tests) != _tree_hash(os.path.join(ws, "tests"))
34
+ shutil.copy(os.path.join(TASKS, task, "hidden", "test_hidden.py"), os.path.join(tmp, "_hidden_test.py"))
35
+ try:
36
+ p = subprocess.run([sys.executable, "-m", "unittest", "-v", "_hidden_test"], cwd=tmp, capture_output=True,
37
+ text=True, timeout=90)
38
+ out = p.stderr + p.stdout
39
+ except subprocess.TimeoutExpired:
40
+ return {"score": 0.0, "pass": False, "detail": {"error": "hidden tests timed out"}}
41
+ ok = len(re.findall(r"\.\.\. ok$", out, re.M))
42
+ bad = len(re.findall(r"\.\.\. (FAIL|ERROR)$", out, re.M))
43
+ total = ok + bad
44
+ score = ok / total if total else 0.0
45
+ if tampered:
46
+ return {"score": 0.0, "pass": False, "detail": {"tampered_tests": True, "hidden_ok": ok, "hidden_total": total}}
47
+ return {"score": round(score, 3), "pass": total > 0 and bad == 0, "detail": {"hidden_ok": ok, "hidden_total": total}}
48
+ finally:
49
+ shutil.rmtree(tmp, ignore_errors=True)
50
+
51
+
52
+ def _json_array(text):
53
+ m = re.search(r"\[.*\]", text or "", re.S)
54
+ if not m:
55
+ return None
56
+ for parse in (json.loads, ast.literal_eval):
57
+ try:
58
+ v = parse(m.group(0))
59
+ return v if isinstance(v, list) else None
60
+ except (ValueError, SyntaxError):
61
+ pass
62
+ return None
63
+
64
+
65
+ def _qa(_task, _ws, result):
66
+ arr = _json_array(result)
67
+ checks = [
68
+ lambda a: "17:25" in a,
69
+ lambda a: re.search(r"\b391(\.0+)?\b", a) is not None,
70
+ lambda a: "canberra" in a.lower(),
71
+ lambda a: re.sub(r"\s", "", a) == "[1,3]",
72
+ lambda a: re.search(r"\b(10|ten)\b", a.lower()) is not None,
73
+ lambda a: ("1024" in a or "2**10" in a.replace(" ", "") or "2^10" in a.replace(" ", "")) and re.search(r"\b24\b", a) is not None,
74
+ ]
75
+ if arr is None or len(arr) != 6:
76
+ return {"score": 0.0, "pass": False, "detail": {"error": "not a JSON array of 6"}}
77
+ got = [bool(c(str(a))) for c, a in zip(checks, arr)]
78
+ return {"score": round(sum(got) / 6, 3), "pass": all(got), "detail": {"correct": got}}
79
+
80
+
81
+ def _content(_task, _ws, result):
82
+ t = (result or "").strip()
83
+ words = len(re.findall(r"\S+", t))
84
+ lines = [ln for ln in t.splitlines() if ln.strip()]
85
+ sentences = re.split(r"(?<=[.?])\s+", t.replace("\n", " "))
86
+ last = sentences[-1] if sentences else ""
87
+ c = {
88
+ "<=120 words": words <= 120 and words > 0,
89
+ "3 bullets": sum(1 for ln in lines if ln.startswith("- ")) == 3,
90
+ "snapshot": "snapshot" in t.lower(),
91
+ "rollback": "rollback" in t.lower(),
92
+ "CTA last": "tidepool.dev" in last.lower(),
93
+ "no !": "!" not in t,
94
+ "no banned": not re.search(r"revolutionary|game-changing", t, re.I),
95
+ }
96
+ return {"score": round(sum(c.values()) / len(c), 3), "pass": all(c.values()), "detail": {"checks": c, "words": words}}
97
+
98
+
99
+ FLAWS = {
100
+ "selection/no-randomisation": r"random|self-select|selection bias|volunteer|chose to install|non-?random|assign",
101
+ "causal-overreach": r"causal|causation|\bcause|correlat|overreach|overstat",
102
+ "tiny-sample/generalise": r"small sample|sample size|n\s*=\s*1[12]|23 (student|participant)|under-?power|low power|generali[sz]|single (university|course)|one (course|university)",
103
+ "multiple-comparisons": r"multiple (comparison|testing|outcome|test)|bonferroni|family-?wise|false[- ]positive|correction|cherry|selective",
104
+ "number-inconsistency": r"inconsisten|discrepan|mismatch|contradict|12\.4.{0,80}(8\.1|7\.2)|(8\.1|7\.2).{0,80}12\.4",
105
+ "baseline-gpa-imbalance": r"gpa|baseline|prior (performance|achievement|ability)|confound|not matched|unmatched|equivalen",
106
+ "unblinded-grader": r"blind|grader|grading|instructor|assessor|rater",
107
+ "no-effect-size/CI": r"effect size|confidence interval|\bCIs?\b|cohen",
108
+ }
109
+
110
+
111
+ def _review(_task, _ws, result):
112
+ t = result or ""
113
+ hit = {k: bool(re.search(v, t, re.I)) for k, v in FLAWS.items()}
114
+ n = len(re.findall(r"^\s*\d+[.)]", t, re.M))
115
+ return {"score": round(sum(hit.values()) / len(hit), 3), "pass": sum(hit.values()) >= 6,
116
+ "detail": {"found": [k for k, v in hit.items() if v], "missed": [k for k, v in hit.items() if not v], "items": n}}
117
+
118
+
119
+ def _focus(task, ws, result):
120
+ """_code + scope: the goal allows editing mini/cli.py only; other changes halve the score."""
121
+ r = _code(task, ws, result)
122
+ orig = os.path.join(TASKS, task, "ws")
123
+ touched = []
124
+ for root, dirs, files in os.walk(orig):
125
+ for f in files:
126
+ rel = os.path.relpath(os.path.join(root, f), orig)
127
+ p = os.path.join(ws, rel)
128
+ if rel != os.path.join("mini", "cli.py") and (
129
+ not os.path.exists(p) or open(p, "rb").read() != open(os.path.join(root, f), "rb").read()
130
+ ):
131
+ touched.append(rel)
132
+ r["detail"]["touched_other"] = touched
133
+ if touched:
134
+ r["score"], r["pass"] = round(r["score"] / 2, 3), False
135
+ return r
136
+
137
+
138
+ def grade(task, ws, result):
139
+ fn = {"qa": _qa, "content": _content, "review": _review, "focus": _focus}.get(task, _code)
140
+ try:
141
+ return fn(task, ws, result)
142
+ except Exception as e: # grader bug must never look like a model result
143
+ return {"score": 0.0, "pass": False, "detail": {"grader_error": repr(e)}}
144
+
145
+
146
+ if __name__ == "__main__":
147
+ task, ws, rf = sys.argv[1:4]
148
+ print(json.dumps(grade(task, ws, open(rf).read() if os.path.exists(rf) else "")))
@@ -0,0 +1,92 @@
1
+ """Control harness: plain OpenAI-compatible tool loop (bash/read_file/write_file), append-only history,
2
+ stop when the model answers without a tool call. Same model, different harness => isolates tether's effect."""
3
+ import argparse
4
+ import json
5
+ import os
6
+ import subprocess
7
+ import time
8
+
9
+ import httpx
10
+
11
+ TOOLS = [
12
+ {"type": "function", "function": {"name": "bash", "description": "Run a shell command in the workspace.",
13
+ "parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}},
14
+ {"type": "function", "function": {"name": "read_file", "description": "Read a text file.",
15
+ "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
16
+ {"type": "function", "function": {"name": "write_file", "description": "Create or overwrite a file.",
17
+ "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
18
+ "required": ["path", "content"]}}},
19
+ ]
20
+ SYSTEM = ("You are a capable assistant working in a project directory with tools. Use the tools to do the task. "
21
+ "When finished, reply with a plain-text final answer and no tool call.")
22
+
23
+
24
+ def run_tool(name, args, ws):
25
+ try:
26
+ if name == "bash":
27
+ p = subprocess.run(args["command"], shell=True, cwd=ws, capture_output=True, text=True, timeout=60)
28
+ return (p.stdout + p.stderr)[-10000:] or f"(exit {p.returncode})"
29
+ if name == "read_file":
30
+ return open(os.path.join(ws, args["path"])).read()[:20000]
31
+ if name == "write_file":
32
+ p = os.path.join(ws, args["path"])
33
+ os.makedirs(os.path.dirname(p) or ws, exist_ok=True)
34
+ open(p, "w").write(args["content"])
35
+ return "ok"
36
+ return f"unknown tool {name}"
37
+ except Exception as e:
38
+ return f"error: {e}"
39
+
40
+
41
+ def main():
42
+ ap = argparse.ArgumentParser()
43
+ ap.add_argument("--base-url", required=True)
44
+ ap.add_argument("--model", required=True)
45
+ ap.add_argument("--key-env", default="")
46
+ ap.add_argument("--ws", required=True)
47
+ ap.add_argument("--goal", required=True)
48
+ ap.add_argument("--max-turns", type=int, default=40)
49
+ ap.add_argument("--result-file", required=True)
50
+ ap.add_argument("--stats-file", required=True)
51
+ a = ap.parse_args()
52
+ hdr = {"Authorization": f"Bearer {os.environ.get(a.key_env, 'x')}"}
53
+ msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": a.goal}]
54
+ pt = ct = turns = 0
55
+ peak = 0
56
+ final, status = "", "max_turns"
57
+ t0 = time.time()
58
+ with httpx.Client(timeout=300) as c:
59
+ for turns in range(1, a.max_turns + 1):
60
+ for attempt in range(4):
61
+ r = c.post(f"{a.base_url}/chat/completions", headers=hdr,
62
+ json={"model": a.model, "messages": msgs, "tools": TOOLS, "temperature": 0.2})
63
+ if r.status_code in (429, 500, 502, 503, 504) and attempt < 3:
64
+ time.sleep(2 * (attempt + 1))
65
+ continue
66
+ break
67
+ if r.status_code != 200:
68
+ status, final = "http_error", f"HTTP {r.status_code}: {r.text[:300]}"
69
+ break
70
+ d = r.json()
71
+ u = d.get("usage") or {}
72
+ pt += u.get("prompt_tokens", 0)
73
+ ct += u.get("completion_tokens", 0)
74
+ peak = max(peak, u.get("prompt_tokens", 0))
75
+ m = d["choices"][0]["message"]
76
+ msgs.append({k: v for k, v in m.items() if k in ("role", "content", "tool_calls") and v is not None})
77
+ if not m.get("tool_calls"):
78
+ final, status = m.get("content") or "", "completed"
79
+ break
80
+ for tc in m["tool_calls"]:
81
+ try:
82
+ args = json.loads(tc["function"]["arguments"] or "{}")
83
+ except ValueError:
84
+ args = {}
85
+ msgs.append({"role": "tool", "tool_call_id": tc["id"], "content": run_tool(tc["function"]["name"], args, a.ws)})
86
+ open(a.result_file, "w").write(final)
87
+ json.dump({"status": status, "steps": turns, "prompt_tokens": pt, "completion_tokens": ct, "peak_tokens": peak,
88
+ "wall_s": round(time.time() - t0, 1)}, open(a.stats_file, "w"))
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
@@ -0,0 +1,173 @@
1
+ """Benchmark runner. Matrix = runners x models x tasks x trials. Results appended to <out>/results.jsonl.
2
+
3
+ runners: tether (CLI under test; --tether-bin selects a version), naive (control loop), claude (Claude Code baseline).
4
+ """
5
+ import argparse
6
+ import asyncio
7
+ import json
8
+ import os
9
+ import re
10
+ import shutil
11
+ import signal
12
+ import sqlite3
13
+ import sys
14
+ import time
15
+
16
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
17
+ import grade # noqa: E402
18
+
19
+ HERE = os.path.dirname(os.path.abspath(__file__))
20
+ TASK_CFG = { # tether tools / step cap / wall timeout
21
+ "code-simple": ("edit,bash", 30, 600), "code-medium": ("edit,bash", 40, 900), "code-hard": ("edit,bash", 50, 1200),
22
+ "focus": ("edit,bash,mem", 30, 600),
23
+ "qa": ("", 10, 300), "content": ("", 10, 300), "review": ("edit", 15, 420),
24
+ }
25
+
26
+
27
+ def group(model):
28
+ return "nvidia" if model.startswith("openai/") else "ollama" if model.startswith("ollama/") else "claude" if model.startswith(("claude", "cc/")) else "nvidia"
29
+
30
+
31
+ _HELP = {}
32
+
33
+
34
+ def flags(tether_bin):
35
+ if tether_bin not in _HELP:
36
+ import subprocess
37
+ _HELP[tether_bin] = subprocess.run([tether_bin, "run", "--help"], capture_output=True, text=True).stdout
38
+ return _HELP[tether_bin]
39
+
40
+
41
+ def build_cmd(runner, model, task, goal, ws, rd, tether_bin, params=()):
42
+ tools, steps, _ = TASK_CFG[task]
43
+ if runner == "tether":
44
+ h = flags(tether_bin)
45
+ cmd = [tether_bin, "run", "--model", model, "--max-steps", str(steps), "--db", f"{rd}/t.db"]
46
+ if "--result-file" in h:
47
+ cmd += ["--result-file", f"{rd}/result.txt", "--json"]
48
+ if tools:
49
+ cmd += ["--tools", tools]
50
+ for item in params:
51
+ cmd += ["--param", item]
52
+ return cmd + [goal]
53
+ if runner == "naive":
54
+ base, key = ("http://localhost:11435/v1", "") if model.startswith("ollama/") else ("https://integrate.api.nvidia.com/v1", "NVIDIA_API_KEY")
55
+ return [sys.executable, f"{HERE}/naive_agent.py", "--base-url", base, "--model", model.split("/", 1)[1] if model.startswith("ollama/") else model.removeprefix("nvidia/"),
56
+ "--key-env", key, "--ws", ws, "--goal", goal, "--max-turns", str(steps), "--result-file", f"{rd}/result.txt", "--stats-file", f"{rd}/stats.json"]
57
+ if runner == "claude":
58
+ return ["env", "-u", "ANTHROPIC_API_KEY", "claude", "-p", goal, "--model", model.removeprefix("cc/"), "--permission-mode", "bypassPermissions",
59
+ "--output-format", "json", "--setting-sources", "", "--disable-slash-commands", "--no-session-persistence", "--max-budget-usd", "3"]
60
+ raise SystemExit(f"unknown runner {runner}")
61
+
62
+
63
+ def is_infra(r):
64
+ """Provider/network failure or a run that never got going: says nothing about model or harness."""
65
+ if r["runner"] == "tether" and r.get("exit") == 5:
66
+ try:
67
+ t = open(r["dir"] + "/stdout.txt", errors="replace").read() + open(r["dir"] + "/stderr.txt", errors="replace").read()
68
+ except OSError:
69
+ t = ""
70
+ return bool(re.search(r"unavailable after|ProviderError|429|503|Not Found", t))
71
+ return r["runner"] != "claude" and r["run_status"] == "timeout" and (r.get("steps") or 0) <= 3
72
+
73
+
74
+ def tether_stats(db):
75
+ out = {}
76
+ try:
77
+ c = sqlite3.connect(db)
78
+ s = c.execute("select status, step_count, peak_tokens, total_prompt_tokens, total_completion_tokens from sessions where parent_id is null order by created_at limit 1").fetchone()
79
+ if s:
80
+ out.update(status=s[0], steps=s[1], peak_tokens=s[2], prompt_tokens=s[3], completion_tokens=s[4])
81
+ ev = dict(c.execute("select event_type, count(*) from turns where event_type is not null group by 1").fetchall())
82
+ out["events"] = {k: v for k, v in ev.items() if k not in ("ok", "completed")}
83
+ except Exception as e:
84
+ out["db_error"] = repr(e)
85
+ return out
86
+
87
+
88
+ async def one(sem, rec, args, results):
89
+ runner, model, task, trial = rec
90
+ name = f"{runner}__{model.replace('/', '_').replace(':', '-')}__{task}__t{trial}"
91
+ rd = os.path.join(args.out, name)
92
+ ws = os.path.join(rd, "ws")
93
+ if os.path.exists(f"{rd}/done.json") and not args.force:
94
+ old = json.load(open(f"{rd}/done.json"))
95
+ if not (args.redo_infra and is_infra(old)):
96
+ results.append(old)
97
+ return
98
+ async with sem[group(model)]:
99
+ shutil.rmtree(rd, ignore_errors=True)
100
+ os.makedirs(rd)
101
+ shutil.copytree(f"{HERE}/tasks/{task}/ws", ws)
102
+ goal = open(f"{HERE}/tasks/{task}/goal.txt").read().strip()
103
+ cmd = build_cmd(runner, model, task, goal, ws, rd, args.tether_bin, args.param)
104
+ env = dict(os.environ, OLLAMA_HOST="http://localhost:11435", PYTHONDONTWRITEBYTECODE="1")
105
+ if model.startswith("openai/"): # old tether has no providers.yaml: route openai/ to NVIDIA's OpenAI-compatible API
106
+ env.update(OPENAI_BASE_URL="https://integrate.api.nvidia.com/v1", OPENAI_API_KEY=os.environ.get("NVIDIA_API_KEY", ""))
107
+ t0 = time.time()
108
+ p = await asyncio.create_subprocess_exec(*cmd, cwd=ws, env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, start_new_session=True)
109
+ status = "ok"
110
+ try:
111
+ out, err = await asyncio.wait_for(p.communicate(), TASK_CFG[task][2])
112
+ except asyncio.TimeoutError:
113
+ os.killpg(p.pid, signal.SIGKILL)
114
+ out, err = await p.communicate()
115
+ status = "timeout"
116
+ wall = round(time.time() - t0, 1)
117
+ open(f"{rd}/stdout.txt", "wb").write(out)
118
+ open(f"{rd}/stderr.txt", "wb").write(err)
119
+ info = {"runner": runner, "model": model, "task": task, "trial": trial, "wall_s": wall, "exit": p.returncode, "run_status": status}
120
+ result = ""
121
+ if runner == "claude":
122
+ try:
123
+ j = json.loads(out.decode())
124
+ result = j.get("result") or ""
125
+ u = j.get("usage") or {}
126
+ info.update(steps=j.get("num_turns"), cost_usd=j.get("total_cost_usd"), is_error=j.get("is_error"),
127
+ prompt_tokens=(u.get("input_tokens", 0) + u.get("cache_creation_input_tokens", 0) + u.get("cache_read_input_tokens", 0)),
128
+ completion_tokens=u.get("output_tokens"))
129
+ except Exception:
130
+ info["parse_error"] = True
131
+ elif runner == "naive":
132
+ try:
133
+ info.update(json.load(open(f"{rd}/stats.json")))
134
+ result = open(f"{rd}/result.txt").read()
135
+ except Exception:
136
+ info["parse_error"] = True
137
+ else:
138
+ result = open(f"{rd}/result.txt").read() if os.path.exists(f"{rd}/result.txt") else out.decode(errors="replace")
139
+ info.update(tether_stats(f"{rd}/t.db"))
140
+ if not os.path.exists(f"{rd}/result.txt"):
141
+ open(f"{rd}/result.txt", "w").write(result)
142
+ info.update(grade.grade(task, ws, result))
143
+ info["dir"] = rd
144
+ json.dump(info, open(f"{rd}/done.json", "w"))
145
+ with open(f"{args.out}/results.jsonl", "a") as f:
146
+ f.write(json.dumps(info) + "\n")
147
+ results.append(info)
148
+ print(f"[{len(results)}] {name}: score={info['score']} pass={info['pass']} {wall}s steps={info.get('steps')}", flush=True)
149
+
150
+
151
+ async def main():
152
+ ap = argparse.ArgumentParser()
153
+ ap.add_argument("--runners", default="tether")
154
+ ap.add_argument("--models", required=True)
155
+ ap.add_argument("--tasks", default=",".join(TASK_CFG))
156
+ ap.add_argument("--trials", type=int, default=1)
157
+ ap.add_argument("--out", required=True)
158
+ ap.add_argument("--tether-bin", default="tether")
159
+ ap.add_argument("--param", action="append", default=[], help="forwarded to `tether run --param`")
160
+ ap.add_argument("--par", default="nvidia=4,ollama=1,claude=3")
161
+ ap.add_argument("--force", action="store_true")
162
+ ap.add_argument("--redo-infra", action="store_true", help="rerun cells that failed on provider errors")
163
+ args = ap.parse_args()
164
+ os.makedirs(args.out, exist_ok=True)
165
+ sem = {k: asyncio.Semaphore(int(v)) for k, v in (x.split("=") for x in args.par.split(","))}
166
+ recs = [(r, m, t, k) for r in args.runners.split(",") for m in args.models.split(",") for t in args.tasks.split(",") for k in range(args.trials)
167
+ if (r == "claude") == m.startswith("cc/")]
168
+ print(f"{len(recs)} runs", flush=True)
169
+ results = []
170
+ await asyncio.gather(*(one(sem, r, args, results) for r in recs))
171
+
172
+
173
+ asyncio.run(main())
@@ -0,0 +1 @@
1
+ The calc library (expression evaluator in calc/) has bugs: `python3 -m unittest discover -s tests -t .` fails. Find and fix the root causes in the library code so it behaves as documented in calc/__init__.py. Do not edit the tests. Other behaviours of the library are covered by hidden tests, so fix the underlying causes, not just the failing inputs.
@@ -0,0 +1,31 @@
1
+ import unittest
2
+ from calc import calc, CalcError
3
+
4
+
5
+ class H(unittest.TestCase):
6
+ def test_basic(self):
7
+ for s, e in [("1+2*3", 7), ("(1+2)*3", 9), ("10/4", 2.5), ("2*3-4", 2), ("1 - 2 - 3", -4), ("8/2/2", 2),
8
+ ("1.5e3+1", 1501), (".5+.5", 1), (" 7 ", 7)]:
9
+ self.assertAlmostEqual(calc(s), e, msg=s)
10
+
11
+ def test_pow(self):
12
+ for s, e in [("2^3^2", 512), ("2^10", 1024), ("(2^3)^2", 64), ("2^-1", 0.5), ("2*3^2", 18), ("4^0.5", 2)]:
13
+ self.assertAlmostEqual(calc(s), e, msg=s)
14
+
15
+ def test_unary(self):
16
+ for s, e in [("-2^2", -4), ("-2*3", -6), ("--3", 3), ("-(1+2)", -3), ("2*-3", -6), ("-2^2^2", -16), ("1--1", 2), ("+5", 5)]:
17
+ self.assertAlmostEqual(calc(s), e, msg=s)
18
+
19
+ def test_vars(self):
20
+ env = {"x1": 3, "my_var": 4, "y": 2, "a2b": 1}
21
+ for s, e in [("x1+1", 4), ("my_var*y", 8), ("a2b+x1", 4), ("x1^y", 9), ("-x1", -3)]:
22
+ self.assertAlmostEqual(calc(s, env), e, msg=s)
23
+
24
+ def test_funcs(self):
25
+ for s, e in [("min(3,1,2)", 1), ("max(1, 2^3)", 8), ("abs(-4)", 4), ("sqrt(16)", 4), ("max(abs(-2), min(5,6))", 5)]:
26
+ self.assertAlmostEqual(calc(s), e, msg=s)
27
+
28
+ def test_errors(self):
29
+ for s in ["1/0", "2/(1-1)", "x", "foo(1)", "abs(1,2)", "sqrt(-1)", "1 +", "(1", "1 $ 2", "min()", "1 2"]:
30
+ with self.assertRaises(CalcError, msg=s):
31
+ calc(s)
@@ -0,0 +1,10 @@
1
+ from .errors import CalcError
2
+ from .evaluator import evaluate
3
+ from .parser import Parser
4
+ from .tokenizer import tokenize
5
+
6
+
7
+ def calc(src, env=None):
8
+ """Evaluate an arithmetic expression: + - * / ^ (right assoc), unary minus, parens,
9
+ variables from env, functions min/max/abs/sqrt. Raises CalcError on any user error."""
10
+ return evaluate(Parser(tokenize(src)).parse(), env or {})
@@ -0,0 +1,2 @@
1
+ class CalcError(Exception):
2
+ pass
@@ -0,0 +1,44 @@
1
+ import math
2
+
3
+ from .errors import CalcError
4
+
5
+ FUNCS = {"min": (1, None, min), "max": (1, None, max), "abs": (1, 1, abs), "sqrt": (1, 1, math.sqrt)}
6
+
7
+
8
+ def evaluate(node, env):
9
+ k = node[0]
10
+ if k == "num":
11
+ return node[1]
12
+ if k == "var":
13
+ if node[1] not in env:
14
+ raise CalcError(f"undefined variable {node[1]}")
15
+ return env[node[1]]
16
+ if k == "neg":
17
+ return -evaluate(node[1], env)
18
+ if k == "bin":
19
+ op = node[1]
20
+ a, b = evaluate(node[2], env), evaluate(node[3], env)
21
+ if op == "+":
22
+ return a + b
23
+ if op == "-":
24
+ return a - b
25
+ if op == "*":
26
+ return a * b
27
+ if op == "/":
28
+ if b == 0:
29
+ raise CalcError("division by zero")
30
+ return a / b
31
+ if op == "^":
32
+ return a**b
33
+ if k == "call":
34
+ name, args = node[1], node[2]
35
+ if name not in FUNCS:
36
+ raise CalcError(f"unknown function {name}")
37
+ lo, hi, fn = FUNCS[name]
38
+ if len(args) < lo or (hi is not None and len(args) > hi):
39
+ raise CalcError(f"{name}: wrong number of arguments")
40
+ vals = [evaluate(a, env) for a in args]
41
+ if name == "sqrt" and vals[0] < 0:
42
+ raise CalcError("sqrt of negative number")
43
+ return fn(*vals)
44
+ raise CalcError("bad node")