@sema-agent/core 5.20.0 → 5.21.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 (312) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/agents/agent-definition.d.ts +7 -0
  3. package/dist/agents/agent-transcript-tool.d.ts +30 -0
  4. package/dist/agents/builtin-agents.d.ts +60 -0
  5. package/dist/agents/cascade.d.ts +107 -0
  6. package/dist/agents/cumulative-stats.d.ts +56 -0
  7. package/dist/agents/observer.d.ts +162 -0
  8. package/dist/agents/peer-admission.d.ts +95 -0
  9. package/dist/agents/repair-loop.d.ts +226 -0
  10. package/dist/agents/retain-ledger.d.ts +141 -0
  11. package/dist/agents/roster-store.d.ts +105 -0
  12. package/dist/agents/send-message-tool.d.ts +92 -0
  13. package/dist/agents/session-util.d.ts +5 -0
  14. package/dist/agents/subagent-steps.d.ts +66 -0
  15. package/dist/agents/subagent.d.ts +600 -0
  16. package/dist/agents/suspend-guard.d.ts +29 -0
  17. package/dist/agents/teacher.d.ts +75 -0
  18. package/dist/agents/team.d.ts +120 -1
  19. package/dist/agents/tool-filter.d.ts +34 -0
  20. package/dist/agents/verify.d.ts +198 -0
  21. package/dist/bench/metrics.d.ts +455 -0
  22. package/dist/brain/anthropic.d.ts +30 -0
  23. package/dist/brain/circuit-breaker.d.ts +33 -0
  24. package/dist/brain/context-overflow.d.ts +60 -3
  25. package/dist/brain/degrading.d.ts +67 -0
  26. package/dist/brain/errors.d.ts +42 -0
  27. package/dist/brain/failover.d.ts +15 -0
  28. package/dist/brain/media-degrade.d.ts +39 -0
  29. package/dist/brain/model-presets.d.ts +31 -0
  30. package/dist/brain/open-responses.d.ts +19 -0
  31. package/dist/brain/openai.d.ts +46 -0
  32. package/dist/brain/reasoning.d.ts +106 -1
  33. package/dist/brain/repetition.d.ts +83 -0
  34. package/dist/brain/request-params.d.ts +56 -0
  35. package/dist/brain/retry.d.ts +46 -0
  36. package/dist/brain/routing.d.ts +12 -0
  37. package/dist/brain/status-sink.d.ts +30 -1
  38. package/dist/brain/stream-engine.d.ts +147 -0
  39. package/dist/brain/stream-shared.d.ts +34 -0
  40. package/dist/brain/terminal-cause.d.ts +31 -0
  41. package/dist/brain/timeout.d.ts +107 -0
  42. package/dist/brain/tool-call-id.d.ts +20 -0
  43. package/dist/brain/tool-call-repair.d.ts +13 -0
  44. package/dist/config/catalog.d.ts +47 -0
  45. package/dist/config/defaults.d.ts +33 -0
  46. package/dist/core/a2a-task-state.d.ts +53 -0
  47. package/dist/core/a2a.d.ts +51 -0
  48. package/dist/core/arg-summary.d.ts +62 -0
  49. package/dist/core/ask-question.d.ts +272 -2
  50. package/dist/core/auto-compaction.d.ts +467 -0
  51. package/dist/core/auto-compaction.js +20 -6
  52. package/dist/core/auto-mode-prompt-assets.d.ts +8 -0
  53. package/dist/core/auto-mode-prompt.d.ts +27 -0
  54. package/dist/core/auto-mode.d.ts +54 -3
  55. package/dist/core/auto-promote.d.ts +100 -0
  56. package/dist/core/background-agent-store.d.ts +292 -0
  57. package/dist/core/background-shell.d.ts +110 -0
  58. package/dist/core/cache-break-detector.d.ts +34 -0
  59. package/dist/core/canonical-json.d.ts +57 -0
  60. package/dist/core/checkpoint-store.d.ts +1574 -16
  61. package/dist/core/compliance.d.ts +30 -0
  62. package/dist/core/consolidate-scope.d.ts +75 -0
  63. package/dist/core/context-edit.d.ts +99 -0
  64. package/dist/core/context-guard.d.ts +46 -0
  65. package/dist/core/exec-gate.d.ts +44 -0
  66. package/dist/core/exec-output-tail.d.ts +61 -0
  67. package/dist/core/file-snapshot-store.d.ts +104 -0
  68. package/dist/core/fs-write-gate-policy.d.ts +36 -0
  69. package/dist/core/git-worktree-env.d.ts +31 -0
  70. package/dist/core/governance-codes.d.ts +19 -0
  71. package/dist/core/hooks.d.ts +608 -1
  72. package/dist/core/human-input-projection.d.ts +37 -0
  73. package/dist/core/human-input-projection.js +13 -0
  74. package/dist/core/image-downsample.d.ts +74 -0
  75. package/dist/core/locked-config.d.ts +37 -0
  76. package/dist/core/lsp-diagnostics.d.ts +77 -0
  77. package/dist/core/lsp-protocol.d.ts +29 -0
  78. package/dist/core/lsp-session.d.ts +60 -1
  79. package/dist/core/lsp.d.ts +150 -1
  80. package/dist/core/mailbox-store.d.ts +57 -0
  81. package/dist/core/mcp.d.ts +381 -0
  82. package/dist/core/media-byte-cap.d.ts +21 -0
  83. package/dist/core/memory-admission.d.ts +71 -0
  84. package/dist/core/memory-engine/content-origin.d.ts +64 -0
  85. package/dist/core/memory-engine/data-plane.d.ts +43 -0
  86. package/dist/core/memory-engine/dual-root.d.ts +24 -0
  87. package/dist/core/memory-engine/engine.d.ts +230 -0
  88. package/dist/core/memory-engine/engine.js +103 -35
  89. package/dist/core/memory-engine/file-backend.d.ts +155 -0
  90. package/dist/core/memory-engine/frontmatter.d.ts +16 -0
  91. package/dist/core/memory-engine/layout.d.ts +217 -0
  92. package/dist/core/memory-engine/memory-backend-contract.d.ts +12 -0
  93. package/dist/core/memory-engine/migrate.d.ts +9 -0
  94. package/dist/core/memory-engine/scan.d.ts +12 -0
  95. package/dist/core/memory-engine/scope-contract.d.ts +61 -1
  96. package/dist/core/memory-engine/sync-client.d.ts +87 -0
  97. package/dist/core/memory-engine/sync.d.ts +60 -0
  98. package/dist/core/memory-engine/tools.d.ts +41 -0
  99. package/dist/core/memory-engine/types.d.ts +188 -0
  100. package/dist/core/memory-recall.d.ts +141 -0
  101. package/dist/core/memory-vector.d.ts +20 -0
  102. package/dist/core/memory.d.ts +458 -0
  103. package/dist/core/message-utils.d.ts +6 -0
  104. package/dist/core/oracle-isolation.d.ts +69 -0
  105. package/dist/core/permission-rule-consent.d.ts +138 -0
  106. package/dist/core/permission-rule-model.d.ts +122 -0
  107. package/dist/core/permission-rule-store.d.ts +119 -3
  108. package/dist/core/permission-rules.d.ts +87 -1
  109. package/dist/core/present-plan-tool.d.ts +20 -0
  110. package/dist/core/pricing.d.ts +26 -0
  111. package/dist/core/property-harness.d.ts +86 -0
  112. package/dist/core/protocol-naming.d.ts +38 -0
  113. package/dist/core/protocol-table.d.ts +61 -0
  114. package/dist/core/push-queue.d.ts +1 -0
  115. package/dist/core/remote-env.d.ts +383 -1
  116. package/dist/core/retention-policy.d.ts +33 -0
  117. package/dist/core/retention.d.ts +51 -0
  118. package/dist/core/roles.d.ts +59 -0
  119. package/dist/core/runner/active-skill-scope.d.ts +34 -0
  120. package/dist/core/runner/assemble-result.d.ts +134 -0
  121. package/dist/core/runner/compaction-call-options.d.ts +97 -1
  122. package/dist/core/runner/grounding-signal.d.ts +10 -0
  123. package/dist/core/runner/image.d.ts +17 -0
  124. package/dist/core/runner/image.js +29 -15
  125. package/dist/core/runner/memory-consolidation.d.ts +60 -0
  126. package/dist/core/runner/prepare-memory.d.ts +59 -0
  127. package/dist/core/runner/prepare-task.d.ts +1011 -2
  128. package/dist/core/runner/prepare-task.js +12 -11
  129. package/dist/core/runner/prompt-suggestions.d.ts +7 -0
  130. package/dist/core/runner/runtask.d.ts +304 -3
  131. package/dist/core/runner/session-file-state-replay.d.ts +49 -0
  132. package/dist/core/runner/session-rule-policy.d.ts +58 -0
  133. package/dist/core/runner/strict-output-schema.d.ts +18 -3
  134. package/dist/core/runner/synthetic-tools.d.ts +113 -0
  135. package/dist/core/runner/teardown-bounded.d.ts +34 -0
  136. package/dist/core/runner/tool-disclosure.d.ts +227 -0
  137. package/dist/core/runner/tool-output-projection.d.ts +6 -0
  138. package/dist/core/runner/turn-attachments.d.ts +634 -0
  139. package/dist/core/runner/usage-accounting.d.ts +32 -0
  140. package/dist/core/runtime.d.ts +9 -0
  141. package/dist/core/safe-notify.d.ts +64 -0
  142. package/dist/core/safety-axis-vocab.d.ts +23 -0
  143. package/dist/core/safety-merge-corpus.d.ts +37 -0
  144. package/dist/core/scheduler.d.ts +121 -0
  145. package/dist/core/secret-env.d.ts +32 -0
  146. package/dist/core/select-model.d.ts +15 -0
  147. package/dist/core/sensitive-path-policy.d.ts +42 -0
  148. package/dist/core/session-policy-store.d.ts +94 -0
  149. package/dist/core/session-reconcile.d.ts +80 -0
  150. package/dist/core/session-store.d.ts +85 -0
  151. package/dist/core/session.d.ts +153 -0
  152. package/dist/core/shared-memory/contract.d.ts +22 -0
  153. package/dist/core/shared-memory/normalize.d.ts +123 -2
  154. package/dist/core/shared-memory/tools.d.ts +14 -0
  155. package/dist/core/shared-memory/types.d.ts +105 -0
  156. package/dist/core/shutdown-debug.d.ts +6 -0
  157. package/dist/core/side-query.d.ts +38 -0
  158. package/dist/core/side-query.js +6 -1
  159. package/dist/core/skill-tool-specifier.d.ts +72 -0
  160. package/dist/core/skills-directory.d.ts +100 -1
  161. package/dist/core/spec-contract.d.ts +89 -0
  162. package/dist/core/store-contracts/background-agent-store-contract.d.ts +31 -0
  163. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +26 -0
  164. package/dist/core/store-contracts/contract-harness.d.ts +20 -0
  165. package/dist/core/store-contracts/contract-kit-version.d.ts +27 -0
  166. package/dist/core/store-contracts/file-snapshot-store-contract.d.ts +8 -0
  167. package/dist/core/store-contracts/mailbox-store-contract.d.ts +42 -0
  168. package/dist/core/store-contracts/tool-result-store-contract.d.ts +13 -0
  169. package/dist/core/strategy-store.d.ts +37 -0
  170. package/dist/core/stub-env.d.ts +7 -0
  171. package/dist/core/surrogate-safe-slice.d.ts +35 -0
  172. package/dist/core/task-notification.d.ts +202 -0
  173. package/dist/core/task-outcome.d.ts +53 -0
  174. package/dist/core/task-registry-agent.d.ts +337 -1
  175. package/dist/core/task-registry-monitor.d.ts +12 -0
  176. package/dist/core/task-registry-shared.d.ts +540 -0
  177. package/dist/core/task-registry.d.ts +343 -0
  178. package/dist/core/task-registry.js +13 -2
  179. package/dist/core/task-tool-shape.d.ts +44 -0
  180. package/dist/core/tighten-task-spec.d.ts +21 -0
  181. package/dist/core/tool-detach.d.ts +21 -0
  182. package/dist/core/tool-errors.d.ts +131 -0
  183. package/dist/core/tool-errors.js +4 -0
  184. package/dist/core/tool-name-aliases.d.ts +27 -0
  185. package/dist/core/tool-policy.d.ts +555 -0
  186. package/dist/core/tool-result-budget.d.ts +32 -0
  187. package/dist/core/tool-result-store.d.ts +174 -1
  188. package/dist/core/tools.d.ts +45 -0
  189. package/dist/core/trace.d.ts +323 -0
  190. package/dist/core/types.d.ts +3859 -2
  191. package/dist/core/untrusted-egress.d.ts +8 -0
  192. package/dist/core/untrusted-text.d.ts +156 -0
  193. package/dist/core/usage-window-store.d.ts +95 -0
  194. package/dist/core/version.d.ts +1 -0
  195. package/dist/core/warm-resume.d.ts +17 -0
  196. package/dist/core/wiring-manifest.d.ts +169 -0
  197. package/dist/core/with-retry.d.ts +24 -0
  198. package/dist/core/workflow-journal-store.d.ts +160 -0
  199. package/dist/core/workflow-run-store-contract.d.ts +25 -0
  200. package/dist/core/workflow-run-store.d.ts +119 -0
  201. package/dist/engine/compaction/compaction.d.ts +256 -1
  202. package/dist/engine/compaction/utils.d.ts +94 -0
  203. package/dist/engine/execution-env/kill-tree.d.ts +29 -0
  204. package/dist/engine/execution-env/node-execution-env.d.ts +94 -0
  205. package/dist/engine/harness/agent-harness.d.ts +116 -0
  206. package/dist/engine/harness/agent-harness.js +3 -14
  207. package/dist/engine/harness/messages.d.ts +15 -0
  208. package/dist/engine/harness/types.d.ts +464 -2
  209. package/dist/engine/llm/diagnostics.d.ts +4 -0
  210. package/dist/engine/llm/event-stream.d.ts +3 -0
  211. package/dist/engine/llm/index.d.ts +7 -0
  212. package/dist/engine/llm/types.d.ts +500 -3
  213. package/dist/engine/llm/validation.d.ts +3 -0
  214. package/dist/engine/loop/agent-loop.d.ts +87 -2
  215. package/dist/engine/loop/runtime-deps.d.ts +7 -0
  216. package/dist/engine/loop/types.d.ts +424 -0
  217. package/dist/engine/lsp/frame-decoder.d.ts +13 -0
  218. package/dist/engine/lsp/node-lsp-manager.d.ts +107 -0
  219. package/dist/engine/lsp/stdio-lsp-transport.d.ts +7 -0
  220. package/dist/engine/session/import-validate.d.ts +27 -0
  221. package/dist/engine/session/log-digest.d.ts +93 -0
  222. package/dist/engine/session/memory-repo.d.ts +6 -0
  223. package/dist/engine/session/memory-storage.d.ts +2 -0
  224. package/dist/engine/session/session.d.ts +75 -0
  225. package/dist/engine/session/storage-base.d.ts +8 -0
  226. package/dist/fixtures/index.d.ts +36 -0
  227. package/dist/index.d.ts +16 -1
  228. package/dist/index.js +0 -1
  229. package/dist/internal/harness-types.d.ts +6 -0
  230. package/dist/internal/harness.d.ts +11 -0
  231. package/dist/internal/llm.d.ts +6 -0
  232. package/dist/orchestration/builtin-workflows.d.ts +53 -0
  233. package/dist/orchestration/dev-vm-script-runner.d.ts +19 -0
  234. package/dist/orchestration/goal.d.ts +57 -0
  235. package/dist/orchestration/goal.js +3 -0
  236. package/dist/orchestration/run-spec.d.ts +42 -0
  237. package/dist/orchestration/run-workflow-tool.d.ts +169 -0
  238. package/dist/orchestration/workflow-governance.d.ts +61 -0
  239. package/dist/orchestration/workflow-meta.d.ts +28 -0
  240. package/dist/orchestration/workflow-observe.d.ts +60 -0
  241. package/dist/orchestration/workflow-primitives.d.ts +23 -1
  242. package/dist/orchestration/workflow-sandbox-conformance.d.ts +38 -0
  243. package/dist/orchestration/workflow-script-runner.d.ts +88 -0
  244. package/dist/orchestration/workflow-script-store.d.ts +98 -0
  245. package/dist/orchestration/workflow-size-guideline.d.ts +67 -0
  246. package/dist/orchestration/workflow-types.d.ts +169 -2
  247. package/dist/orchestration/workflow.d.ts +358 -0
  248. package/dist/prompt-assembly/artifact-store.d.ts +33 -0
  249. package/dist/prompt-assembly/artifact.d.ts +25 -0
  250. package/dist/prompt-assembly/assemble.d.ts +20 -0
  251. package/dist/prompt-assembly/composer.d.ts +29 -0
  252. package/dist/prompt-assembly/epoch.d.ts +55 -1
  253. package/dist/prompt-assembly/event-registry.d.ts +35 -0
  254. package/dist/prompt-assembly/explain.d.ts +12 -0
  255. package/dist/prompt-assembly/tool-catalog.d.ts +38 -0
  256. package/dist/prompt-assembly/turn-snapshot.d.ts +40 -0
  257. package/dist/prompt-assembly/types.d.ts +115 -0
  258. package/dist/prompts/coordinator.d.ts +27 -0
  259. package/dist/prompts/default.d.ts +539 -0
  260. package/dist/prompts/simple-sections.d.ts +45 -0
  261. package/dist/prompts/supervisor.d.ts +66 -0
  262. package/dist/scenarios/env.d.ts +28 -0
  263. package/dist/scenarios/full-body.d.ts +50 -0
  264. package/dist/scenarios/scenario-registry.d.ts +60 -0
  265. package/dist/scenarios/teacher-quickstart.d.ts +27 -0
  266. package/dist/server/http.d.ts +17 -0
  267. package/dist/stores/cc/lockfile.d.ts +6 -0
  268. package/dist/stores/cc/mailbox-store.d.ts +8 -0
  269. package/dist/stores/cc/roster-adapter.d.ts +4 -0
  270. package/dist/stores/cc/sidecar-transcript.d.ts +66 -0
  271. package/dist/stores/file/background-agent-store.d.ts +24 -0
  272. package/dist/stores/file/checkpoint-store.d.ts +38 -0
  273. package/dist/stores/file/file-snapshot-store.d.ts +25 -0
  274. package/dist/stores/file/fs-atomic.d.ts +155 -0
  275. package/dist/stores/file/index.d.ts +89 -0
  276. package/dist/stores/file/mailbox-store.d.ts +36 -0
  277. package/dist/stores/file/memory-store.d.ts +82 -0
  278. package/dist/stores/file/permission-rule-store.d.ts +79 -0
  279. package/dist/stores/file/session-policy-store.d.ts +28 -0
  280. package/dist/stores/file/session-store.d.ts +40 -0
  281. package/dist/stores/file/shared-ledger.d.ts +83 -0
  282. package/dist/stores/file/tool-result-store.d.ts +11 -0
  283. package/dist/stores/file/usage-window-store.d.ts +18 -0
  284. package/dist/stores/file/workflow-journal-store.d.ts +100 -0
  285. package/dist/stores/file/workflow-run-store.d.ts +11 -0
  286. package/dist/tools/fs/bash-readonly-classifier.d.ts +282 -0
  287. package/dist/tools/fs/encoding.d.ts +60 -0
  288. package/dist/tools/fs/fs-bash.d.ts +133 -0
  289. package/dist/tools/fs/fs-pdf.d.ts +28 -0
  290. package/dist/tools/fs/fs-search-tools.d.ts +5 -0
  291. package/dist/tools/fs/fs-shared.d.ts +360 -0
  292. package/dist/tools/fs/fs-write.d.ts +16 -0
  293. package/dist/tools/fs/gh-rate-limit.d.ts +22 -0
  294. package/dist/tools/fs/index.d.ts +79 -0
  295. package/dist/tools/fs/notebook.d.ts +56 -0
  296. package/dist/tools/fs/pdf.d.ts +70 -0
  297. package/dist/tools/fs/pdf.js +8 -2
  298. package/dist/tools/fs/repo-map.d.ts +10 -0
  299. package/dist/tools/fs/safety.d.ts +376 -0
  300. package/dist/tools/fs/search.d.ts +131 -0
  301. package/dist/tools/loop-tick.d.ts +24 -0
  302. package/dist/tools/monitor.d.ts +55 -0
  303. package/dist/tools/scheduler-tools.d.ts +51 -0
  304. package/dist/tools/sql-adapters.d.ts +18 -0
  305. package/dist/tools/sql.d.ts +25 -0
  306. package/dist/tools/task-list.d.ts +77 -0
  307. package/dist/tools/todo.d.ts +8 -0
  308. package/dist/tools/web.d.ts +184 -0
  309. package/dist/tools/worktree.d.ts +81 -0
  310. package/package.json +2 -2
  311. package/dist/tools/gitea-issue.d.ts +0 -13
  312. package/dist/tools/gitea-issue.js +0 -75
@@ -1,15 +1,45 @@
1
1
  import type { Brain } from "../core/types.js";
2
2
  import { type StreamEngineConfig } from "./stream-engine.js";
3
3
  export interface AnthropicBrainConfig extends StreamEngineConfig {
4
+ /** Base URL of the Anthropic(-compatible) API. Default `https://api.anthropic.com`. Overridden by model.baseUrl. */
4
5
  baseUrl?: string;
6
+ /** API key (`x-api-key`). Overridden by per-call options.apiKey / getApiKeyAndHeaders. */
5
7
  apiKey?: string;
8
+ /** `anthropic-version` header. Default `2023-06-01`. */
6
9
  version?: string;
10
+ /** Extra headers merged into every request (e.g. `anthropic-beta`). */
7
11
  headers?: Record<string, string>;
12
+ /** Custom fetch (tests / proxies). Defaults to global fetch. */
8
13
  fetchImpl?: typeof fetch;
14
+ /** `max_tokens` when the call/model doesn't specify one (Anthropic requires it). Default 4096. */
9
15
  defaultMaxTokens?: number;
16
+ /**
17
+ * Insert `cache_control: {type:"ephemeral"}` prompt-cache breakpoints on the last system block and
18
+ * the last tool, so the (stable) system + tools prefix is cached across requests. Default true.
19
+ */
10
20
  cacheBreakpoints?: boolean;
21
+ /**
22
+ * Detect **degenerate repetition** (the model looping on the same char/phrase forever) mid-stream
23
+ * and cut it off — the turn ends `error` ("degenerate repetition"). Default true.
24
+ */
11
25
  detectRepetition?: boolean;
26
+ /**
27
+ * Extended-thinking budget as a fraction of `max_tokens` when reasoning is on. Default 0.5.
28
+ * The budget is always clamped to `[1024, max_tokens - 1]` (Anthropic requires it strictly below
29
+ * `max_tokens`, ≥ 1024). Lower it to leave more room for the answer with verbose reasoning models.
30
+ */
12
31
  thinkingBudgetShare?: number;
32
+ /**
33
+ * Fixed extended-thinking budget in tokens (overrides `thinkingBudgetShare`). Still clamped to
34
+ * `[1024, max_tokens - 1]`. Use when you want a constant reasoning budget regardless of max_tokens.
35
+ */
13
36
  thinkingBudgetTokens?: number;
14
37
  }
38
+ /**
39
+ * Create a Brain for the Anthropic Messages API (`/v1/messages`) with **prompt caching** and
40
+ * **extended-thinking replay**. Translates the unified Context into an Anthropic request and the
41
+ * streamed response back into the unified AssistantMessageEvent protocol. The connect/retry/timeout/
42
+ * read-loop machinery lives in the shared {@link runStreamingBrain} engine (design/32); this adapter
43
+ * owns the Anthropic request shaping + typed content-block SSE parsing + finalization.
44
+ */
15
45
  export declare function createAnthropicBrain(config?: AnthropicBrainConfig): Brain;
@@ -1,26 +1,59 @@
1
1
  import type { Model } from "../internal/llm.js";
2
2
  import type { Brain } from "../core/types.js";
3
3
  import { type BrainErrorCode } from "./errors.js";
4
+ /** Stable prefix of an open-breaker error's detail (`[network] circuit open for <key>`). Exported so
5
+ * the degradation cascade can detect breaker-open **structurally** instead of string-matching a literal
6
+ * (council #1) — reword the message only by changing this constant. */
4
7
  export declare const CIRCUIT_OPEN_MARKER = "circuit open for ";
5
8
  export type BreakerPhase = "closed" | "open" | "half-open";
6
9
  export interface BreakerSnapshot {
7
10
  phase: BreakerPhase;
11
+ /** Consecutive failures while closed. */
8
12
  failures: number;
13
+ /** When the breaker opened (epoch ms), for cooldown. */
9
14
  openedAt?: number;
15
+ /** Probes currently allowed through while half-open. */
10
16
  halfOpenInFlight?: number;
17
+ /**
18
+ * When the current half-open probe round was admitted (epoch ms) — the PROBE LEASE stamp.
19
+ *
20
+ * HRD-BRN-1: `record()` is the only writer that leaves half-open, and it only runs once the probe's
21
+ * stream settles. A probe that never settles — precisely the accepted-then-hangs gateway the breaker
22
+ * exists for, and the default shape since `firstTokenTimeoutMs`/`idleTimeoutMs` both default off —
23
+ * therefore held `halfOpenInFlight` forever and made half-open an ABSORBING state: no clock could
24
+ * release the key again. The lease bounds it: once `cooldownMs` has elapsed since this stamp, the
25
+ * in-flight probe is presumed lost and a fresh probe is admitted (see `tryPass`).
26
+ *
27
+ * Optional/additive: a snapshot deserialized by a shared backend that predates the field simply
28
+ * adopts a stamp on the first refusal, so the lease starts from then rather than never.
29
+ */
11
30
  halfOpenAt?: number;
12
31
  }
32
+ /** Pluggable breaker state. In-memory by default; a deployment can back it with Redis/TiDB so all
33
+ * replicas share one circuit (otherwise each replica trips independently and reacts slowly).
34
+ *
35
+ * ATOMICITY: the breaker does read-modify-write (`get` → decide → `set`). The in-process Map is safe
36
+ * under Node's single-threaded run-to-completion. A shared async backend MUST make get/set
37
+ * **linearizable** (or expose CAS) — otherwise concurrent transitions (closed→open, open→half-open)
38
+ * race (TOCTOU). Implement it with a Lua script / transaction / optimistic-version on the store. */
13
39
  export interface BreakerState {
14
40
  get(key: string): BreakerSnapshot | undefined;
15
41
  set(key: string, snap: BreakerSnapshot): void;
16
42
  }
17
43
  export interface CircuitBreakerOptions {
44
+ /** Consecutive transient failures that trip the breaker. Default 5. */
18
45
  failureThreshold?: number;
46
+ /** How long the breaker stays open before a half-open probe. Default 30_000 ms. */
19
47
  cooldownMs?: number;
48
+ /** Probes allowed through while half-open. Default 1. */
20
49
  halfOpenProbes?: number;
50
+ /** Error codes that count toward tripping. Default `["network","server","rate_limit"]`. */
21
51
  countCodes?: BrainErrorCode[];
52
+ /** Breaker key from a model. Default `"<provider>:<id>"` (per model+provider). */
22
53
  key?: (model: Model) => string;
54
+ /** State backend. Default in-memory (per process). */
23
55
  state?: BreakerState;
56
+ /** Clock, injectable for tests. */
24
57
  now?: () => number;
25
58
  }
26
59
  export declare function createCircuitBreakerBrain(inner: Brain, opts?: CircuitBreakerOptions): Brain;
@@ -1,20 +1,77 @@
1
+ /**
2
+ * Adaptive `max_tokens` recovery for the ONE provider 400 that is self-healing (CC parity `Fjp` /
3
+ * `Ijp`, ruled 2026-08-05).
4
+ *
5
+ * The failure: the input fits the model's context window, but `input + max_tokens` does not. Nothing
6
+ * downstream rescues it — the compaction layer's own detectors match "prompt is too long", a
7
+ * DIFFERENT message meaning the input ALONE overflows, so this 400 is classified `invalid_request`,
8
+ * is not retried, and terminates the task even though lowering this one request's output cap would
9
+ * have served it. The provider states every number needed to compute the fix in the error text.
10
+ *
11
+ * The recovery is deliberately NARROW: only a 400 whose body carries this exact sentence can trigger
12
+ * it, and anything the parser cannot read as three integers leaves the original failure untouched.
13
+ * Two fail-loud guards then bound it — a floor below which lowering the cap stops being useful, and
14
+ * a no-progress guard so a provider that keeps reporting the same numbers cannot loop the engine.
15
+ */
16
+ /** CC parity (`Ijp`): the smallest output cap worth retrying with. Below this the answer room is so
17
+ * small that a re-send is not a recovery, so the original 400 is surfaced instead. */
1
18
  export declare const FLOOR_OUTPUT_TOKENS = 3000;
19
+ /** The three numbers the provider reported. */
2
20
  export interface ContextOverflowReport {
21
+ /** Tokens the provider measured in the request input. */
3
22
  inputTokens: number;
23
+ /** The output cap this request carried. */
4
24
  maxTokens: number;
25
+ /** The model's total context limit, as the provider counts it. */
5
26
  contextLimit: number;
6
27
  }
28
+ /**
29
+ * Read the three numbers out of a provider 400 body, or `undefined` for every other failure —
30
+ * including a 400 of any other shape, a body whose provenance is unestablished, a truncated body, and
31
+ * numbers too large to be exact integers. A caller that gets `undefined` must surface the original
32
+ * failure unchanged.
33
+ */
7
34
  export declare function parseContextOverflow(status: number, body: string): ContextOverflowReport | undefined;
8
- export type OutputCapAdjustment = {
35
+ /**
36
+ * What to do about a parsed overflow. `adjust` is the only outcome that re-sends; the other two are
37
+ * refusals that the caller must report ALONGSIDE the original provider failure, so an operator sees
38
+ * that a recovery was attempted and why it was declined rather than a bare 400.
39
+ */
40
+ export type OutputCapAdjustment =
41
+ /** `current` is the cap this adjustment lowers FROM — the smallest one known to be in effect, which
42
+ * is what a disclosure must name (the provider's echoed number may not be what was sent). */
43
+ {
9
44
  outcome: "adjust";
10
45
  maxOutputTokens: number;
11
46
  current: number;
12
- } | {
47
+ }
48
+ /** The room left under the context limit is below {@link FLOOR_OUTPUT_TOKENS} — the input itself is
49
+ * the problem, and no output cap makes this request servable. */
50
+ | {
13
51
  outcome: "below_floor";
14
52
  available: number;
15
- } | {
53
+ }
54
+ /** The recomputed cap is not STRICTLY below the cap already in effect — the previous adjustment
55
+ * did not take effect, or the provider re-reported the same numbers, or the numbers would RAISE
56
+ * the cap. Re-sending cannot help, and in the raising case would be actively worse. */
57
+ | {
16
58
  outcome: "no_progress";
17
59
  available: number;
18
60
  current: number;
19
61
  };
62
+ /**
63
+ * Compute the lowered output cap for a re-send, or the reason not to.
64
+ *
65
+ * `otherCapsInEffect` are the caps the CALLER knows about beyond the one the provider echoed —
66
+ * typically the cap this engine already imposed on an earlier attempt, and the cap the request
67
+ * actually carried on the wire. The SMALLEST of all of them bounds the adjustment, and a new cap
68
+ * must be strictly below it. That single rule does three jobs:
69
+ * - it terminates the loop (every accepted adjustment lowers the cap, and the floor bounds it);
70
+ * - it makes an adapter that ignored an imposed cap fail loud after one round instead of looping;
71
+ * - it keeps the recovery from ever RAISING a cap on the strength of a number the provider
72
+ * reported but the request never carried.
73
+ *
74
+ * `report.maxTokens` is always one of the caps considered — the provider says the failing request
75
+ * carried it, and a value it did not carry can only be smaller in the direction that matters.
76
+ */
20
77
  export declare function planOutputCapAdjustment(report: ContextOverflowReport, otherCapsInEffect?: readonly (number | undefined)[]): OutputCapAdjustment;
@@ -1,26 +1,93 @@
1
+ /**
2
+ * Error/budget-aware **degradation cascade** (1.39, design/21, design/17 §5C).
3
+ *
4
+ * Unlike failover (a *peer* backup whose goal is "same quality, a gateway that's actually up"),
5
+ * degradation **deliberately downgrades** to a cheaper / different-provider model to KEEP SERVING when
6
+ * the primary is rate-limited or its circuit breaker is open — accepting some quality loss instead of
7
+ * failing the task. Opt-in; the served turn is tagged so the Runner can surface `TaskResult.degraded`.
8
+ *
9
+ * This file handles the four **reactive** triggers visible at the brain layer — `rate_limit`,
10
+ * `breaker_open`, `server_error` and `last_resort` (design/126; all four are the default gate, narrow it
11
+ * with `downgradeOn`). The proactive **near-budget** trigger needs the task budget (only the Runner sees
12
+ * it) and is not implemented here; `"budget"` is reserved in `DegradeReason` for it.
13
+ *
14
+ * Detection is **structural**, not literal string-matching: the breaker-open signal is
15
+ * `CIRCUIT_OPEN_MARKER` (exported from circuit-breaker.ts) and the code comes from the shared
16
+ * `extractErrorCode`. Degradation must be the **outermost** brain in a stack (so it sees the inner
17
+ * failover/breaker/timeout outcomes and can downgrade on them), and the downgrade target is the ordered
18
+ * `fallbacks` chain (RB-482 #3 — the single `fallback`+`fallbackModel` pair is retired):
19
+ * `createDegradingBrain({ primary: failover(breaker(timeout(brain))), fallbacks: [{ brain, model }] })`.
20
+ */
1
21
  import { type AssistantMessageDiagnostic, type Model } from "../internal/llm.js";
2
22
  import type { Brain } from "../core/types.js";
23
+ /** Diagnostic `type` the decorator stamps on a degraded turn's message; the Runner reads it back. */
3
24
  export declare const DEGRADED_DIAGNOSTIC_TYPE = "degraded";
25
+ /** Why a turn was degraded. `"budget"` is reserved for the v2 near-budget trigger (Runner-level).
26
+ * design/126 (CC 批 β) widens the reactive set: `"server_error"` = a `server`-class failure (5xx incl.
27
+ * 529 overloaded, 408/409) that ESCAPED the inner brain's own retry budget (CC parity: retry in place
28
+ * first, then fall back — CC :600552); `"last_resort"` = an `http`-class status error (404
29
+ * model-not-found and other non-retryable statuses — CC :600513/:600588 folds both into "try the next
30
+ * model instead of dying"). Deliberate deviations from CC, documented in design/126 D2: `rate_limit`
31
+ * stays a trigger (CC waits in place; an unattended headless task waiting forever is a dead task), and
32
+ * `auth` (401/403) NEVER triggers (CC falls back on 403; silently swapping models over a
33
+ * permission/key misconfiguration is worse than failing loud for headless). */
4
34
  export type DegradeReason = "breaker_open" | "rate_limit" | "budget" | "server_error" | "last_resort";
5
35
  export interface DegradationInfo {
36
+ /** The model id that was meant to serve (the primary). */
6
37
  from: string;
38
+ /** The cheaper model id that actually served (or the LAST model attempted when the chain failed too). */
7
39
  to: string;
40
+ /** The FIRST trigger that started the downgrade walk (later hops may fail for other reasons). */
8
41
  reason: DegradeReason;
42
+ /** design/126: the model ids attempted after the primary, in order (length 1 = the classic single
43
+ * hop). Optional — absent on markers written by pre-chain versions. */
9
44
  chain?: string[];
10
45
  }
11
46
  interface DegradingBrainBaseOptions {
47
+ /** The preferred brain (typically `failover(breaker(timeout(openai)))`). */
12
48
  primary: Brain;
49
+ /**
50
+ * Which reactive triggers cause a downgrade. Default = all four reactive classes
51
+ * (`rate_limit`/`breaker_open`/`server_error`/`last_resort`). Pass it explicitly to narrow.
52
+ */
13
53
  downgradeOn?: DegradeReason[];
14
54
  }
55
+ /** RB-482 #3 (ruled 2026-08-03): ONE form — the ordered `fallbacks` chain. The legacy single
56
+ * `fallback`+`fallbackModel` pair is retired (a chain-of-one is `fallbacks: [{brain, model}]`), and
57
+ * its pre-126 two-trigger default retires with it: every construction gets the full four-class gate
58
+ * unless `downgradeOn` narrows it explicitly. */
15
59
  export type DegradingBrainOptions = DegradingBrainBaseOptions & {
60
+ /**
61
+ * design/126 (CC 批 β) — the ORDERED downgrade chain (up to 3 entries, CC `Kjd` parity; excess is
62
+ * truncated, duplicate model ids deduped, and an entry whose model id equals the model that just
63
+ * failed is skipped at walk time). Each hop carries its OWN brain — carry its credentials in its
64
+ * config (e.g. `createOpenAIBrain({ apiKey, baseUrl })`): the decorator clears the primary's
65
+ * per-call `apiKey`/`headers`/`metadata` for every hop so a hop never leaks the primary's identity
66
+ * to a different provider.
67
+ */
16
68
  fallbacks: Array<{
17
69
  brain: Brain;
18
70
  model: Model;
19
71
  }>;
20
72
  };
73
+ /** Pull a degradation marker off a served message (used by the Runner to fill `TaskResult.degraded`). */
21
74
  export declare function readDegradation(msg: {
22
75
  diagnostics?: AssistantMessageDiagnostic[];
23
76
  } | undefined): DegradationInfo | undefined;
77
+ /**
78
+ * design/131 (codex 131 审 A) — resilience-standdown pass-through: forward one brain's stream
79
+ * verbatim, but keep the decorator discipline that a REJECTING inner brain (throw instead of an
80
+ * error event) still leaves a terminal on the returned stream — otherwise `result()` never
81
+ * resolves and the harness hangs (the same class as the degradation-brain blocker).
82
+ *
83
+ * HRD-BRN-5: that discipline covered only the REJECT shape. An inner stream ENDED BARE (`end()` with no
84
+ * terminal event) drained the `for await` loop and then pushed nothing, so `result()` stayed pending
85
+ * forever — the exact hang class this function's contract claims to prevent, and reached through the
86
+ * two standdown knobs (`resilience.allowFailover:false` / `allowDegrade:false`) that a benchmark or eval
87
+ * harness turns on to see a provider's TRUE failure shape. Standing resilience down was therefore
88
+ * strictly MORE hang-prone than leaving it on, since the normal failover path awaits `inner.result()`
89
+ * and lands in its catch. Both shapes now leave exactly one terminal.
90
+ */
24
91
  export declare function passthroughStream(brain: Brain, model: Model, context: Parameters<Brain["stream"]>[1], options: Parameters<Brain["stream"]>[2]): ReturnType<Brain["stream"]>;
25
92
  export declare function createDegradingBrain(opts: DegradingBrainOptions): Brain;
26
93
  export {};
@@ -1,16 +1,58 @@
1
+ /**
2
+ * Structured brain error so the *kind* of failure is machine-distinguishable end-to-end (the message
3
+ * is prefixed `[code]`, which the Runner lifts into `TaskResult.errorCode`). This lets an external
4
+ * caller react correctly without string-matching: `auth` → the API key is wrong, **stop and fix it**
5
+ * (it's not retried, so the caller gets a fast failure); `rate_limit` → back off; `network`/`server`
6
+ * → a transient outage worth retrying. Only `network`/`server`/`rate_limit` are retried by the brains.
7
+ */
1
8
  import type { Usage } from "../internal/llm.js";
9
+ /** A zeroed `Usage` for synthetic error/short-circuit assistant messages (no tokens spent). Shared by
10
+ * the circuit-breaker, degradation, and routing brains so the empty-usage shape lives in one place. */
2
11
  export declare const ZERO_USAGE: Usage;
12
+ /** The single source of truth for brain error codes — the type, the `[code]` parser, and the prefix
13
+ * stripper all derive from this one list, so adding a code can't silently diverge across call sites.
14
+ *
15
+ * The last three are IN-BAND terminal-output codes ([1086]③): stamped on errored assistant MESSAGES
16
+ * (never thrown as BrainError) so `TaskResult.errorCode` covers the error family end-to-end and
17
+ * downstream consumers can bucket without string-matching. Deliberately behavior-neutral everywhere
18
+ * else: the circuit breaker's default countCodes excludes them (model-output problems, not provider
19
+ * outages), degradation maps them to nothing, and subagent retry classification keeps them in the
20
+ * non-retryable "logic" bucket — exactly how these previously-uncoded messages already behaved.
21
+ * - `stream_torn` — the stream ended with no content and no finish/stop reason (response lost)
22
+ * - `refusal` — policy refusal / provider content filter withheld the output
23
+ * - `length_empty` — max_tokens exhausted with no answer text (pairs with errorKind "length_empty") */
3
24
  declare const BRAIN_ERROR_CODES: readonly ["auth", "rate_limit", "invalid_request", "server", "network", "http", "stream_torn", "refusal", "length_empty"];
4
25
  export type BrainErrorCode = (typeof BRAIN_ERROR_CODES)[number];
26
+ /** The full code list as a value, exported for exhaustive drift guards (e.g. the `errorClassOf` copy in
27
+ * tool-errors.ts must classify every member — a code added here but missed there folds to "unknown"). */
5
28
  export declare const ALL_BRAIN_ERROR_CODES: readonly BrainErrorCode[];
29
+ /** The in-band terminal-output subset (see the list doc above). The circuit breaker collapses these
30
+ * to the legacy `"http"` bucket before counting (codex [1086]③ 审): its taxonomy is TRANSPORT-level,
31
+ * and before these codes existed the same failures reached it as the unprefixed→"http" fallback — a
32
+ * custom `countCodes: ["http"]` policy must keep counting them exactly as it always did. */
6
33
  export declare const IN_BAND_OUTPUT_CODES: ReadonlySet<BrainErrorCode>;
7
34
  export declare class BrainError extends Error {
8
35
  readonly code: BrainErrorCode;
9
36
  readonly status?: number;
10
37
  constructor(code: BrainErrorCode, detail: string, status?: number);
11
38
  }
39
+ /** Map an HTTP status to an error class. 401/403 = auth (don't retry); 429 = rate limit; 5xx = server. */
12
40
  export declare function classifyHttp(status: number): BrainErrorCode;
41
+ /** Lift the machine-readable code back out of a `[code] …` prefixed `errorMessage` (the single shared
42
+ * parser — circuit breaker, degradation, and the Runner all read the prefix this way, council #7). */
13
43
  export declare function extractErrorCode(errorMessage: string | undefined): BrainErrorCode | undefined;
44
+ /** Strip a leading `[code] ` prefix (including the trailing space) from an `errorMessage`, leaving the
45
+ * human text. Pairs with {@link extractErrorCode} so a caller can lift the code and clean the message
46
+ * without re-hardcoding the code list (the Runner does both when assembling `TaskResult`). */
14
47
  export declare function stripErrorCodePrefix(errorMessage: string): string;
48
+ /** RB-386③ ([2090]) — render a transport-level error WITHOUT folding away its cause chain. undici's
49
+ * `fetch` rejects with `TypeError("fetch failed", { cause })` where the CAUSE carries the actually
50
+ * actionable fact (`connect ECONNREFUSED …` / `getaddrinfo ENOTFOUND …` / `SocketError: other side
51
+ * closed` with a `code`); `String(e)` / `e.message` alone collapsed ALL THREE network-failure shapes
52
+ * (refused / DNS / mid-stream disconnect) into the same opaque "fetch failed", end to end (BrainError
53
+ * detail → TaskResult.errorMessage → bg-agent terminal notification / poll error). Walks the cause
54
+ * chain (bounded), appending each layer's `code:`-prefixed message; layers whose message the parent
55
+ * already contains are skipped (no duplicate noise). Falls back to the plain message for causeless
56
+ * errors — those call sites' output is byte-identical to before. */
15
57
  export declare function describeNetworkError(e: unknown): string;
16
58
  export {};
@@ -1,2 +1,17 @@
1
1
  import type { Brain } from "../core/types.js";
2
+ /**
3
+ * Compose several brains into one with ordered failover (primary → fallbacks).
4
+ *
5
+ * The happy path streams live from the first brain. A brain is only failed over to the next when it
6
+ * fails **before emitting any content** (e.g. the gateway is down / connection refused, OR a
7
+ * first-token timeout that fires after the stream opened but before any delta) — a clean upfront
8
+ * failure. The leading `start` event is **held back** until the first real content event, so an
9
+ * error between `start` and the first delta can still fail over without ever having forwarded a
10
+ * (then-duplicated) `start`. Once real content (text/thinking/tool) has streamed, the outcome
11
+ * (including a mid-stream error or abort) is propagated rather than restarted, so the consumer never
12
+ * sees duplicate `start`/text events. The last brain's result is always final.
13
+ *
14
+ * Each underlying brain keeps its own retry policy (e.g. `createOpenAIBrain({ maxRetries })`);
15
+ * failover is the cross-gateway layer on top.
16
+ */
2
17
  export declare function createFailoverBrain(brains: Brain[]): Brain;
@@ -1,13 +1,52 @@
1
+ /**
2
+ * Media degradation shared by the two message assemblers (anthropic.ts / openai.ts).
3
+ *
4
+ * Both lanes have to answer the same two questions on every request — "may this model see images?"
5
+ * and "what do I say when a media block cannot ride along?" — and both used to answer them with
6
+ * their own copy of the predicate and their own copy of the sentence. One construction point:
7
+ * a capability rule that drifts between lanes is a silent per-provider behavior difference, and a
8
+ * placeholder sentence that drifts is a string consumers grep for.
9
+ */
1
10
  import type { Model } from "../internal/llm.js";
11
+ /**
12
+ * Whether the SERVING model accepts image input (`Model.input` contains "image").
13
+ *
14
+ * An ABSENT `input` is deliberately permissive (vision on): the field is caller-supplied metadata,
15
+ * and treating "not declared" as "not capable" would silently downgrade every caller who never
16
+ * filled it in. A caller that genuinely serves a text-only endpoint declares `input: ["text"]` and
17
+ * gets the placeholder path — the case a text-only API rejects with a hard 400 on an image part.
18
+ */
2
19
  export declare function modelSupportsVision(model?: Model): boolean;
20
+ /** Placeholder for an image block dropped because the serving model declares no image input. */
3
21
  export declare const IMAGE_OMITTED_NO_VISION = "[image omitted: the serving model does not support image input]";
22
+ /** {@link IMAGE_OMITTED_NO_VISION}, counted — a batch of dropped images states how many were lost. */
4
23
  export declare function imagesOmittedNoVisionNote(count: number): string;
24
+ /** An image content block carrying both wire fields — the only shape any lane can actually send. */
5
25
  export interface SendableImage {
6
26
  type: "image";
7
27
  data: string;
8
28
  mimeType: string;
9
29
  }
30
+ /**
31
+ * The blocks that would ride as REAL image media: `type:"image"` with both wire fields present.
32
+ *
33
+ * One predicate for both lanes and for both of its uses — deciding what to SEND and counting what was
34
+ * DROPPED. A block missing `data`/`mimeType` is discarded by every assembler on every path, error or
35
+ * not, so an omission note that counted it would blame the error for a loss it did not cause.
36
+ */
10
37
  export declare function sendableImages(blocks: readonly unknown[]): SendableImage[];
38
+ /**
39
+ * Disclosure for media blocks stripped out of an ERROR tool result.
40
+ *
41
+ * The stripping itself is mandatory on both lanes and is NOT a choice this note softens: the
42
+ * Anthropic API rejects an image inside an `is_error` tool_result outright (CC messages.ts, image-in-error rejection —
43
+ * a passthrough attempt 400s the request forever, not once), and the OpenAI-compatible `tool` role
44
+ * carries text only, with the synthetic image-carrier user message deliberately not built for error
45
+ * results. What the note fixes is the SILENCE: an error whose attached evidence simply vanished
46
+ * reads to the model as an error that never had any, so it cannot ask for the evidence another way.
47
+ *
48
+ * @returns the note, or `undefined` when there is nothing to disclose (no media was dropped).
49
+ */
11
50
  export declare function errorResultMediaNote(counts: {
12
51
  images: number;
13
52
  documents: number;
@@ -1,4 +1,35 @@
1
+ /**
2
+ * First-party model presets (design/119, CC 2.1.198 rebaseline).
3
+ *
4
+ * sema stays caller-injects-`Model` by design (no baked catalog — the CC catalog/alias/family layer
5
+ * is a product surface we deliberately don't carry). What IS worth shipping is the per-model
6
+ * CAPABILITY facts a caller can't guess from the docs page: the Fable-5-class wire contract
7
+ * (adaptive thinking form, effort tiers, temperature rejection) that a wrong guess turns into a
8
+ * hard 400. These presets are DATA, not mechanism — every field can be overridden by the caller.
9
+ *
10
+ * Pricing is deliberately NOT baked (CC 198 doesn't bake it either): `cost` defaults to zeros and a
11
+ * deployment that wants cost accounting fills in the current official per-MTok rates.
12
+ */
1
13
  import type { AnthropicMessagesCompat, Model } from "../internal/llm.js";
14
+ /**
15
+ * The Fable-5-class Anthropic wire contract (CC 2.1.198 capability bits, design/119 P0):
16
+ * - `thinkingMode: "adaptive"` — `thinking: { type: "adaptive" }`, NO budget_tokens (400 on budget).
17
+ * - `effortLevels` — the full five-tier `output_config.effort` range (fable-5 has `xhigh_effort` +
18
+ * `max_effort`; a model without those bits should declare a shorter list and higher requests clamp).
19
+ * - `supportsTemperature: false` — CC never sends temperature to this class, thinking on OR off.
20
+ */
2
21
  export declare const FABLE_5_COMPAT: AnthropicMessagesCompat;
22
+ /**
23
+ * Fable-5 behavioral guidance (CC 2.1.198 `fable_5_mitigations` — Anthropic's own runtime patches
24
+ * for this model class's known behavior pitfalls, adapted; design/119 S3). Carried on the Model as
25
+ * `promptGuidance` DATA — the injection mechanism (`Model.promptGuidance` → system-prompt tail) is
26
+ * generic and model-name-free.
27
+ */
3
28
  export declare const FABLE_5_PROMPT_GUIDANCE: string[];
29
+ /**
30
+ * A ready-to-use `claude-fable-5` {@link Model} (CC 2.1.198 registry facts: 1M-token native context
31
+ * window, 64k default max output — the 128k tier is opt-in via `maxTokens` override, knowledge
32
+ * cutoff Jan 2026, `default_effort: "high"`). Override anything per deployment; set `cost` for
33
+ * accounting (not baked — see module note).
34
+ */
4
35
  export declare function fable5Model(overrides?: Partial<Model>): Model;
@@ -1,11 +1,30 @@
1
1
  import type { Brain } from "../core/types.js";
2
2
  import { type StreamEngineConfig } from "./stream-engine.js";
3
3
  export interface OpenResponsesBrainConfig extends StreamEngineConfig {
4
+ /** Base URL of the Open Responses endpoint, WITHOUT the trailing `/responses`. Overridden by `model.baseUrl`. */
4
5
  baseUrl?: string;
6
+ /** API key. Overridden by per-call `options.apiKey`. */
5
7
  apiKey?: string;
8
+ /** Extra headers merged into every request (auth + content-type are hard-locked after the merge). */
6
9
  headers?: Record<string, string>;
10
+ /** Inject a custom fetch (tests / proxies). Defaults to global fetch. */
7
11
  fetchImpl?: typeof fetch;
12
+ /**
13
+ * Replay prior assistant reasoning items back to the endpoint on the turns that carry tool calls
14
+ * (see the file header — an endpoint in thinking mode REQUIRES it there and ignores it elsewhere).
15
+ * **On by default.** Set `false` only for an endpoint that rejects the `reasoning` input item;
16
+ * with it off, a thinking-mode endpoint refuses every replayed tool-call turn.
17
+ */
8
18
  replayReasoning?: boolean;
19
+ /**
20
+ * Detect **degenerate repetition** (the model looping on the same char/phrase forever) mid-stream
21
+ * and cut it off — the turn ends `error` (`errorKind:"degenerate"`) so the loop stops paying.
22
+ * Default true. Same detector, same cadence, same salvage rules as the other two lanes.
23
+ */
9
24
  detectRepetition?: boolean;
10
25
  }
26
+ /**
27
+ * Create a Brain that talks to an Open Responses endpoint. See the file header for the stateless
28
+ * invariant, the capability-audit posture, and the reasoning-replay rule.
29
+ */
11
30
  export declare function createOpenResponsesBrain(config?: OpenResponsesBrainConfig): Brain;
@@ -1,13 +1,59 @@
1
1
  import type { Brain } from "../core/types.js";
2
2
  import { type StreamEngineConfig } from "./stream-engine.js";
3
3
  export interface OpenAIBrainConfig extends StreamEngineConfig {
4
+ /** Base URL of your OpenAI-compatible gateway (without /chat/completions). Overridden by model.baseUrl if set. */
4
5
  baseUrl?: string;
6
+ /** API key. Overridden by per-call options.apiKey / getApiKeyAndHeaders. */
5
7
  apiKey?: string;
8
+ /** Extra headers merged into every request. */
6
9
  headers?: Record<string, string>;
10
+ /** Inject a custom fetch (tests / proxies). Defaults to global fetch. */
7
11
  fetchImpl?: typeof fetch;
12
+ /**
13
+ * For weaker models that emit tool calls as TEXT (`<tool_call>{...}</tool_call>` / fenced json)
14
+ * instead of native tool calls: promote them to real tool calls. Off by default. Native models
15
+ * don't need this.
16
+ */
8
17
  repairTextToolCalls?: boolean;
18
+ /**
19
+ * Replay assistant `reasoning_content` back to the provider on follow-up requests (design/46).
20
+ * **On by default**, and **conditional**: thinking is replayed only on prior assistant **tool-call**
21
+ * turns — DeepSeek V4 **requires** it there (else it errors/degrades), while non-tool turns ignore it,
22
+ * so replaying there only bloats the context window (prefix-cache cuts the *cost* of that bloat but not
23
+ * the *window occupancy* → earlier compaction). Replaying just the tool-call turns is correctness-
24
+ * equivalent and leaner. Set `false` to never replay (e.g. a provider that rejects the field).
25
+ * Anthropic uses `createAnthropicBrain`, which always replays thinking blocks with their signature.
26
+ */
9
27
  replayThinking?: boolean;
28
+ /**
29
+ * Detect **degenerate repetition** (the model looping on the same char/phrase forever) mid-stream
30
+ * and cut it off — the turn ends `error` ("degenerate repetition") so the loop stops paying and a
31
+ * team member's looped output is treated as a failed turn, not a real statement. Default true.
32
+ */
10
33
  detectRepetition?: boolean;
11
34
  }
35
+ /**
36
+ * Wire-field inference for the per-reply output cap when the model declares no explicit
37
+ * `compat.maxTokensField`. Newer stock-OpenAI model families REJECT `max_tokens` with a 400
38
+ * ("Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens'
39
+ * instead."): the o-series reasoning models (o1/o3/o4 and their -mini/-pro/dated variants), the gpt-5
40
+ * family, and chatgpt-4o. Everything else — older OpenAI models AND the long tail of third-party
41
+ * OpenAI-COMPATIBLE endpoints (vLLM, DeepSeek, llama.cpp, gateways) — keeps `max_tokens`, because many
42
+ * compat endpoints only recognize that spelling. Heuristic rules (deliberately conservative — an id the
43
+ * table can't confidently classify keeps the widely-supported `max_tokens`):
44
+ * - `gpt-5…` → max_completion_tokens (gpt-5, gpt-5-mini, gpt-5.x, …)
45
+ * - `chatgpt-4o…` → max_completion_tokens (chatgpt-4o-latest)
46
+ * - `o1|o3|o4` (+ `-`/`.` suffix or bare) → max_completion_tokens (o1-preview, o3-mini, o4-mini, …)
47
+ * - anything else → max_tokens (gpt-4o/gpt-4.x accept both; third-party ids often ONLY this)
48
+ * An explicit `compat.maxTokensField` always wins over this inference. Exported so shells constructing
49
+ * Models from bare ids (e.g. the TB entry) can bake the same inference into compat metadata.
50
+ */
12
51
  export declare function inferMaxTokensField(modelId: string): "max_completion_tokens" | "max_tokens";
52
+ /**
53
+ * Create a Brain that talks to an OpenAI-compatible chat-completions endpoint (your model gateway).
54
+ * Translates the unified Context into an OpenAI request and the streamed response back into the unified
55
+ * AssistantMessageEvent protocol, including native tool calls. The connect/retry/timeout/read-loop
56
+ * machinery lives in the shared {@link runStreamingBrain} engine (design/32); this adapter owns the
57
+ * OpenAI request shaping + chat-completions SSE parsing + finalization.
58
+ */
13
59
  export declare function createOpenAIBrain(config?: OpenAIBrainConfig): Brain;