@sema-agent/core 5.20.0 → 5.21.1

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 (313) hide show
  1. package/CHANGELOG.md +19 -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-search-tools.js +0 -1
  292. package/dist/tools/fs/fs-shared.d.ts +360 -0
  293. package/dist/tools/fs/fs-write.d.ts +16 -0
  294. package/dist/tools/fs/gh-rate-limit.d.ts +22 -0
  295. package/dist/tools/fs/index.d.ts +79 -0
  296. package/dist/tools/fs/notebook.d.ts +56 -0
  297. package/dist/tools/fs/pdf.d.ts +70 -0
  298. package/dist/tools/fs/pdf.js +8 -2
  299. package/dist/tools/fs/repo-map.d.ts +10 -0
  300. package/dist/tools/fs/safety.d.ts +376 -0
  301. package/dist/tools/fs/search.d.ts +131 -0
  302. package/dist/tools/loop-tick.d.ts +24 -0
  303. package/dist/tools/monitor.d.ts +55 -0
  304. package/dist/tools/scheduler-tools.d.ts +51 -0
  305. package/dist/tools/sql-adapters.d.ts +18 -0
  306. package/dist/tools/sql.d.ts +25 -0
  307. package/dist/tools/task-list.d.ts +77 -0
  308. package/dist/tools/todo.d.ts +8 -0
  309. package/dist/tools/web.d.ts +184 -0
  310. package/dist/tools/worktree.d.ts +81 -0
  311. package/package.json +2 -2
  312. package/dist/tools/gitea-issue.d.ts +0 -13
  313. package/dist/tools/gitea-issue.js +0 -75
@@ -8,6 +8,12 @@ export type ImagesApi = KnownImagesApi | (string & {});
8
8
  export type Provider = string;
9
9
  export type KnownImagesProvider = "openrouter";
10
10
  export type ImagesProvider = string;
11
+ /**
12
+ * Effort/intensity TIERS (no "off" — this is the value a provider effort field takes). ⚠ Name clash
13
+ * by history with the loop-layer `ThinkingLevel` (engine/loop/types.ts), which is the SEVEN-value
14
+ * on/off+tier knob ("off" | these six). Rule of thumb: harness/task config uses the loop's 7-tier
15
+ * type; provider compat fields (`reasoningEffortLevels`/`effortLevels`) use this 6-tier one.
16
+ */
11
17
  export type ThinkingLevel = "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
12
18
  export type ModelThinkingLevel = "off" | ThinkingLevel;
13
19
  export type ThinkingLevelMap = Partial<Record<ModelThinkingLevel, string | null>>;
@@ -18,52 +24,191 @@ export interface ProviderResponse {
18
24
  status: number;
19
25
  headers: Record<string, string>;
20
26
  }
27
+ /**
28
+ * design/131 — per-task resilience overrides (intent flags, NOT decorator config). A bench/eval or
29
+ * critical task can say "fail rather than fall back" without any new global switch; the deployment's
30
+ * decorator stack stays the single topology owner. All default to today's behavior when absent.
31
+ */
21
32
  export interface ResilienceOptions {
33
+ /** false = this task forbids reactive model DEGRADE (the degrading brain passes the failure through). */
22
34
  allowDegrade?: boolean;
35
+ /** false = this task forbids cross-gateway FAILOVER (only the primary brain is tried). */
23
36
  allowFailover?: boolean;
37
+ /** true = this task ignores an OPEN circuit breaker's fast-fail (the probe goes through; outcomes
38
+ * are STILL recorded so shared observation is undiminished). Operator-facing — an open breaker
39
+ * exists to protect the provider; bypass only where true failure shape matters (benchmarks). */
24
40
  bypassBreaker?: boolean;
25
41
  }
42
+ /** 1.296 件A — per-call advisory stall-watchdog values (see {@link StreamOptions.stallTimeouts}). */
26
43
  export interface StallTimeouts {
44
+ /** Advisory connect watchdog (ms) — bounds the fetch→response-headers wait (件1a: a gateway that
45
+ * never returns headers is invisible to every post-headers watchdog, including the absolute
46
+ * deadline timer). Fires as the brain's existing retryable `network` connect timeout. */
27
47
  connectMs?: number;
48
+ /** Advisory first-token watchdog (ms) — first thinking delta counts as the first token. */
28
49
  firstTokenMs?: number;
50
+ /** Advisory mid-stream idle watchdog (ms) — re-armed on every delta after the first. */
29
51
  idleMs?: number;
30
52
  }
31
53
  export interface StreamOptions {
32
54
  temperature?: number;
33
55
  maxTokens?: number;
56
+ /**
57
+ * Stop sequences forwarded to providers that support them. Providers map this
58
+ * to their native request field, such as OpenAI `stop` or Anthropic
59
+ * `stop_sequences`.
60
+ */
34
61
  stop?: string[];
35
62
  signal?: AbortSignal;
36
63
  apiKey?: string;
64
+ /**
65
+ * Preferred transport for providers that support multiple transports.
66
+ * Providers that do not support this option ignore it.
67
+ */
37
68
  transport?: Transport;
69
+ /**
70
+ * Prompt cache retention preference. Providers map this to their supported values.
71
+ * Default: "short".
72
+ */
38
73
  cacheRetention?: CacheRetention;
74
+ /**
75
+ * Optional session identifier for providers that support session-based caching.
76
+ * Providers can use this to enable prompt caching, request routing, or other
77
+ * session-aware features. Ignored by providers that don't support it.
78
+ */
39
79
  sessionId?: string;
80
+ /**
81
+ * Optional provider prompt-cache affinity key, distinct from transcript/session identity.
82
+ * Providers that do not support separate cache affinity ignore it.
83
+ */
40
84
  promptCacheKey?: string;
85
+ /**
86
+ * Optional callback for inspecting or replacing provider payloads before sending.
87
+ * Return undefined to keep the payload unchanged.
88
+ */
41
89
  onPayload?: (payload: unknown, model: Model) => MaybePromise<unknown>;
90
+ /**
91
+ * Optional callback invoked after an HTTP response is received and before
92
+ * its body stream is consumed.
93
+ */
42
94
  onResponse?: (response: ProviderResponse, model: Model) => void | Promise<void>;
95
+ /**
96
+ * Optional custom HTTP headers to include in API requests.
97
+ * Merged with provider defaults; can override default headers.
98
+ * Not supported by all providers (e.g., AWS Bedrock uses SDK auth).
99
+ */
43
100
  headers?: Record<string, string>;
101
+ /**
102
+ * HTTP request timeout in milliseconds for providers/SDKs that support it.
103
+ * For example, OpenAI and Anthropic SDK clients default to 10 minutes.
104
+ */
44
105
  timeoutMs?: number;
106
+ /**
107
+ * service [405] P0 — true when `maxTokens` on THIS call was DYNAMICALLY SHRUNK by the wall-clock
108
+ * cap (design/130 P1), not statically configured. A provider hitting max_tokens with ONLY
109
+ * reasoning output should then finish as a RECOVERABLE `length` stop (the loop's truncated-output
110
+ * continue picks it up; the next call is cap-exempt via the runtime reasoning observation) instead
111
+ * of the static-config fail-loud error — under a dynamic cap the truncation is the ENGINE's doing,
112
+ * not a deployment mistake.
113
+ */
45
114
  maxTokensDynamic?: boolean;
115
+ /**
116
+ * Blackboard [477] — the STATIC leg of the [405] dynamicCut family. True = the caller (the agent
117
+ * loop) is prepared to recover a `length` stop, so a provider hitting the STATIC max_tokens with
118
+ * ONLY reasoning output (a budget-ignoring thinking model — e.g. a Qwen gateway that ignores the
119
+ * thinking control plane and eats the whole static budget in one thought) may finish as a
120
+ * RECOVERABLE `length` stop tagged `staticReasoningCut` instead of the fail-loud config error.
121
+ * The loop grants this only while its per-run stop-loss budget lasts (2 downgrades), then stops
122
+ * passing it — the third truncation fails loud again (no infinite truncate/continue burn).
123
+ * Absent/false ⇒ today's behavior: reasoning-only static max_tokens is a fail-loud error (a
124
+ * genuine misconfiguration must stay loud — e.g. the compaction summarizer relies on the
125
+ * `length_empty` errorKind to escalate its budget).
126
+ */
46
127
  staticReasoningCutDowngrade?: boolean;
128
+ /**
129
+ * design/131 (service [404] 拍) — per-task resilience INTENT flags, threaded per call so the
130
+ * resilience decorator stack (degrading / failover / circuit-breaker) can stand aside for THIS
131
+ * task. Intent-only: no decorator topology rides the wire; each layer reads the flag it owns and
132
+ * defaults to today's behavior when absent. See design/131-per-task-resilience-overrides.md.
133
+ */
47
134
  resilience?: ResilienceOptions;
135
+ /**
136
+ * 1.296 件A — per-call ADVISORY stall watchdogs, supplied by the engine on every call so a SILENT
137
+ * stream cannot hang the run: they bound the first-token wait and mid-stream silence with the
138
+ * brain's existing retryable `network` stall machinery — TB2.0 run89: 680s of
139
+ * zero deltas. ADVISORY, not an override: a brain whose construction-time `BrainTimeoutConfig`
140
+ * sets the corresponding field keeps it — deployment sovereignty, including an explicit
141
+ * 0/negative meaning "deliberately disabled" — and only an ABSENT (undefined) field adopts the
142
+ * per-call value. Priority chain: brain explicit config > this per-call advisory > off.
143
+ * `firstTokenMs` is reasoning-safe: the first THINKING delta already counts as the first token
144
+ * (see BrainTimeoutConfig.firstTokenTimeoutMs, design/17 O5).
145
+ */
48
146
  stallTimeouts?: StallTimeouts;
147
+ /**
148
+ * Maximum retry attempts for providers/SDKs that support client-side retries.
149
+ * For example, OpenAI and Anthropic SDK clients default to 2.
150
+ */
49
151
  maxRetries?: number;
152
+ /**
153
+ * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
154
+ * If the server's requested delay exceeds this value, the request fails immediately
155
+ * with an error containing the requested delay, allowing higher-level retry logic
156
+ * to handle it with user visibility.
157
+ * Default: 60000 (60 seconds). Set to 0 to disable the cap.
158
+ */
50
159
  maxRetryDelayMs?: number;
160
+ /**
161
+ * Optional metadata to include in API requests.
162
+ * Providers extract the fields they understand and ignore the rest.
163
+ * For example, Anthropic uses `user_id` for abuse tracking and rate limiting.
164
+ */
51
165
  metadata?: Record<string, unknown>;
52
166
  }
53
167
  export type ProviderStreamOptions = StreamOptions & Record<string, unknown>;
54
168
  export interface ImagesOptions {
55
169
  signal?: AbortSignal;
56
170
  apiKey?: string;
171
+ /**
172
+ * Optional callback for inspecting or replacing provider payloads before sending.
173
+ * Return undefined to keep the payload unchanged.
174
+ */
57
175
  onPayload?: (payload: unknown, model: ImagesModel) => MaybePromise<unknown>;
176
+ /**
177
+ * Optional callback invoked after an HTTP response is received.
178
+ */
58
179
  onResponse?: (response: ProviderResponse, model: ImagesModel) => void | Promise<void>;
180
+ /**
181
+ * Optional custom HTTP headers to include in API requests.
182
+ * Merged with provider defaults; can override default headers.
183
+ */
59
184
  headers?: Record<string, string>;
185
+ /**
186
+ * HTTP request timeout in milliseconds for providers/SDKs that support it.
187
+ */
60
188
  timeoutMs?: number;
189
+ /**
190
+ * Maximum retry attempts for providers/SDKs that support client-side retries.
191
+ */
61
192
  maxRetries?: number;
193
+ /**
194
+ * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
195
+ * If the server's requested delay exceeds this value, the request fails immediately
196
+ * with an error containing the requested delay, allowing higher-level retry logic
197
+ * to handle it with user visibility.
198
+ * Default: 60000 (60 seconds). Set to 0 to disable the cap.
199
+ */
62
200
  maxRetryDelayMs?: number;
201
+ /**
202
+ * Optional metadata to include in API requests.
203
+ * Providers extract the fields they understand and ignore the rest.
204
+ */
63
205
  metadata?: Record<string, unknown>;
64
206
  }
65
207
  export type ProviderImagesOptions = ImagesOptions & Record<string, unknown>;
66
208
  export interface SimpleStreamOptions extends StreamOptions {
209
+ /** [1076]③a: widened to include the explicit "off" — an off that reaches the wire layer lets the
210
+ * brains emit the provider DISABLE key on binary enable formats (default-on Qwen gateways reason
211
+ * on absence, so absence ≠ off there). Both brains guard: off never enables thinking. */
67
212
  reasoning?: ModelThinkingLevel;
68
213
  }
69
214
  export type StreamFunction<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> = (model: Model<TApi>, context: Context, options?: TOptions) => AssistantMessageEventStreamContract;
@@ -76,6 +221,9 @@ export interface ThinkingContent {
76
221
  type: "thinking";
77
222
  thinking: string;
78
223
  thinkingSignature?: string;
224
+ /** When true, the thinking content was redacted by safety filters. The opaque
225
+ * encrypted payload is stored in `thinkingSignature` so it can be passed back
226
+ * to the API for multi-turn continuity. */
79
227
  redacted?: boolean;
80
228
  }
81
229
  export interface ImageContent {
@@ -83,6 +231,11 @@ export interface ImageContent {
83
231
  data: string;
84
232
  mimeType: string;
85
233
  }
234
+ /** A binary document payload (today: PDF only — `application/pdf`). Produced by the Read tool's PDF
235
+ * branch (CC FileReadTool parity: the file is sent to the model as a native `document` content block
236
+ * so an Anthropic-family model reads the text layer directly). Provider support is uneven: the
237
+ * anthropic brain forwards it as `{type:"document",source:{type:"base64",…}}`; the openai brain has
238
+ * no equivalent block and substitutes an honest text placeholder (never a silent drop). */
86
239
  export interface DocumentContent {
87
240
  type: "document";
88
241
  data: string;
@@ -110,23 +263,120 @@ export interface Usage {
110
263
  };
111
264
  }
112
265
  export type StopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
266
+ /**
267
+ * design/171 §6.1 — WHO a piece of human input came from, as an attribution label. THE single
268
+ * definition, at its layering-legal home (the engine cannot import core): the persisted steer
269
+ * queue (`core/checkpoint-store`) RE-EXPORTS this type, so the live message seat and the parked
270
+ * entry can never drift apart.
271
+ *
272
+ * **Normative:** an actor NEVER participates in any permission / approval / scope decision — authority
273
+ * belongs to the principal, always. This is display-and-audit provenance, nothing more.
274
+ *
275
+ * `hostAsserted` must be derived by the host from INGRESS CREDENTIALS and must never be taken from a
276
+ * request body (same rule the parked steer queue's `trusted` flag already follows: the service computes
277
+ * it from a verified principal, the core stores it VERBATIM and never recomputes it). Enforcement lives
278
+ * at the ingress that mints the assertion; the core's job is to carry it unchanged.
279
+ */
113
280
  export interface ActorAssertion {
281
+ /** Namespaced stable subject id (`"slack:U123"` / `"sso:alice@example.com"`) — the namespace prevents
282
+ * two ingresses from colliding on the same raw id. */
114
283
  id: string;
284
+ /** True iff the HOST derived this identity from ingress credentials. `false` = an unverified
285
+ * self-claim, which a renderer must mark as such; never settable from a request body. */
115
286
  hostAsserted: boolean;
287
+ /** Who asserted it (Slack app id, SSO IdP, …) — present when the host can name its ingress. */
116
288
  issuer?: string;
117
289
  }
290
+ /** design/171 — the ONE canonical copy of an {@link ActorAssertion}: exactly the three contract
291
+ * fields, a fresh object. Every seat that RETAINS an assertion (message mint, event build, steer
292
+ * acceptance) snapshots through here, so a caller mutating its own object after the call — or
293
+ * riding junk extra keys on it — can never rewrite persisted attribution. */
118
294
  export declare function snapshotActorAssertion(actor: ActorAssertion): ActorAssertion;
119
295
  export interface UserMessage {
120
296
  role: "user";
121
297
  content: string | (TextContent | ImageContent)[];
122
298
  timestamp: number;
299
+ /**
300
+ * [c209-C] codex 收口 C1/C2 — EXACT character length of the ENGINE-PREPENDED prefix on this
301
+ * user-lane message (first-frame listing/`<skills>` reminders + a UserPromptSubmit
302
+ * additionalContext reminder ahead of the objective; the trusted engine-authored head of a resume
303
+ * continuation). Derived views that re-present user messages under a `[user]`/`[User]:` label
304
+ * (auto-mode classifier window, compaction summarizer input) slice EXACTLY this many chars off the
305
+ * head — metadata, never shape-guessing, so a user who legitimately opens their own prompt with a
306
+ * `<system-reminder>` block is NEVER mis-stripped. Additive schema field: absent on old sessions
307
+ * (⇒ rendered verbatim — conservative direction: a classifier seeing engine listings is
308
+ * acceptable, losing real user text is not). Never sent to a provider (brains rebuild wire
309
+ * messages field-by-field).
310
+ */
123
311
  enginePrefixChars?: number;
312
+ /**
313
+ * [c209-C] R4 codex 终判 — the ENGINE-TRUSTED SEGMENTS of this user-lane message, as half-open
314
+ * `[start, end)` UTF-16 code-unit ranges into the flattened text content (ascending,
315
+ * non-overlapping). Generalizes {@link UserMessage.enginePrefixChars} beyond the head: the resume
316
+ * continuation preserves ISSUE ORDER (parked steer first, wake message second — the public
317
+ * contract on ResumeOutcome `wake` / ResumeRun / the resume entry, which a custom Brain may rely
318
+ * on to read "the last state that appears"), so a TRUSTED engine `<system-reminder>` frame can
319
+ * legally sit AFTER an untrusted fenced segment; each such frame is recorded as its own segment
320
+ * wherever it lands. Derived views treat segment bytes as engine guidance (auto-mode window:
321
+ * neutral note, never `[user]`; compaction serializer: stripped) and everything OUTSIDE the
322
+ * segments verbatim under user authority.
323
+ *
324
+ * Relationship with `enginePrefixChars`: ONE of the two per message — `enginePrefixChars` is
325
+ * retained as sugar for the single head segment `[0, chars)` (first-frame listings / prompt-hook
326
+ * context, where the engine bytes are a pure prefix); when both are present (foreign/corrupt
327
+ * data), `engineSegments` WINS and the prefix field is ignored. Malformed ranges (non-integer,
328
+ * out of range, descending/overlapping) invalidate the whole field ⇒ verbatim render
329
+ * (conservative direction, same as an out-of-range prefix). Same additive / old-session-verbatim /
330
+ * never-on-the-wire posture as `enginePrefixChars`.
331
+ */
124
332
  engineSegments?: ReadonlyArray<{
125
333
  start: number;
126
334
  end: number;
127
335
  }>;
336
+ /**
337
+ * [c209-C] codex 收口 C1/C2 — this ENTIRE message is engine-minted guidance (deadline nudges,
338
+ * graceful-finalize write-out steers, boundary attachment bundles, final-verification / stop-hook
339
+ * reminders), not user speech. Derived views must not present it under `[user]` authority
340
+ * (auto-mode window: neutral annotation; compaction serialization: skipped). Same additive /
341
+ * old-session-verbatim / never-on-the-wire posture as {@link UserMessage.enginePrefixChars}.
342
+ *
343
+ * [c209-C] R4 codex 终判 — MUTUALLY EXCLUSIVE with {@link UserMessage.provenance}: a message is
344
+ * either wholly SKIPPABLE (`engineMinted`) or MUST-STAY-VISIBLE (`provenance:"engine-note"`),
345
+ * never both. The exclusion is enforced at runtime (mint clamp in the harness'
346
+ * `createUserMessage`, normalization at the session import gate) and defensively at every
347
+ * projection: a double-stamped message is treated as `engine-note` — the must-stay-visible
348
+ * invariant outranks the may-skip one (dropping visible content is the unrecoverable direction).
349
+ */
128
350
  engineMinted?: true;
351
+ /**
352
+ * [c209-C] R3 codex 收口 — the "visible but not the user" THIRD state. This message is an
353
+ * ENGINE-INJECTED note whose CONTENT the model must read (LSP `<new-diagnostics>` blocks,
354
+ * task-notification frames, TaskStream steering, dynamic memory re-recall, loop recovery
355
+ * guidance), but which is NOT user speech. Two-state contrast with {@link UserMessage.engineMinted}:
356
+ * - `engineMinted` ⇒ engine guidance whose content derived views may SKIP ENTIRELY
357
+ * (nudges/finalize/attachment bundles — re-delivered by their own
358
+ * machinery, no summary/classifier value);
359
+ * - `provenance:"engine-note"` ⇒ the content STAYS VISIBLE in derived views (the classifier /
360
+ * summarizer needs it to follow the run), but under a NEUTRAL
361
+ * engine label — never `[user]`/`[User]:` authority (an engine
362
+ * note must not read as user authorization).
363
+ * [c209-C] R4: the two are MUTUALLY EXCLUSIVE — see the exclusion note on
364
+ * {@link UserMessage.engineMinted} (double-stamp ⇒ `engine-note` wins everywhere).
365
+ * Same additive / old-session-verbatim / never-on-the-wire posture as the fields above.
366
+ */
129
367
  provenance?: "engine-note";
368
+ /**
369
+ * design/171 §5.2 — WHO spoke this user-lane message, when the session is shared by several people
370
+ * (thread-style multiplayer). Attribution metadata ONLY: absent = the caller supplied none
371
+ * (anonymous — every pre-171 session and every single-user host). Persisted on the message;
372
+ * NEVER sent to a provider (brains rebuild wire messages field-by-field, and
373
+ * {@link stripEngineMetadata} strips it for a custom Brain that whole-object-serializes). The
374
+ * model-facing rendering is the SPEAKER ENVELOPE minted by the single projection point
375
+ * (`projectHumanInput`) INTO the text content — this field is the machine-readable side. The
376
+ * session-import gate strips foreign values by default (an importer must not re-assert historical
377
+ * identity; operator-declared trusted imports may keep them). Same additive /
378
+ * old-session-verbatim posture as the engine-provenance fields above.
379
+ */
130
380
  actor?: ActorAssertion;
131
381
  }
132
382
  export interface AssistantMessage {
@@ -139,15 +389,64 @@ export interface AssistantMessage {
139
389
  responseId?: string;
140
390
  diagnostics?: AssistantMessageDiagnostic[];
141
391
  usage: Usage;
392
+ /** TB 尸检 T1-5 (codex 1.238 复审 F3): the provider never delivered a usage frame for this message (e.g. a
393
+ * degenerate-repetition cutoff cancelled the stream first) — `usage` above is a zero-synthesized shell.
394
+ * Consumers must treat the numbers as UNKNOWN, not zero. Absent ⇒ usage is provider-reported. */
142
395
  usageMissing?: true;
143
396
  stopReason: StopReason;
144
397
  errorMessage?: string;
398
+ /** Structured cause for `stopReason:"error"` a caller can react to programmatically (errorMessage is
399
+ * human-facing prose and NOT a contract). `"length_empty"` = a max_tokens cut that produced reasoning/
400
+ * scratch but NO answer text (both brains surface that as an error, not a "length" stop) — the compaction
401
+ * summary path escalates its token budget on it. Extend the union as new recoverable causes are classified.
402
+ *
403
+ * RB-464: `"degenerate"` is the DELIBERATE brain-side cut (the repetition loop). It used to be
404
+ * identifiable only by comparing `errorMessage` against the exported sentinel string
405
+ * `DEGENERATE_MESSAGE` across call sites in two layers — safer than prose matching, but still a
406
+ * string standing in for a typed terminal cause: any producer that builds the same text without
407
+ * importing the constant is silently invisible to every one of those sites. It is classified here
408
+ * instead, on the field whose own contract invites exactly this ("extend the union…"), rather than
409
+ * on a second parallel field — two typed causes for one `stopReason:"error"` would leave every
410
+ * reader asking which one is authoritative. `errorMessage` still carries the sentinel prose
411
+ * verbatim for display.
412
+ *
413
+ * ⚠️ Brain OBLIGATION (RB-482 #12, 5.1.0): stamping this field on every cut turn is part of the
414
+ * Brain contract — the sentinel-prose fallback readers are RETIRED, so a custom Brain that stamps
415
+ * only `errorMessage` prose is no longer recognized as a cut (terminal-cause.ts reads this field
416
+ * and nothing else). Widening note: exhaustive switches on this union gain arms as it grows. */
145
417
  errorKind?: "length_empty" | "degenerate";
418
+ /**
419
+ * design/124 tier A: this final message was PARTIALLY FINALIZED after a mid-stream connection
420
+ * loss/stall — the substantive streamed prefix (text and/or completed tool calls) was promoted to
421
+ * final content instead of failing the turn (CC 198 queryModelStreaming parity: avoid re-billing +
422
+ * keep the displayed content consistent with the result). `stopReason` is synthesized from the
423
+ * content ("toolUse" when a completed tool call streamed, else "stop"); `errorMessage` carries the
424
+ * CC-verbatim warning ("Response stalled mid-stream." / "Connection closed mid-response."), visible
425
+ * to the model in the transcript. Downstream semantics (agent-loop): `partialFinalized &&
426
+ * stopReason==="stop"` gets a BOUNDED continue nudge (an unattended run must not book the cut as an
427
+ * incomplete success); `partialFinalized && stopReason==="toolUse"` executes normally (a truncated
428
+ * trailing call was already dropped by the finalize malformed path). Additive — absent everywhere else.
429
+ */
146
430
  partialFinalized?: true;
431
+ /**
432
+ * Degenerate-repetition telemetry for THIS call (clay 2026-07-10: counts + detected segment, not just
433
+ * a boolean). `cut` = the event that cancelled the stream (always paired with the DEGENERATE_MESSAGE
434
+ * errorMessage); `spared` = repetitions that landed in a detection window but were exempted by a
435
+ * 2e1c161 structural allowance (code-line shape / divider run) — deduped per stream by rule+segment.
436
+ * The RSI raw material for judging whether the allowance is too wide or too narrow. Additive —
437
+ * absent when the detector never hit anything.
438
+ */
147
439
  repetition?: {
148
440
  cut?: RepetitionEvent;
149
441
  spared?: RepetitionEvent[];
150
442
  };
443
+ /**
444
+ * Blackboard [477]: this `length` stop is a DOWNGRADED reasoning-only STATIC max_tokens hit — the
445
+ * model spent the entire static output budget on thinking (budget-ignoring gateway shape) and the
446
+ * brain, granted `StreamOptions.staticReasoningCutDowngrade`, finished the turn as a recoverable
447
+ * `length` instead of the fail-loud config error. The agent loop counts these per run to enforce
448
+ * the 2-downgrade stop-loss. Additive — absent everywhere else (incl. the dynamicCut shape).
449
+ */
151
450
  staticReasoningCut?: true;
152
451
  timestamp: number;
153
452
  }
@@ -161,6 +460,16 @@ export interface ToolResultMessage<TDetails = unknown> {
161
460
  timestamp: number;
162
461
  }
163
462
  export type Message = UserMessage | AssistantMessage | ToolResultMessage;
463
+ /**
464
+ * RB-3 (campaign S4 carry): strip the engine-provenance metadata fields from user messages before
465
+ * serializing a Context to an external wire. The five fields (`enginePrefixChars`/`engineSegments`/
466
+ * `engineMinted`/`provenance`/`actor`, the last per design/171 §5.2) are INTERNAL coordination
467
+ * between the engine's minting side and its consumers (permission classifier, compaction summarizer,
468
+ * prompt suggestions, multiplayer attribution) — they must never reach a provider payload. The
469
+ * built-in brains construct their own wire shapes and are immune; a CUSTOM Brain that
470
+ * whole-object-serializes messages (`JSON.stringify(context.messages)`) would leak them — run the
471
+ * array through this projection first.
472
+ */
164
473
  export declare function stripEngineMetadata(messages: Message[]): Message[];
165
474
  export type ImagesInputContent = TextContent | ImageContent;
166
475
  export type ImagesOutputContent = TextContent | ImageContent;
@@ -182,13 +491,24 @@ export interface AssistantImages {
182
491
  import type { TSchema } from "typebox";
183
492
  export interface Tool<TParameters extends TSchema = TSchema> {
184
493
  name: string;
494
+ /** VENDORED EDIT (design/115 P0): canonical tool renames keep old model/SDK wire names as aliases. */
185
495
  aliases?: string[];
186
496
  description: string;
497
+ /** R2 双形轴 — classic-profile description variant (see ToolSpec.descriptionClassic). Swapped in
498
+ * for `description` at mount time when the run's promptProfile is "classic"; absent = one form. */
187
499
  descriptionClassic?: string;
188
500
  parameters: TParameters;
189
501
  }
190
502
  export interface Context {
191
503
  systemPrompt?: string;
504
+ /**
505
+ * Campaign S4 (prompt-assembly §5.4, ADDITIVE): the system prompt as PHYSICAL blocks with
506
+ * per-block cache-span boundaries. Compatibility projection duty (plan M13): when present,
507
+ * `systemPrompt` is ALWAYS also populated with the equivalent joined text — a Brain that only
508
+ * reads `systemPrompt` gets wire-equivalent input (single merged block), never a dropped prompt.
509
+ * Brains that understand blocks (Anthropic) materialize one system entry per block, ending a
510
+ * prompt-cache span where `cacheControlBoundary` is set. Absent ⇒ legacy single-string face.
511
+ */
192
512
  systemBlocks?: Array<{
193
513
  text: string;
194
514
  cacheControlBoundary: boolean;
@@ -196,6 +516,14 @@ export interface Context {
196
516
  messages: Message[];
197
517
  tools?: Tool[];
198
518
  }
519
+ /**
520
+ * Event protocol for AssistantMessageEventStream.
521
+ *
522
+ * Streams should emit `start` before partial updates, then terminate with either:
523
+ * - `done` carrying the final successful AssistantMessage, or
524
+ * - `error` carrying the final AssistantMessage with stopReason "error" or "aborted"
525
+ * and errorMessage.
526
+ */
199
527
  export type AssistantMessageEvent = {
200
528
  type: "start";
201
529
  partial: AssistantMessage;
@@ -203,7 +531,13 @@ export type AssistantMessageEvent = {
203
531
  type: "text_start";
204
532
  contentIndex: number;
205
533
  partial: AssistantMessage;
206
- } | {
534
+ }
535
+ /**
536
+ * VENDORED EDIT (upstream cherry-pick 6fcc945702, monthly diff 2026-06-13): plain text deltas may
537
+ * omit `partial` to avoid retaining one full assistant snapshot per token; consumers replay
538
+ * `delta` from the latest start/end partial checkpoint (agent-loop reconstructs).
539
+ */
540
+ | {
207
541
  type: "text_delta";
208
542
  contentIndex: number;
209
543
  delta: string;
@@ -213,7 +547,17 @@ export type AssistantMessageEvent = {
213
547
  contentIndex: number;
214
548
  content: string;
215
549
  partial: AssistantMessage;
216
- } | {
550
+ }
551
+ /**
552
+ * design/124 tier B contract note: after a mid-stream failure with only thinking streamed, the
553
+ * brain seals the block (`thinking_end`) and RE-SENDS the whole turn WITHOUT a second `start` —
554
+ * the retry attempt may then legally reopen a thinking block at the SAME contentIndex (the openai
555
+ * parser hardcodes thinking at index 0; the anthropic wire restarts block indexing per attempt).
556
+ * Consumers that render by `partial` snapshot are naturally correct (each retry event carries a
557
+ * fresh snapshot that REPLACES the previous attempt's content — CC's "drop the thinking" semantics);
558
+ * a consumer keying blocks by index gets exactly the intended replacement.
559
+ */
560
+ | {
217
561
  type: "thinking_start";
218
562
  contentIndex: number;
219
563
  partial: AssistantMessage;
@@ -236,7 +580,21 @@ export type AssistantMessageEvent = {
236
580
  contentIndex: number;
237
581
  delta: string;
238
582
  partial: AssistantMessage;
239
- } | {
583
+ }
584
+ /**
585
+ * design/120 P2.0 provider contract — `toolcall_end` may trigger IN-STREAM TOOL EXECUTION
586
+ * (agent-loop P2), so its emission carries real semantics, not just UI progress:
587
+ * - Emit it only when the call's input is COMPLETE and parsed to a valid JSON object (`toolCall`
588
+ * is executable as-is). A malformed/truncated accumulation must emit nothing (fail-closed: the
589
+ * call then never executes in-stream; the brain's finalize surfaces it via its malformed path).
590
+ * - Emit AT MOST ONCE per call, and every emitted call MUST appear — same `id`, same `arguments`
591
+ * object identity not required but same values — in the terminal `done` message's content.
592
+ * (One-directional: content may carry calls that never emitted `toolcall_end`, e.g. trailing
593
+ * calls closed at finalize or text-repaired calls; those simply run on the post-stream batch
594
+ * path.) An `error` terminal is allowed to lack the block; the loop's error-final reconciliation
595
+ * merges executor-held calls back into the persisted content (design/120 §5.4).
596
+ */
597
+ | {
240
598
  type: "toolcall_end";
241
599
  contentIndex: number;
242
600
  toolCall: ToolCall;
@@ -258,22 +616,103 @@ export interface AssistantMessageEventStreamContract extends AsyncIterable<Assis
258
616
  export interface AssistantMessageEventStreamLike extends AsyncIterable<AssistantMessageEvent> {
259
617
  result(): Promise<AssistantMessage>;
260
618
  }
619
+ /**
620
+ * Compatibility settings the OpenAI-compatible completions brain actually reads.
621
+ *
622
+ * Thirteen further members were declared here until 2026-08-04 and consumed by NOTHING in the engine
623
+ * (`supportsStore`, `supportsDeveloperRole`, `supportsUsageInStreaming`, `requiresToolResultName`,
624
+ * `requiresAssistantAfterToolResult`, `requiresThinkingAsText`, `openRouterRouting`,
625
+ * `vercelGatewayRouting`, `zaiToolStream`, `supportsStrictMode`, `cacheControlFormat`,
626
+ * `sendSessionAffinityHeaders`, `supportsLongCacheRetention`) — leftovers of the vendored era whose
627
+ * behaviour never crossed into the first-party brain, several of them promising a "Default:
628
+ * auto-detected from URL" that no code performs. They are removed rather than kept: a model author who
629
+ * sets a declared-only knob gets silence, which is worse than a compile error (same ruling as
630
+ * {@link OpenAIResponsesCompat}, and now gated by `gate:field-liveness`).
631
+ */
261
632
  export interface OpenAICompletionsCompat {
633
+ /** Whether the provider supports `reasoning_effort`. Default: auto-detected from URL. */
262
634
  supportsReasoningEffort?: boolean;
635
+ /**
636
+ * Which `reasoning_effort` tiers this endpoint accepts. Absent → the conservative default
637
+ * (`minimal | low | medium | high`), so a higher requested tier (`xhigh`/`max`) clamps down to `high`
638
+ * rather than 422'ing a stock OpenAI endpoint. Declare a higher tier here when the provider genuinely
639
+ * takes it (e.g. `["minimal","low","medium","high","xhigh"]`). See sema-core design/96 S5.
640
+ */
263
641
  reasoningEffortLevels?: ThinkingLevel[];
642
+ /** Which field to use for max tokens. Absent → inferred from the model id (no URL auto-detection):
643
+ * newer stock-OpenAI families that REQUIRE `max_completion_tokens` (gpt-5*, the o1/o3/o4 families,
644
+ * chatgpt-4o*) get it; every other id keeps `max_tokens`, the only spelling many third-party
645
+ * OpenAI-compatible endpoints accept. Declare explicitly to override the inference
646
+ * (design/119 #3; see `inferMaxTokensField` in brain/openai). */
264
647
  maxTokensField?: "max_completion_tokens" | "max_tokens";
648
+ /** Whether all replayed assistant messages must include an empty reasoning_content field when reasoning is enabled. Default: auto-detected from URL. */
265
649
  requiresReasoningContentOnAssistantMessages?: boolean;
650
+ /** Format for reasoning/thinking parameter. "openai" uses reasoning_effort, "openrouter" uses reasoning: { effort }, "deepseek" uses thinking: { type } plus reasoning_effort, "together" uses reasoning: { enabled } plus reasoning_effort when supported, "zai" uses top-level enable_thinking: boolean, "qwen" uses top-level enable_thinking: boolean, and "qwen-chat-template" uses chat_template_kwargs.enable_thinking. Default: "openai". */
266
651
  thinkingFormat?: "openai" | "openrouter" | "deepseek" | "together" | "zai" | "qwen" | "qwen-chat-template";
267
652
  }
653
+ /** Compatibility settings for OpenAI Responses APIs. */
654
+ /**
655
+ * Compatibility settings the Open Responses lane (`createOpenResponsesBrain`) actually reads.
656
+ * The two former members (`sendSessionIdHeader` / `supportsLongCacheRetention`) had ZERO consumers
657
+ * anywhere in the engine — declared-only fields that told a typed model author two knobs existed
658
+ * while the two REAL knobs were unreachable through the typed surface (ruled 2026-08-04, review of
659
+ * the adapter landing). This declaration now states exactly what the adapter consumes.
660
+ */
268
661
  export interface OpenAIResponsesCompat {
662
+ /** Does this endpoint accept `reasoning.effort` at all? Absent ⇒ yes. */
269
663
  supportsReasoningEffort?: boolean;
664
+ /** The effort tiers THIS endpoint accepts. Absent ⇒ the engine's default ladder (higher tiers clamp down). */
270
665
  reasoningEffortLevels?: ThinkingLevel[];
271
666
  }
667
+ /**
668
+ * Compatibility settings the Anthropic Messages brain actually reads. Four further members
669
+ * (`supportsEagerToolInputStreaming`, `supportsLongCacheRetention`, `sendSessionAffinityHeaders`,
670
+ * `supportsCacheControlOnTools`) were declared here with zero consumers until 2026-08-04 — each one
671
+ * described request behaviour (beta headers, `cache_control` placement, session-affinity routing) that
672
+ * the brain performs unconditionally or not at all, so declaring the opposite changed nothing. Removed;
673
+ * see {@link OpenAIResponsesCompat} for the ruling and `gate:field-liveness` for the guard.
674
+ */
272
675
  export interface AnthropicMessagesCompat {
676
+ /**
677
+ * How this endpoint takes extended thinking (CC 2.1.198 parity, design/119).
678
+ * - `"budget"` (default, pre-Fable models): `thinking: { type: "enabled", budget_tokens }`.
679
+ * - `"adaptive"` (Fable 5 / Opus 4.8/4.7 class): `thinking: { type: "adaptive" }` — NO
680
+ * `budget_tokens` (these models 400 on a budget), no max_tokens bump; the intensity is carried
681
+ * by `output_config.effort` instead (see {@link effortLevels}). `off` omits the field entirely
682
+ * (these models also reject `{type:"disabled"}`).
683
+ */
273
684
  thinkingMode?: "budget" | "adaptive";
685
+ /**
686
+ * Effort tiers this endpoint accepts via `output_config.effort` (CC 2.1.198 `effort` /
687
+ * `xhigh_effort` / `max_effort` capability bits collapsed into one declared set, matching the
688
+ * `reasoningEffortLevels` pattern on {@link OpenAICompletionsCompat}). Present ⇒ the brain sends
689
+ * `output_config: { effort }` plus the `effort-2025-11-24` beta header, clamping the requested
690
+ * tier DOWN into this set (e.g. Fable 5 = `["low","medium","high","xhigh","max"]`; a model without
691
+ * `xhigh_effort` declares up to `"high"` and higher requests clamp). Absent ⇒ no `output_config`
692
+ * is ever sent (pre-effort models unchanged).
693
+ */
274
694
  effortLevels?: ThinkingLevel[];
695
+ /**
696
+ * Whether the endpoint accepts `temperature` at all. CC 2.1.198 sends temperature only to a
697
+ * legacy allowlist — Fable-5-class models NEVER receive it (400 risk), independent of thinking
698
+ * state. Default true (existing models unchanged); `false` drops a caller temperature
699
+ * unconditionally, not just under extended thinking.
700
+ */
275
701
  supportsTemperature?: boolean;
702
+ /**
703
+ * design/119 S4 (CC 2.1.198 `context_management` capability): when thinking is enabled, send
704
+ * `context_management: { edits: [{ type: "clear_thinking_20251015", keep: "all" }] }` plus the
705
+ * `context-management-2025-06-27` beta — an explicit opt-OUT of the server's default
706
+ * thinking-clearing, preserving cross-turn reasoning continuity (what CC sends on first-party
707
+ * endpoints). Declare only on endpoints that accept the beta (real Anthropic); an
708
+ * Anthropic-COMPATIBLE gateway (e.g. DeepSeek's anthropic endpoint) must leave it off.
709
+ */
276
710
  contextManagement?: boolean;
711
+ /**
712
+ * design/119 S4 (CC 2.1.198): attach the `interleaved-thinking-2025-05-14` beta on tool-enabled
713
+ * requests with thinking on (thinking blocks may interleave with tool_use). Declare per endpoint;
714
+ * absent = no beta (pre-119 behavior; a deployment could already do this via static `headers`).
715
+ */
277
716
  interleavedThinking?: boolean;
278
717
  }
279
718
  export interface Model<TApi extends Api = Api> {
@@ -283,7 +722,20 @@ export interface Model<TApi extends Api = Api> {
283
722
  provider: Provider;
284
723
  baseUrl: string;
285
724
  reasoning: boolean;
725
+ /**
726
+ * design/111 — this model's DEFAULT thinking level (per-model preset). The thinking-resolution chain is
727
+ * `spec.thinking ?? role.thinking ?? model.defaultThinking` (prepare-task) — a caller/role still overrides, but
728
+ * a model that should "think by default" (e.g. an Anthropic reasoning model defaulting to `medium`) declares it
729
+ * here instead of every task/role re-specifying. Absent ⇒ no model-level default (chain falls to `undefined` =
730
+ * thinking off unless a caller/role asks). It is the REQUESTED tier; the per-endpoint clamp (`resolveReasoning`/
731
+ * `reasoningEffortLevels`) still bounds it — a stock-OpenAI endpoint clamps `max`→`high`, while an
732
+ * `anthropic-messages` budget endpoint honors the full range up to `max` unclamped.
733
+ */
286
734
  defaultThinking?: ThinkingLevel;
735
+ /**
736
+ * Maps OpenClaw thinking levels to provider/model-specific values.
737
+ * Missing keys use provider defaults. null marks a level as unsupported.
738
+ */
287
739
  thinkingLevelMap?: ThinkingLevelMap;
288
740
  input: ("text" | "image")[];
289
741
  cost: {
@@ -293,14 +745,59 @@ export interface Model<TApi extends Api = Api> {
293
745
  cacheWrite: number;
294
746
  };
295
747
  contextWindow: number;
748
+ /**
749
+ * Optional effective runtime cap used for compaction/session budgeting.
750
+ * Keeps provider/native contextWindow metadata intact while allowing a
751
+ * smaller practical window.
752
+ */
296
753
  contextTokens?: number;
754
+ /**
755
+ * Optional AUTOCOMPACT window — the window the compaction trigger and the clearStale frontier
756
+ * are derived from when it differs from the physical request window (dual-window semantics).
757
+ * CC 2.1.207 posture: its 1M sonnet keeps the PHYSICAL window at 1M while a per-model dynamic
758
+ * config lowers only the autocompact window to 967000, so the reactive trigger lands at 934000
759
+ * (= 967000 − 33000); a single window value cannot express both. Consumed by the trigger-side
760
+ * geometry only (`editBudget`/`sanitizeCompactionSettings`/`shouldCompact` window); the request
761
+ * hard-stop guard (`guardBudget`) and physical request budgeting stay on
762
+ * `contextTokens ?? contextWindow`. Absent ⇒ `contextTokens ?? contextWindow`.
763
+ */
297
764
  autoCompactTokens?: number;
765
+ /**
766
+ * design/123 D2 — structural token-estimate coefficient: how many CHARACTERS ≈ one token for this
767
+ * model's tokenizer. Used by every structural (non-usage-anchored) token estimate in the engine:
768
+ * the compaction trigger's anchor-less fallback, the request-layer defenses (clearStaleToolResults /
769
+ * trimToBudget), cut-point accounting, the prompt-overhead term, and the summarization input guard.
770
+ * API-agnostic model property (NOT a wire knob), hence top-level and not `compat`.
771
+ *
772
+ * Default **4** (byte-compatible with the historical chars/4 heuristic; CC 198's legacy-family
773
+ * value — claude-3.x / opus·sonnet-4-x / haiku-4-5). Newer families tokenize denser (CC 198 uses
774
+ * **3** for the sonnet-5/fable-5 class). CJK-heavy deployments should consider **2–3**: chars/4
775
+ * underestimates Chinese by 60–75%, which lets the defenses pass over-window requests.
776
+ */
298
777
  charsPerToken?: number;
299
778
  maxTokens: number;
779
+ /** Provider-specific request/runtime parameters passed through to provider plugins. */
300
780
  params?: Record<string, unknown>;
781
+ /**
782
+ * Extra request-BODY params merged into the provider call (design/40): official provider knobs core
783
+ * doesn't model as first-class — OpenAI `frequency_penalty`/`presence_penalty`/`top_p`/`seed`/`logit_bias`,
784
+ * Anthropic `top_k`/`top_p`/`stop_sequences`, etc. Keys core owns (messages/tools/temperature/…) are
785
+ * stripped (core wins). **Anchored on the Model and stable across turns** — reuse the SAME Model object
786
+ * (stable key-insertion order) for every turn sharing a cache namespace, or the serialized body bytes
787
+ * change and the prefix cache breaks (design/9/31). Not for per-turn variation.
788
+ */
301
789
  extraBody?: Record<string, unknown>;
790
+ /** Extra request HEADERS merged into the provider call. Cannot override auth / content-type / version. */
302
791
  headers?: Record<string, string>;
792
+ /**
793
+ * design/119 S3 (CC 2.1.198 parity): model-declared system-prompt guidance sections, appended to
794
+ * the assembled system prompt. This is the declarative home for per-model behavioral patches (CC
795
+ * ships Fable-5 "mitigations" baked behind model-name checks; sema keeps the MECHANISM generic —
796
+ * any Model can carry guidance — and the CONTENT as preset data, zero model-name matching in core).
797
+ * Each entry is one section; joined with blank lines.
798
+ */
303
799
  promptGuidance?: string[];
800
+ /** Compatibility overrides for OpenAI-compatible APIs. If not set, auto-detected from baseUrl. */
304
801
  compat?: TApi extends "openai-completions" ? OpenAICompletionsCompat : TApi extends "openai-responses" ? OpenAIResponsesCompat : TApi extends "anthropic-messages" ? AnthropicMessagesCompat : never;
305
802
  }
306
803
  export interface ImagesModel<TApi extends ImagesApi = ImagesApi> extends Omit<Model, "api" | "provider" | "reasoning" | "contextWindow" | "maxTokens" | "compat"> {