@animalabs/agent-framework 0.26.2 → 0.27.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 (276) hide show
  1. package/README.md +56 -6
  2. package/dist/src/agent.d.ts +263 -22
  3. package/dist/src/agent.d.ts.map +1 -1
  4. package/dist/src/agent.js +531 -54
  5. package/dist/src/agent.js.map +1 -1
  6. package/dist/src/api/server.d.ts.map +1 -1
  7. package/dist/src/api/server.js +1 -2
  8. package/dist/src/api/server.js.map +1 -1
  9. package/dist/src/auto-continue.d.ts +33 -0
  10. package/dist/src/auto-continue.d.ts.map +1 -0
  11. package/dist/src/auto-continue.js +35 -0
  12. package/dist/src/auto-continue.js.map +1 -0
  13. package/dist/src/code-execution/isolate/scripts.d.ts +11 -0
  14. package/dist/src/code-execution/isolate/scripts.d.ts.map +1 -1
  15. package/dist/src/code-execution/isolate/scripts.js +5 -1
  16. package/dist/src/code-execution/isolate/scripts.js.map +1 -1
  17. package/dist/src/framework.d.ts +759 -129
  18. package/dist/src/framework.d.ts.map +1 -1
  19. package/dist/src/framework.js +3482 -928
  20. package/dist/src/framework.js.map +1 -1
  21. package/dist/src/gate/event-gate.d.ts +309 -46
  22. package/dist/src/gate/event-gate.d.ts.map +1 -1
  23. package/dist/src/gate/event-gate.js +2117 -395
  24. package/dist/src/gate/event-gate.js.map +1 -1
  25. package/dist/src/gate/index.d.ts +2 -2
  26. package/dist/src/gate/index.d.ts.map +1 -1
  27. package/dist/src/gate/index.js +1 -1
  28. package/dist/src/gate/index.js.map +1 -1
  29. package/dist/src/gate/recipe-reconcile.d.ts +103 -0
  30. package/dist/src/gate/recipe-reconcile.d.ts.map +1 -0
  31. package/dist/src/gate/recipe-reconcile.js +325 -0
  32. package/dist/src/gate/recipe-reconcile.js.map +1 -0
  33. package/dist/src/gate/types.d.ts +68 -8
  34. package/dist/src/gate/types.d.ts.map +1 -1
  35. package/dist/src/index.d.ts +6 -4
  36. package/dist/src/index.d.ts.map +1 -1
  37. package/dist/src/index.js +5 -2
  38. package/dist/src/index.js.map +1 -1
  39. package/dist/src/mcpl/channel-registry.d.ts +433 -113
  40. package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
  41. package/dist/src/mcpl/channel-registry.js +1152 -434
  42. package/dist/src/mcpl/channel-registry.js.map +1 -1
  43. package/dist/src/mcpl/conversation-router.d.ts +16 -8
  44. package/dist/src/mcpl/conversation-router.d.ts.map +1 -1
  45. package/dist/src/mcpl/conversation-router.js +29 -15
  46. package/dist/src/mcpl/conversation-router.js.map +1 -1
  47. package/dist/src/mcpl/convert-block.d.ts.map +1 -1
  48. package/dist/src/mcpl/convert-block.js +14 -2
  49. package/dist/src/mcpl/convert-block.js.map +1 -1
  50. package/dist/src/mcpl/hook-orchestrator.d.ts +7 -1
  51. package/dist/src/mcpl/hook-orchestrator.d.ts.map +1 -1
  52. package/dist/src/mcpl/hook-orchestrator.js +32 -7
  53. package/dist/src/mcpl/hook-orchestrator.js.map +1 -1
  54. package/dist/src/mcpl/index.d.ts +5 -1
  55. package/dist/src/mcpl/index.d.ts.map +1 -1
  56. package/dist/src/mcpl/index.js +4 -0
  57. package/dist/src/mcpl/index.js.map +1 -1
  58. package/dist/src/mcpl/inference-router.d.ts +14 -2
  59. package/dist/src/mcpl/inference-router.d.ts.map +1 -1
  60. package/dist/src/mcpl/inference-router.js +73 -28
  61. package/dist/src/mcpl/inference-router.js.map +1 -1
  62. package/dist/src/mcpl/prose-grammar.d.ts +4 -0
  63. package/dist/src/mcpl/prose-grammar.d.ts.map +1 -1
  64. package/dist/src/mcpl/prose-grammar.js +6 -0
  65. package/dist/src/mcpl/prose-grammar.js.map +1 -1
  66. package/dist/src/mcpl/protocol-family.d.ts.map +1 -1
  67. package/dist/src/mcpl/protocol-family.js +3 -0
  68. package/dist/src/mcpl/protocol-family.js.map +1 -1
  69. package/dist/src/mcpl/push-coalescer.d.ts +20 -2
  70. package/dist/src/mcpl/push-coalescer.d.ts.map +1 -1
  71. package/dist/src/mcpl/push-coalescer.js +33 -11
  72. package/dist/src/mcpl/push-coalescer.js.map +1 -1
  73. package/dist/src/mcpl/reference-fetcher.d.ts +63 -42
  74. package/dist/src/mcpl/reference-fetcher.d.ts.map +1 -1
  75. package/dist/src/mcpl/reference-fetcher.js +177 -145
  76. package/dist/src/mcpl/reference-fetcher.js.map +1 -1
  77. package/dist/src/mcpl/references.d.ts +380 -46
  78. package/dist/src/mcpl/references.d.ts.map +1 -1
  79. package/dist/src/mcpl/references.js +736 -77
  80. package/dist/src/mcpl/references.js.map +1 -1
  81. package/dist/src/mcpl/server-connection.d.ts +82 -3
  82. package/dist/src/mcpl/server-connection.d.ts.map +1 -1
  83. package/dist/src/mcpl/server-connection.js +132 -7
  84. package/dist/src/mcpl/server-connection.js.map +1 -1
  85. package/dist/src/mcpl/tool-lifecycle.d.ts +11 -0
  86. package/dist/src/mcpl/tool-lifecycle.d.ts.map +1 -1
  87. package/dist/src/mcpl/tool-lifecycle.js +21 -0
  88. package/dist/src/mcpl/tool-lifecycle.js.map +1 -1
  89. package/dist/src/mcpl/tool-presence.d.ts +259 -0
  90. package/dist/src/mcpl/tool-presence.d.ts.map +1 -0
  91. package/dist/src/mcpl/tool-presence.js +628 -0
  92. package/dist/src/mcpl/tool-presence.js.map +1 -0
  93. package/dist/src/mcpl/tool-result-normalize.d.ts +9 -3
  94. package/dist/src/mcpl/tool-result-normalize.d.ts.map +1 -1
  95. package/dist/src/mcpl/tool-result-normalize.js +14 -6
  96. package/dist/src/mcpl/tool-result-normalize.js.map +1 -1
  97. package/dist/src/mcpl/tool-signature.d.ts +39 -0
  98. package/dist/src/mcpl/tool-signature.d.ts.map +1 -0
  99. package/dist/src/mcpl/tool-signature.js +292 -0
  100. package/dist/src/mcpl/tool-signature.js.map +1 -0
  101. package/dist/src/mcpl/toolset-host.d.ts +200 -0
  102. package/dist/src/mcpl/toolset-host.d.ts.map +1 -0
  103. package/dist/src/mcpl/toolset-host.js +621 -0
  104. package/dist/src/mcpl/toolset-host.js.map +1 -0
  105. package/dist/src/mcpl/toolsets-module.d.ts +80 -0
  106. package/dist/src/mcpl/toolsets-module.d.ts.map +1 -0
  107. package/dist/src/mcpl/toolsets-module.js +431 -0
  108. package/dist/src/mcpl/toolsets-module.js.map +1 -0
  109. package/dist/src/mcpl/transport.d.ts +2 -2
  110. package/dist/src/mcpl/transport.d.ts.map +1 -1
  111. package/dist/src/mcpl/transport.js +3 -2
  112. package/dist/src/mcpl/transport.js.map +1 -1
  113. package/dist/src/mcpl/types.d.ts +21 -1
  114. package/dist/src/mcpl/types.d.ts.map +1 -1
  115. package/dist/src/mcpl/types.js.map +1 -1
  116. package/dist/src/mcpl/visible-content.d.ts +7 -9
  117. package/dist/src/mcpl/visible-content.d.ts.map +1 -1
  118. package/dist/src/mcpl/visible-content.js +21 -9
  119. package/dist/src/mcpl/visible-content.js.map +1 -1
  120. package/dist/src/module-registry.d.ts +23 -8
  121. package/dist/src/module-registry.d.ts.map +1 -1
  122. package/dist/src/module-registry.js +68 -15
  123. package/dist/src/module-registry.js.map +1 -1
  124. package/dist/src/modules/discord/index.js +1 -1
  125. package/dist/src/modules/discord/index.js.map +1 -1
  126. package/dist/src/modules/history/index.d.ts +2 -1
  127. package/dist/src/modules/history/index.d.ts.map +1 -1
  128. package/dist/src/modules/history/index.js +51 -17
  129. package/dist/src/modules/history/index.js.map +1 -1
  130. package/dist/src/modules/history/semantic.d.ts +108 -6
  131. package/dist/src/modules/history/semantic.d.ts.map +1 -1
  132. package/dist/src/modules/history/semantic.js +273 -57
  133. package/dist/src/modules/history/semantic.js.map +1 -1
  134. package/dist/src/modules/workspace/direct-write.d.ts +181 -0
  135. package/dist/src/modules/workspace/direct-write.d.ts.map +1 -0
  136. package/dist/src/modules/workspace/direct-write.js +384 -0
  137. package/dist/src/modules/workspace/direct-write.js.map +1 -0
  138. package/dist/src/modules/workspace/edit-text.d.ts +26 -12
  139. package/dist/src/modules/workspace/edit-text.d.ts.map +1 -1
  140. package/dist/src/modules/workspace/edit-text.js +58 -28
  141. package/dist/src/modules/workspace/edit-text.js.map +1 -1
  142. package/dist/src/modules/workspace/effects.d.ts +10 -0
  143. package/dist/src/modules/workspace/effects.d.ts.map +1 -1
  144. package/dist/src/modules/workspace/effects.js +1 -1
  145. package/dist/src/modules/workspace/effects.js.map +1 -1
  146. package/dist/src/modules/workspace/index.d.ts +246 -27
  147. package/dist/src/modules/workspace/index.d.ts.map +1 -1
  148. package/dist/src/modules/workspace/index.js +1216 -236
  149. package/dist/src/modules/workspace/index.js.map +1 -1
  150. package/dist/src/modules/workspace/read-page.d.ts +41 -0
  151. package/dist/src/modules/workspace/read-page.d.ts.map +1 -0
  152. package/dist/src/modules/workspace/read-page.js +213 -0
  153. package/dist/src/modules/workspace/read-page.js.map +1 -0
  154. package/dist/src/modules/workspace/result-text.d.ts +67 -0
  155. package/dist/src/modules/workspace/result-text.d.ts.map +1 -0
  156. package/dist/src/modules/workspace/result-text.js +94 -0
  157. package/dist/src/modules/workspace/result-text.js.map +1 -0
  158. package/dist/src/modules/workspace/text.d.ts +29 -12
  159. package/dist/src/modules/workspace/text.d.ts.map +1 -1
  160. package/dist/src/modules/workspace/text.js +35 -33
  161. package/dist/src/modules/workspace/text.js.map +1 -1
  162. package/dist/src/modules/workspace/types.d.ts +41 -17
  163. package/dist/src/modules/workspace/types.d.ts.map +1 -1
  164. package/dist/src/modules/workspace/types.js.map +1 -1
  165. package/dist/src/sent-rows.d.ts +59 -0
  166. package/dist/src/sent-rows.d.ts.map +1 -0
  167. package/dist/src/sent-rows.js +145 -0
  168. package/dist/src/sent-rows.js.map +1 -0
  169. package/dist/src/silent-heartbeat.d.ts +17 -10
  170. package/dist/src/silent-heartbeat.d.ts.map +1 -1
  171. package/dist/src/silent-heartbeat.js.map +1 -1
  172. package/dist/src/stable-hash.d.ts +3 -0
  173. package/dist/src/stable-hash.d.ts.map +1 -0
  174. package/dist/src/stable-hash.js +15 -0
  175. package/dist/src/stable-hash.js.map +1 -0
  176. package/dist/src/stored-injections.d.ts +99 -0
  177. package/dist/src/stored-injections.d.ts.map +1 -0
  178. package/dist/src/stored-injections.js +106 -0
  179. package/dist/src/stored-injections.js.map +1 -0
  180. package/dist/src/text-as-stored.d.ts +4 -3
  181. package/dist/src/text-as-stored.d.ts.map +1 -1
  182. package/dist/src/text-as-stored.js +4 -3
  183. package/dist/src/text-as-stored.js.map +1 -1
  184. package/dist/src/thinking-drops.d.ts +81 -0
  185. package/dist/src/thinking-drops.d.ts.map +1 -0
  186. package/dist/src/thinking-drops.js +103 -0
  187. package/dist/src/thinking-drops.js.map +1 -0
  188. package/dist/src/tool-image-ledger.d.ts +9 -8
  189. package/dist/src/tool-image-ledger.d.ts.map +1 -1
  190. package/dist/src/tool-image-ledger.js +9 -8
  191. package/dist/src/tool-image-ledger.js.map +1 -1
  192. package/dist/src/tool-presentation.d.ts.map +1 -1
  193. package/dist/src/tool-presentation.js +3 -1
  194. package/dist/src/tool-presentation.js.map +1 -1
  195. package/dist/src/tool-result-guard.d.ts +4 -2
  196. package/dist/src/tool-result-guard.d.ts.map +1 -1
  197. package/dist/src/tool-result-guard.js +21 -6
  198. package/dist/src/tool-result-guard.js.map +1 -1
  199. package/dist/src/tool-result-history.d.ts +176 -24
  200. package/dist/src/tool-result-history.d.ts.map +1 -1
  201. package/dist/src/tool-result-history.js +411 -91
  202. package/dist/src/tool-result-history.js.map +1 -1
  203. package/dist/src/tune-out/coordinator.d.ts +17 -9
  204. package/dist/src/tune-out/coordinator.d.ts.map +1 -1
  205. package/dist/src/tune-out/coordinator.js +84 -37
  206. package/dist/src/tune-out/coordinator.js.map +1 -1
  207. package/dist/src/types/agent.d.ts +186 -7
  208. package/dist/src/types/agent.d.ts.map +1 -1
  209. package/dist/src/types/events.d.ts +15 -1
  210. package/dist/src/types/events.d.ts.map +1 -1
  211. package/dist/src/types/framework.d.ts +24 -3
  212. package/dist/src/types/framework.d.ts.map +1 -1
  213. package/dist/src/types/module.d.ts +90 -7
  214. package/dist/src/types/module.d.ts.map +1 -1
  215. package/dist/src/types/trace.d.ts +57 -2
  216. package/dist/src/types/trace.d.ts.map +1 -1
  217. package/package.json +4 -3
  218. package/src/agent.ts +593 -60
  219. package/src/api/server.ts +1 -2
  220. package/src/auto-continue.ts +42 -0
  221. package/src/code-execution/isolate/scripts.ts +11 -3
  222. package/src/framework.ts +3601 -967
  223. package/src/gate/event-gate.ts +2315 -389
  224. package/src/gate/index.ts +2 -1
  225. package/src/gate/recipe-reconcile.ts +355 -0
  226. package/src/gate/types.ts +70 -8
  227. package/src/index.ts +7 -4
  228. package/src/mcpl/channel-registry.ts +1220 -467
  229. package/src/mcpl/conversation-router.ts +34 -16
  230. package/src/mcpl/convert-block.ts +14 -1
  231. package/src/mcpl/hook-orchestrator.ts +33 -6
  232. package/src/mcpl/index.ts +6 -1
  233. package/src/mcpl/inference-router.ts +79 -34
  234. package/src/mcpl/prose-grammar.ts +7 -0
  235. package/src/mcpl/protocol-family.ts +2 -0
  236. package/src/mcpl/push-coalescer.ts +51 -13
  237. package/src/mcpl/reference-fetcher.ts +201 -162
  238. package/src/mcpl/references.ts +851 -77
  239. package/src/mcpl/server-connection.ts +145 -7
  240. package/src/mcpl/tool-lifecycle.ts +21 -0
  241. package/src/mcpl/tool-presence.ts +650 -0
  242. package/src/mcpl/tool-result-normalize.ts +18 -6
  243. package/src/mcpl/tool-signature.ts +285 -0
  244. package/src/mcpl/toolset-host.ts +637 -0
  245. package/src/mcpl/toolsets-module.ts +451 -0
  246. package/src/mcpl/transport.ts +3 -2
  247. package/src/mcpl/types.ts +22 -1
  248. package/src/mcpl/visible-content.ts +22 -9
  249. package/src/module-registry.ts +77 -24
  250. package/src/modules/discord/index.ts +1 -1
  251. package/src/modules/history/index.ts +48 -18
  252. package/src/modules/history/semantic.ts +308 -54
  253. package/src/modules/workspace/direct-write.ts +425 -0
  254. package/src/modules/workspace/edit-text.ts +82 -35
  255. package/src/modules/workspace/effects.ts +1 -1
  256. package/src/modules/workspace/index.ts +1274 -241
  257. package/src/modules/workspace/read-page.ts +222 -0
  258. package/src/modules/workspace/result-text.ts +119 -0
  259. package/src/modules/workspace/text.ts +58 -32
  260. package/src/modules/workspace/types.ts +41 -17
  261. package/src/sent-rows.ts +162 -0
  262. package/src/silent-heartbeat.ts +17 -10
  263. package/src/stable-hash.ts +14 -0
  264. package/src/stored-injections.ts +131 -0
  265. package/src/text-as-stored.ts +4 -3
  266. package/src/thinking-drops.ts +141 -0
  267. package/src/tool-image-ledger.ts +9 -8
  268. package/src/tool-presentation.ts +3 -1
  269. package/src/tool-result-guard.ts +19 -6
  270. package/src/tool-result-history.ts +471 -90
  271. package/src/tune-out/coordinator.ts +80 -37
  272. package/src/types/agent.ts +189 -7
  273. package/src/types/events.ts +15 -1
  274. package/src/types/framework.ts +21 -3
  275. package/src/types/module.ts +86 -7
  276. package/src/types/trace.ts +58 -2
package/dist/src/agent.js CHANGED
@@ -1,38 +1,56 @@
1
1
  import { isAbortedResponse } from '@animalabs/membrane';
2
- import { createHash } from 'node:crypto';
3
2
  import { ToolResultGuard } from './tool-result-guard.js';
4
3
  import { withoutTokenEstimates } from './thinking-token-stamp.js';
4
+ import { placeThinkingDrops } from './thinking-drops.js';
5
+ import { carriedBlock } from './sent-rows.js';
5
6
  import { injectionsAsStored } from './text-as-stored.js';
6
- import { assertBooleanSetting, holdsSettings } from './config-checks.js';
7
+ import { stableHash } from './stable-hash.js';
8
+ import { hasRenderedContent, storedInjectionMarkOf } from './stored-injections.js';
9
+ import { assertBooleanSetting, holdsSettings, kindOf } from './config-checks.js';
7
10
  import { CONTINUE_ROW, continueTurn, indexRequestOnlyRows, renderRequestOnlyRows, silentHeartbeatSeparatorTurn, tickKey, toolLoopPrompt, } from './silent-heartbeat.js';
8
11
  import { randomUUID } from 'node:crypto';
9
12
  import { resolveClockConfig } from './clock-rows.js';
10
13
  import { nonErrorResultText, truncateForHistory, DEFAULT_TOOL_RESULT_INLINE_MAX_CHARS, } from './tool-result-history.js';
11
- function stableHash(value) {
12
- const encode = (item) => {
13
- if (Array.isArray(item))
14
- return `[${item.map(encode).join(',')}]`;
15
- if (item && typeof item === 'object') {
16
- const record = item;
17
- return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${encode(record[key])}`).join(',')}}`;
18
- }
19
- return JSON.stringify(item) ?? 'null';
20
- };
21
- return createHash('sha256').update(encode(value)).digest('hex');
14
+ /** The render stats of the dry compile behind each request a dry run
15
+ * assembled (`assembleActivationRequest` with `dryRun`), by that request.
16
+ * A request that is sent has none here. Read through the framework's
17
+ * `getRequestCompileStats`. */
18
+ const dryCompileStats = new WeakMap();
19
+ /** The render stats of the dry compile that built `request`, or null: see
20
+ * `AgentFramework.getRequestCompileStats`. */
21
+ export function dryCompileStatsOf(request) {
22
+ return dryCompileStats.get(request) ?? null;
23
+ }
24
+ /**
25
+ * Whether a request's messages, as sanitized, end on `agentName`'s own
26
+ * message, apart from `injectionTail` stored context injections after it
27
+ * (counted over the messages the sanitizer keeps).
28
+ */
29
+ function endsOnOwnMessage(messages, agentName, injectionTail) {
30
+ const own = messages[messages.length - 1 - injectionTail];
31
+ return own !== undefined && own.participant === agentName
32
+ && messages.slice(messages.length - injectionTail).every((m) => m.participant.startsWith('system_context:'));
33
+ }
34
+ /** A digest of a value as a request's JSON carries it (a field whose value is undefined left out, as the wire leaves
35
+ * it out), key order aside: the head digests the thinking binding compares, so a change on the wire changes one. */
36
+ function wireDigest(value) {
37
+ return stableHash(JSON.parse(JSON.stringify(value) ?? 'null'));
22
38
  }
23
39
  const DEFAULT_CONTEXT_BUDGET_TOKENS = 100_000;
24
40
  const DEFAULT_TRANSITION_PACE_TOKENS = 16_000;
25
41
  const DEFAULT_SAME_ROUND_THINK_TEXT_POLICY = 'public';
26
42
  /**
27
43
  * Refuse an agent config whose `promptCaching`, `toolResultGuard`,
28
- * `toolWrapperProseGuard`, `thinking.enabled` or `refusalHandling.autoRewind`
29
- * holds anything but true or false (assertBooleanSetting), or whose `thinking`
30
- * or `refusalHandling` is anything but an object, null or false
31
- * (holdsSettings). The constructor runs it first, so the rule holds wherever
32
- * an Agent is built. `create()` also runs it for each of its agents before
33
- * anything opens, and `createEphemeralAgent` before it reserves the name, so a
34
- * refusal there leaves nothing behind. Membrane reads `thinking.enabled`, and
35
- * the refusal is here because the setting is AgentConfig's.
44
+ * `toolWrapperProseGuard`, `thinking.enabled`, `thinkingBinding.dropBlock`,
45
+ * `thinkingBinding.binds` or `refusalHandling.autoRewind` holds anything but true or false
46
+ * (assertBooleanSetting, where null counts as left out), or whose `thinking`, `thinkingBinding` or
47
+ * `refusalHandling` is anything but an object, null or false (holdsSettings),
48
+ * or whose `autoContinue` resolveAutoContinue refuses. The constructor runs it
49
+ * first, so the rule holds wherever an Agent is built. `create()` also runs it
50
+ * for each of its agents before anything opens, and `createEphemeralAgent`
51
+ * before it reserves the name, so a refusal there leaves nothing behind.
52
+ * Membrane reads `thinking.enabled`, and the refusal is here because the
53
+ * setting is AgentConfig's.
36
54
  */
37
55
  export function assertAgentSwitches(config) {
38
56
  const agent = `Agent "${config.name}"`;
@@ -40,6 +58,12 @@ export function assertAgentSwitches(config) {
40
58
  if (holdsSettings(`${agent} thinking`, config.thinking, '{ enabled: true }')) {
41
59
  assertBooleanSetting(`${agent} thinking.enabled`, config.thinking.enabled, 'true asks the provider for extended thinking, and false or leaving it out doesn\'t');
42
60
  }
61
+ if (holdsSettings(`${agent} thinkingBinding`, config.thinkingBinding, '{ binds: true, dropBlock: true }')) {
62
+ assertBooleanSetting(`${agent} thinkingBinding.dropBlock`, config.thinkingBinding.dropBlock, 'true asks the provider to drop a signed thinking block whose earlier conversation changed rather than refuse the request, ' +
63
+ 'and false or leaving it out sends nothing, so the account\'s default applies');
64
+ assertBooleanSetting(`${agent} thinkingBinding.binds`, config.thinkingBinding.binds, 'true says the model binds its signed thinking to the conversation before it, so each compile tells the context manager so, ' +
65
+ 'and false or leaving it out compiles as before');
66
+ }
43
67
  if (holdsSettings(`${agent} refusalHandling`, config.refusalHandling, '{ autoRewind: true }')) {
44
68
  assertBooleanSetting(`${agent} refusalHandling.autoRewind`, config.refusalHandling.autoRewind, 'true redacts the turn that tripped a refusal and runs again, up to maxRewinds times, ' +
45
69
  'and false or leaving it out doesn\'t');
@@ -48,6 +72,46 @@ export function assertAgentSwitches(config) {
48
72
  'and false or leaving it out doesn\'t');
49
73
  assertBooleanSetting(`${agent} toolWrapperProseGuard`, config.toolWrapperProseGuard, 'true keeps a response whose whole prose is a tool-call-shaped wrapper from running or entering the agent\'s history, ' +
50
74
  'and false or leaving it out doesn\'t');
75
+ resolveAutoContinue(config);
76
+ }
77
+ /** `AutoContinueConfig.maxConsecutive` when left out. */
78
+ export const DEFAULT_AUTO_CONTINUE_MAX = 3;
79
+ /** The most continuations in a row a config may ask for. */
80
+ const MAX_AUTO_CONTINUE_MAX = 20;
81
+ /**
82
+ * `AgentConfig.autoContinue` resolved: undefined when off (left out, null or
83
+ * false), else its cap. `true` takes the default cap; an object takes
84
+ * `maxConsecutive`, a whole number from 1 to 20 (the default when left out).
85
+ * Any other value is refused.
86
+ */
87
+ export function resolveAutoContinue(config) {
88
+ const setting = `Agent "${config.name}" autoContinue`;
89
+ const value = config.autoContinue;
90
+ if (value === true)
91
+ return { maxConsecutive: DEFAULT_AUTO_CONTINUE_MAX };
92
+ if (value !== undefined && value !== null && value !== false && (typeof value !== 'object' || Array.isArray(value))) {
93
+ throw new Error(`${setting} must be true, false or an object such as { maxConsecutive: 3 }, not ${kindOf(value)}` +
94
+ (typeof value === 'string' ? ' (true and false go unquoted)' : ''));
95
+ }
96
+ if (!holdsSettings(setting, value, '{ maxConsecutive: 3 }'))
97
+ return undefined;
98
+ const max = value.maxConsecutive;
99
+ if (max === undefined)
100
+ return { maxConsecutive: DEFAULT_AUTO_CONTINUE_MAX };
101
+ if (typeof max !== 'number' || !Number.isInteger(max) || max < 1 || max > MAX_AUTO_CONTINUE_MAX) {
102
+ // The value's kind, never the value (config-checks): a `${VAR}` that
103
+ // lands here could be a credential.
104
+ const kind = typeof max !== 'number' ? kindOf(max)
105
+ : !Number.isInteger(max) ? 'a number that isn\'t whole'
106
+ : max < 1 ? 'a number below 1' : `a number above ${MAX_AUTO_CONTINUE_MAX}`;
107
+ throw new Error(`${setting}.maxConsecutive must be a whole number from 1 to ${MAX_AUTO_CONTINUE_MAX}, not ${kind}: ` +
108
+ 'the most turns in a row that continue without skip_reply before the agent waits for the next event');
109
+ }
110
+ return { maxConsecutive: max };
111
+ }
112
+ /** A branch's key in Agent.unsentSince: its id and when it was created. */
113
+ function branchKey(branch) {
114
+ return `${branch.id}\u0000${branch.created}`;
51
115
  }
52
116
  /**
53
117
  * An agent wraps a context manager and manages inference state.
@@ -72,6 +136,12 @@ export class Agent {
72
136
  * blocks are preserved through Chronicle.
73
137
  */
74
138
  thinking;
139
+ /** Whether requests ask the provider to drop signed thinking whose earlier
140
+ * conversation changed (see AgentConfig.thinkingBinding.dropBlock). */
141
+ thinkingDropBlock;
142
+ /** Whether the model binds its signed thinking to the conversation before
143
+ * it (see AgentConfig.thinkingBinding.binds). */
144
+ thinkingBinds;
75
145
  /** Refusal auto-rewind policy (see AgentConfig.refusalHandling). */
76
146
  refusalHandling;
77
147
  toolResultGuard;
@@ -79,6 +149,9 @@ export class Agent {
79
149
  proseRouting;
80
150
  /** Exact whole-response known-tool wrapper containment (default off). */
81
151
  toolWrapperProseGuard;
152
+ /** Continuation after a turn the model ends itself (see
153
+ * AgentConfig.autoContinue); undefined when off. */
154
+ autoContinue;
82
155
  /** Clock rows' interval and precision (see AgentConfig.clock); undefined
83
156
  * when the agent writes none of its own (a resident still reads those
84
157
  * another resident writes into the shared slot). */
@@ -202,10 +275,13 @@ export class Agent {
202
275
  this.maxTokens = config.maxTokens ?? 4096;
203
276
  this.temperature = config.temperature;
204
277
  this.thinking = config.thinking;
278
+ this.thinkingDropBlock = config.thinkingBinding?.dropBlock === true;
279
+ this.thinkingBinds = config.thinkingBinding?.binds === true;
205
280
  this.refusalHandling = config.refusalHandling;
206
281
  this.toolResultGuard = new ToolResultGuard(config.name, contextManager, config.toolResultGuard === true);
207
282
  this.proseRouting = config.proseRouting ?? 'locus';
208
283
  this.toolWrapperProseGuard = config.toolWrapperProseGuard === true;
284
+ this.autoContinue = resolveAutoContinue(config);
209
285
  this.clock = resolveClockConfig(config.name, config.clock);
210
286
  this.cacheTtl = config.cacheTtl ?? '1h';
211
287
  this.promptCaching = config.promptCaching !== false;
@@ -213,7 +289,12 @@ export class Agent {
213
289
  this.providerParams = config.providerParams;
214
290
  this.sameRoundThinkTextPolicy = config.sameRoundThinkTextPolicy;
215
291
  this.maxStreamTokens = config.maxStreamTokens ?? 150_000;
216
- this.physicalWindowTokens = config.physicalWindowTokens;
292
+ // The window size converted as the projection's comparison (`projected > window`) converts it, so a string such
293
+ // as "200000" from a JSON or YAML config is its number, for every rule that reads it. A value whose number isn't
294
+ // finite is no window: null, NaN and Infinity, which the comparison never passed, and -Infinity, which it always
295
+ // did, a restart at every boundary.
296
+ const window = config.physicalWindowTokens == null ? NaN : Number(config.physicalWindowTokens);
297
+ this.physicalWindowTokens = Number.isFinite(window) ? window : undefined;
217
298
  this.contextBudgetTokens = config.contextBudgetTokens;
218
299
  this.configuredContextBudgetTokens = config.contextBudgetTokens;
219
300
  this.contextManager = contextManager;
@@ -845,6 +926,54 @@ export class Agent {
845
926
  getShownWatermark() {
846
927
  return this.shownWatermark;
847
928
  }
929
+ /**
930
+ * The newest consumed watermark a request carried that was answered: its
931
+ * round's tool calls, or its completion, came back. A message a boundary
932
+ * injected counts as heard only once a request carrying it is answered;
933
+ * the consumed watermark moves when the stream is handed it, before its
934
+ * request runs, so a request that fails, ending its stream with an error,
935
+ * leaves this as it was.
936
+ */
937
+ answeredWatermark = null;
938
+ getAnsweredWatermark() {
939
+ return this.answeredWatermark;
940
+ }
941
+ /** A request that carried `watermark` was answered. Requests are answered
942
+ * in the order they're sent, and the consumed watermark only advances
943
+ * within a branch, so the latest is the newest. */
944
+ markAnswered(watermark) {
945
+ if (watermark)
946
+ this.answeredWatermark = watermark;
947
+ }
948
+ /**
949
+ * Per destination (a server's channel, by its key), the newest consumed
950
+ * watermark the agent had read when it published there by a route the
951
+ * framework sees (its prose, a sleep's announcement, a channel_publish, a
952
+ * draft resend, or a send tool whose channel the framework records), on
953
+ * the branch it was taken on. A wake that carries a channel, unless it's
954
+ * marked ambient (InferenceRequest.ambient), keeps its turn unless the
955
+ * agent spoke there after reading the write the wake is for. It
956
+ * lives as long as this Agent: an agent made again starts it empty, and
957
+ * such a wake then stays.
958
+ */
959
+ publishedThrough = new Map();
960
+ /** Note a publish into `destination` (its key), made having read through
961
+ * `readThrough`: the consumed watermark when its words were written, or
962
+ * its call made. */
963
+ notePublished(destination, readThrough) {
964
+ if (!readThrough)
965
+ return;
966
+ const noted = this.publishedThrough.get(destination);
967
+ if (noted && noted.branch === readThrough.branch && noted.sequence >= readThrough.sequence)
968
+ return;
969
+ this.publishedThrough.set(destination, readThrough);
970
+ }
971
+ /** Whether the agent published into `destination` (its key) having read
972
+ * the row stored at `sequence` on `branch`. */
973
+ publishedAfterReading(destination, branch, sequence) {
974
+ const noted = this.publishedThrough.get(destination);
975
+ return !!noted && noted.branch === branch && noted.sequence >= sequence;
976
+ }
848
977
  /** Mark everything currently stored as consumed (the agent's creation, at
849
978
  * boot or later, and a tool boundary that injected messages into a live
850
979
  * stream declaring it carries them; see consumedWatermark). */
@@ -852,7 +981,8 @@ export class Agent {
852
981
  // Tolerates partial context-manager doubles (tests build Agents over
853
982
  // stubs). Without a watermark, a reader that looks for one takes its own
854
983
  // side: the coalescer counts the message as read, and the framework's
855
- // deferredWriteReadOrGone and unreadNoticesForPrimary count it as unread.
984
+ // unreadNoticesForPrimary counts it as unread. A deferred write's wake
985
+ // reads the answered watermark instead (deferredWriteDone).
856
986
  this.consumedWatermark = this.pendingWatermark();
857
987
  this.watermarkMarks++;
858
988
  this.shownWatermark = this.consumedWatermark;
@@ -920,7 +1050,10 @@ export class Agent {
920
1050
  * manager commits what it commits for one, the consumed watermark moves,
921
1051
  * and a prepared budget change settles. To inspect what the agent would
922
1052
  * see, use the framework's `previewActivation`, which compiles as a dry
923
- * run. */
1053
+ * run. It isn't told the agent's thinking binding (`thinkingBinding.binds`),
1054
+ * so a context manager that keeps a thinking-binding record neither reads
1055
+ * nor writes the record here, and what it returns keeps thinking whose
1056
+ * earlier conversation changed. */
924
1057
  async compileContext(budget) {
925
1058
  // RFC-006 §3.3: consumption is determined at assembly — a compile that
926
1059
  // fails assembled nothing, so the watermark moves only on success.
@@ -942,6 +1075,203 @@ export class Agent {
942
1075
  this.applyCompileWatermark(watermark, marksBefore);
943
1076
  return result;
944
1077
  }
1078
+ /**
1079
+ * The stored context injections of this agent's that the last compile it
1080
+ * built to send rendered (stored-injections.ts), the framework's activation
1081
+ * request's or the direct API's: for each namespace and content, the parts
1082
+ * the compile held, and the branch it read. A compile built to send whose
1083
+ * request then isn't sent (a stop, a failure) still records: its rows stay
1084
+ * in the window all the same. Undefined before the first, as after a
1085
+ * restart. The framework's same-content skip reads it (renderedInjection).
1086
+ */
1087
+ renderedInjections;
1088
+ /**
1089
+ * Per branch (by id and created), the point a stored injection on it has
1090
+ * to come after to have been in no request yet (unsentInjection): the
1091
+ * newest row of this agent's window on that branch when the first plan
1092
+ * there since its last compile built to send (a start's, or a preview's,
1093
+ * which stores nothing) asked about a unit, before that plan's start
1094
+ * stored anything. Each compile built to send that records what it
1095
+ * held unsets its branch's, a restart unsets them all, and a plan asks
1096
+ * here before it stores a unit, so every one of this agent's stored
1097
+ * injections on a branch after its point was stored since that compile.
1098
+ * Kept per branch, so a start or preview on another branch doesn't move
1099
+ * this one's past a copy no request has had.
1100
+ */
1101
+ unsentSince = new Map();
1102
+ /**
1103
+ * A host's hook, called with the messages of each compile built to send
1104
+ * (never a dry run), as the compile is recorded: what the request carries,
1105
+ * after compression and the window have done their work. The framework
1106
+ * uses it to tell when an MCPL toolset's announcement has left the context
1107
+ * (RFC-014 §8.3 reminders). It must not change the messages; one that
1108
+ * throws is logged, and the start goes on.
1109
+ */
1110
+ onCompiledToSend;
1111
+ /**
1112
+ * The newest content of `namespace` among this agent's rows stored since
1113
+ * its last compile built to send (unsentSince), and whether every part of
1114
+ * it is among them: rows a start stored whose compile then didn't record
1115
+ * (it threw, or the start failed before it), which no request has had
1116
+ * yet, and which are newer than anything renderedInjection knows. Undefined when there are none, as at every
1117
+ * start whose last compile was built and recorded. A fold between that
1118
+ * start and the next (a host's own committing compile, or the compression
1119
+ * an over-budget retry waits for) can summarize them all the same: the
1120
+ * next request then has the summary's word for them, and the start after
1121
+ * it stores them again, as after any fold. The window is read back 64
1122
+ * rows at a time from the newest, stopping at that point.
1123
+ */
1124
+ unsentInjection(namespace) {
1125
+ let newest;
1126
+ try {
1127
+ const branch = branchKey(this.contextManager.currentBranchRef());
1128
+ const since = this.unsentSince.get(branch);
1129
+ if (since === undefined) {
1130
+ const count = this.contextManager.getMessageCount();
1131
+ const top = count > 0 ? this.contextManager.getMessageWindow(count - 1, 1, { resolveBlobs: false }).messages[0]?.sequence ?? 0 : 0;
1132
+ this.unsentSince.set(branch, top);
1133
+ return undefined;
1134
+ }
1135
+ scan: for (let end = this.contextManager.getMessageCount(); end > 0;) {
1136
+ const span = Math.min(end, 64);
1137
+ const { messages } = this.contextManager.getMessageWindow(end - span, span, { resolveBlobs: false });
1138
+ for (let i = messages.length - 1; i >= 0; i--) {
1139
+ const row = messages[i];
1140
+ if (row.sequence <= since)
1141
+ break scan;
1142
+ const mark = storedInjectionMarkOf(row.metadata);
1143
+ if (mark?.agent !== this.name || mark.namespace !== namespace)
1144
+ continue;
1145
+ // Read from the newest back, the first copy met is the newest
1146
+ // content; its other parts pool with it.
1147
+ newest ??= { contentHash: mark.contentHash, parts: mark.parts, held: new Set() };
1148
+ if (mark.contentHash === newest.contentHash)
1149
+ newest.held.add(mark.part);
1150
+ }
1151
+ end -= span;
1152
+ }
1153
+ }
1154
+ catch (err) {
1155
+ // Where the rows read before the failure held a copy, the newest of
1156
+ // them is still the newest content (any unread row is older), and a
1157
+ // part it lacks may be unread, so it's stored again at worst. Where
1158
+ // they held none, the last request's record decides, as it did before
1159
+ // this check: a copy a failed start stored is then stored again, or,
1160
+ // where the source has changed back to what that request held, left
1161
+ // newest for one more request. Either way the start goes on, where
1162
+ // failing here would lose its turn.
1163
+ console.error(`[injection] ${this.name}: could not read its window for copies stored since its last request, so ${newest ? 'the rows it read decide' : "that request's record decides"}:`, err);
1164
+ if (!newest)
1165
+ return undefined;
1166
+ }
1167
+ return newest && { contentHash: newest.contentHash, whole: newest.held.size === newest.parts };
1168
+ }
1169
+ /** Record which of this agent's stored injections a compile built to send
1170
+ * rendered. Another agent's stored rows never reach this agent's compile,
1171
+ * since every compile of a shared store leaves them out by its view
1172
+ * filter (isAnotherAgentsInjection): a compile of a shared store without
1173
+ * that filter would mix them in here. */
1174
+ noteRenderedInjections(result) {
1175
+ // The host's look at what this request carries (onCompiledToSend).
1176
+ if (this.onCompiledToSend) {
1177
+ try {
1178
+ this.onCompiledToSend(result.messages);
1179
+ }
1180
+ catch (err) {
1181
+ console.error(`[agent] ${this.name}: the host's compile observer failed:`, err);
1182
+ }
1183
+ }
1184
+ const provenance = result.provenance;
1185
+ // The rows stored before this compile on its branch have been compiled
1186
+ // to send, whether the request held them or a fold or the strategy's
1187
+ // window took them (the record below says which): the first plan there
1188
+ // after it, a start's or a preview's, sets the point again
1189
+ // (unsentInjection). Without provenance, which branch isn't known, so
1190
+ // every branch's point goes, rather than one surviving a compile that
1191
+ // held its rows.
1192
+ if (provenance)
1193
+ this.unsentSince.delete(branchKey(provenance.branch));
1194
+ else
1195
+ this.unsentSince.clear();
1196
+ if (!provenance) {
1197
+ this.renderedInjections = undefined;
1198
+ return;
1199
+ }
1200
+ const byNamespace = new Map();
1201
+ for (const [i, source] of provenance.messages.entries()) {
1202
+ // Only a message rendered as an injection's participant can be one, so
1203
+ // the store is read for those alone.
1204
+ if (source.kind !== 'raw' || !result.messages[i]?.participant.startsWith('system_context:'))
1205
+ continue;
1206
+ for (const body of source.bodies) {
1207
+ const mark = this.storedMarkOf(body.messageId);
1208
+ if (!mark)
1209
+ continue;
1210
+ // A part counts as held when all its shards are there. One the
1211
+ // strategy altered (cut at its per-message cap, an image stripped)
1212
+ // counts too: a new copy would meet the same, so storing again
1213
+ // would only add copies, every start. A part missing shards still
1214
+ // says which content is newest.
1215
+ const held = body.complete || (body.missing !== undefined && !body.missing.includes('shards'));
1216
+ const contents = byNamespace.get(mark.namespace) ?? new Map();
1217
+ byNamespace.set(mark.namespace, contents);
1218
+ // Copies of the same content in view pool what they hold: the agent
1219
+ // has each part that one of them holds.
1220
+ const known = contents.get(mark.contentHash) ?? { parts: mark.parts, held: new Set(), sequence: body.sequence };
1221
+ if (held)
1222
+ known.held.add(mark.part);
1223
+ known.sequence = Math.max(known.sequence, body.sequence);
1224
+ contents.set(mark.contentHash, known);
1225
+ }
1226
+ }
1227
+ this.renderedInjections = { branch: provenance.branch, byNamespace };
1228
+ }
1229
+ /**
1230
+ * The newest content of `namespace` among this agent's stored injections
1231
+ * that the last compile built to send rendered, by its newest copy: its
1232
+ * content hash, and whether every part of that content was there in some
1233
+ * copy, every shard, however the strategy shaped it. Undefined when none
1234
+ * was, when this agent hasn't built a request since it started, or when
1235
+ * the window's branch has changed since.
1236
+ */
1237
+ renderedInjection(namespace) {
1238
+ const rendered = this.renderedInjections;
1239
+ const branch = this.contextManager.currentBranchRef();
1240
+ if (!rendered || rendered.branch.id !== branch.id || rendered.branch.created !== branch.created)
1241
+ return undefined;
1242
+ let newest;
1243
+ for (const entry of rendered.byNamespace.get(namespace) ?? []) {
1244
+ if (!newest || entry[1].sequence > newest[1].sequence)
1245
+ newest = entry;
1246
+ }
1247
+ return newest ? { contentHash: newest[0], whole: newest[1].held.size === newest[1].parts } : undefined;
1248
+ }
1249
+ /**
1250
+ * Whether compiled message `i` of `result` is a row of this agent's stored
1251
+ * context injections (stored-injections.ts): rendered as an injection's
1252
+ * participant, and each of its stored rows, by the compile's provenance,
1253
+ * carrying this agent's mark. A speaker merely named like an injection's
1254
+ * participant isn't one. Only such a message's rows are read, so a start
1255
+ * reads the store for those alone.
1256
+ */
1257
+ isStoredInjectionRow(result, i) {
1258
+ const source = result.provenance?.messages[i];
1259
+ return source?.kind === 'raw' && source.bodies.length > 0
1260
+ && !!result.messages[i]?.participant.startsWith('system_context:')
1261
+ && source.bodies.every((b) => this.storedMarkOf(b.messageId)?.agent === this.name);
1262
+ }
1263
+ /** A stored row's injection mark, or undefined for any other row, and for
1264
+ * one the store can't read just now, which is logged: a start doesn't fail
1265
+ * on it (the row then counts as no stored injection). */
1266
+ storedMarkOf(id) {
1267
+ try {
1268
+ return storedInjectionMarkOf(this.contextManager.getMessage(id)?.metadata);
1269
+ }
1270
+ catch (err) {
1271
+ console.error(`[injection] ${this.name}: could not read stored row ${id}, so it counts as no stored injection:`, err);
1272
+ return undefined;
1273
+ }
1274
+ }
945
1275
  /**
946
1276
  * Compile the context with injections (e.g. from MCPL servers), which the
947
1277
  * context manager merges into the compiled messages. Without
@@ -953,9 +1283,8 @@ export class Agent {
953
1283
  async compileWithInjections(budget, injections, opts) {
954
1284
  // A dry run is a compile that will never be sent. The context manager
955
1285
  // persists no fold resolutions for it and queues none of the compression
956
- // or merge work its fold plan calls for. Its thinking binding
957
- // (context-manager#160, not yet released) will commit stamps and add a
958
- // compile awaiting acceptance for a committing compile only. Here nothing
1286
+ // or merge work its fold plan calls for, and, with the thinking binding
1287
+ // (`thinkingBinding.binds`), writes no binding record. Here nothing
959
1288
  // moves either: the agent never read what a dry run assembled, so the
960
1289
  // consumed watermark stays. A dry run proves nothing about the budget
961
1290
  // either, so it goes straight to the compile, around
@@ -997,14 +1326,22 @@ export class Agent {
997
1326
  // ==========================================================================
998
1327
  /**
999
1328
  * Run inference and return result with tool calls and speech content.
1000
- * Updates agent state during execution.
1329
+ * Updates agent state during execution. Its compile commits. With
1330
+ * `thinkingBinding.binds` it also writes the context manager's
1331
+ * thinking-binding record, so then call it only while none of this agent's
1332
+ * requests is streaming: a stream open meanwhile then has its later notes
1333
+ * write nothing, and its replies go without their thinking at the next
1334
+ * compile. Its own reply is never noted, so with `binds` its thinking is
1335
+ * left out at the compile after it's stored.
1001
1336
  */
1002
1337
  async runInference(availableTools, budget, options = {}) {
1003
1338
  return this.runInferenceWithInjections(availableTools, undefined, budget, options);
1004
1339
  }
1005
1340
  /**
1006
1341
  * Run inference with context injections.
1007
- * Same as runInference but passes injections through to compile.
1342
+ * Same as runInference but passes injections through to compile. Its
1343
+ * compile commits, and with `thinkingBinding.binds` writes the
1344
+ * thinking-binding record, as runInference's does (see there).
1008
1345
  */
1009
1346
  async runInferenceWithInjections(availableTools, injections, budget, options) {
1010
1347
  if (this._state.status === 'inferring') {
@@ -1037,8 +1374,13 @@ export class Agent {
1037
1374
  // been retried; one whose store still fails is compiled as the bare
1038
1375
  // notice.
1039
1376
  let unguardedResults;
1377
+ const binding = this.bindingCompileOptions(tools, (injections ?? [])
1378
+ .filter((injection) => injection.position === 'system')
1379
+ .flatMap((injection) => injection.content));
1040
1380
  const assemble = async () => {
1041
- const compiled = await this.toolResultGuard.afterAnnotations(() => this.compileWithInjections(budget, injections));
1381
+ const compiled = await this.toolResultGuard.afterAnnotations(() => this.compileWithInjections(budget, injections, binding.thinkingBinding ? binding : undefined));
1382
+ // What it holds of the stored injections is what the agent last saw.
1383
+ this.noteRenderedInjections(compiled);
1042
1384
  const { systemInjections } = compiled;
1043
1385
  // The framework's own pricing stamp never goes out (thinking-token-stamp.ts).
1044
1386
  const messages = withoutTokenEstimates(compiled.messages);
@@ -1154,7 +1496,10 @@ export class Agent {
1154
1496
  * watermark); a preview passes `options.dryRun`, so its compile commits
1155
1497
  * none of that (see `compileWithInjections` for what a dry run still
1156
1498
  * leaves). Either way the context manager is handed the compression tool
1157
- * definitions. Safe to call regardless of the agent's current status.
1499
+ * definitions. Safe to call regardless of the agent's current status,
1500
+ * except that with `thinkingBinding.binds` a compile that isn't a dry run
1501
+ * writes the context manager's binding record, so while one of the
1502
+ * agent's requests streams, a call to look passes `options.dryRun`.
1158
1503
  * It doesn't wait for the tool-result guard's annotations, so a preview
1159
1504
  * never waits on a workspace write (rollback, undo and redo report one), and
1160
1505
  * may show a withheld stub before its place is added; the activation waits
@@ -1185,12 +1530,63 @@ export class Agent {
1185
1530
  system: this.buildSystemPrompt(prospectiveSystemInjections),
1186
1531
  })
1187
1532
  : undefined;
1188
- let { messages, systemInjections } = await this.compileWithInjections(budget, injections, immutablePrefixHash || options.dryRun
1533
+ const binding = this.bindingCompileOptions(availableTools, prospectiveSystemInjections);
1534
+ const compiledResult = await this.compileWithInjections(budget, injections, immutablePrefixHash || options.dryRun || binding.thinkingBinding
1189
1535
  ? {
1190
1536
  ...(immutablePrefixHash ? { kvUnifiedImmutablePrefixHash: immutablePrefixHash } : {}),
1191
1537
  ...(options.dryRun ? { dryRun: true } : {}),
1538
+ ...binding,
1192
1539
  }
1193
1540
  : undefined);
1541
+ let { messages } = compiledResult;
1542
+ const { systemInjections } = compiledResult;
1543
+ // It counts what the compile selected, so a preview's stand-ins
1544
+ // (appendedMessages, below) aren't in it.
1545
+ const { renderStats } = compiledResult;
1546
+ // What the request is built from, as the compile returned it: a block the provider drops is found again in
1547
+ // it, through the copies below, by its signature (placeThinkingDrops).
1548
+ const recordedAfter = compiledResult.thinkingRecordedAfter;
1549
+ const compiled = {
1550
+ messages: compiledResult.messages,
1551
+ ...(compiledResult.provenance ? { provenance: compiledResult.provenance } : {}),
1552
+ ...(recordedAfter !== undefined ? { recordedAfter } : {}),
1553
+ };
1554
+ // Each message's place in the compile, or a preview's stand-in (null),
1555
+ // for the count of stored rows the request ends on, below.
1556
+ let origin = messages.map((_, i) => i);
1557
+ // A request that's sent says which stored injections the agent now has in
1558
+ // view, which the next start's same-content skip reads (stored-injections.ts).
1559
+ if (!options.dryRun)
1560
+ this.noteRenderedInjections(compiledResult);
1561
+ const appended = options.appendedMessages ?? [];
1562
+ if (appended.length > 0) {
1563
+ // Where a start's compile would render them, as the window's newest
1564
+ // rows: last, unless the window has no user message, where the compile
1565
+ // places the injections it's given at the end, after the window.
1566
+ const sources = compiledResult.provenance?.messages;
1567
+ let at = messages.length;
1568
+ if (sources && !messages.some((m, i) => sources[i]?.kind !== 'injection' && m.participant.toLowerCase() === 'user')) {
1569
+ while (at > 0 && sources[at - 1]?.kind === 'injection')
1570
+ at--;
1571
+ }
1572
+ origin = [...origin.slice(0, at), ...appended.map(() => null), ...origin.slice(at)];
1573
+ messages = [...messages.slice(0, at), ...appended, ...messages.slice(at)];
1574
+ }
1575
+ // The stored context injections the request ends on, counted over the
1576
+ // messages the sanitizer below keeps (hasRenderedContent), since it drops
1577
+ // a message it leaves empty, a placed blank injection among them.
1578
+ // [Continue] goes after them, and a tool loop's prompt is read from
1579
+ // before them: they're context, not what woke the agent. An injection
1580
+ // compile() places ends the tail, as on main, where every one was placed.
1581
+ let injectionTail = 0;
1582
+ for (let i = messages.length - 1; i >= 0; i--) {
1583
+ if (!hasRenderedContent(messages[i].content))
1584
+ continue;
1585
+ const from = origin[i] ?? null;
1586
+ if (from !== null && !this.isStoredInjectionRow(compiledResult, from))
1587
+ break;
1588
+ injectionTail++;
1589
+ }
1194
1590
  // Sanitize: strip empty/whitespace text blocks and drop messages left with
1195
1591
  // no content. The Anthropic API rejects empty text blocks with 400
1196
1592
  // "messages: text content blocks must be non-empty"; when such a block
@@ -1202,14 +1598,10 @@ export class Agent {
1202
1598
  // 2026-07-10 on a resident agent: one empty block muted the agent's live
1203
1599
  // path entirely; twin of context-manager's stripEmptyTextBlocks on the
1204
1600
  // compression path.)
1601
+ // The same pass a tool boundary applies to what it notes as sent
1602
+ // (sent-rows.ts), so the two can't drift.
1205
1603
  messages = messages
1206
- .map((m) => ({
1207
- ...m,
1208
- content: m.content.filter(
1209
- // typeof guard is deliberate runtime defense: history loaded from
1210
- // disk can carry a non-string `text` despite what the types claim.
1211
- (b) => !(b.type === "text" && (typeof b.text !== "string" || b.text.trim() === ""))),
1212
- }))
1604
+ .map((m) => ({ ...m, content: m.content.filter(carriedBlock) }))
1213
1605
  .filter((m) => m.content.length > 0);
1214
1606
  // The framework's own pricing stamp never goes out (thinking-token-stamp.ts).
1215
1607
  messages = withoutTokenEstimates(messages);
@@ -1233,23 +1625,31 @@ export class Agent {
1233
1625
  && !rendered.separatedTicks.has(tickKey(options.silentHeartbeat));
1234
1626
  // The [Continue] prompt this request's reply follows, read from the
1235
1627
  // request itself: a new one when it ends on [Continue]; else, when it
1236
- // ends on tool results, the prompt of the reply that called those tools,
1237
- // whose tool loop this reply continues; else none. A request that ends
1628
+ // ends on tool results (apart from stored context injections after
1629
+ // them), the prompt of the reply that called those tools, whose tool
1630
+ // loop this reply continues; else none. A request that ends
1238
1631
  // on anything else (a message that arrived during a cooldown, say) gets
1239
1632
  // a reply that follows that message and carries no prompt.
1240
1633
  let continuePrompt;
1241
1634
  if (openingTick) {
1242
1635
  messages = [...messages, silentHeartbeatSeparatorTurn()];
1243
1636
  }
1244
- else if (messages.length > 0 && messages[messages.length - 1].participant === this.name) {
1637
+ else if (endsOnOwnMessage(messages, this.name, injectionTail)) {
1245
1638
  // Safety: ensure messages don't end with an assistant message.
1246
1639
  // Some models reject trailing assistant messages ("prefill not supported"),
1247
1640
  // and after context compression a stale assistant turn can end up last.
1641
+ // Where stored context injections follow the agent's message, as a
1642
+ // changed one does on a wake with nothing new, [Continue] goes after
1643
+ // them, so the cue stays last: the block isn't taken for what woke
1644
+ // the agent. Its reply's promptedBy puts it there in later compiles too,
1645
+ // where they can recognise the reply (renderRequestOnlyRows).
1248
1646
  messages = [...messages, continueTurn()];
1249
1647
  continuePrompt = { turn: randomUUID(), text: CONTINUE_ROW };
1250
1648
  }
1251
1649
  else {
1252
- continuePrompt = toolLoopPrompt(messages.at(-1), index);
1650
+ // What the request ends on apart from the stored injections after it,
1651
+ // which aren't something the reply answers.
1652
+ continuePrompt = toolLoopPrompt(messages.at(-1 - injectionTail), index);
1253
1653
  }
1254
1654
  const request = {
1255
1655
  messages: this.toolResultGuard.prepareRequest(messages),
@@ -1258,23 +1658,26 @@ export class Agent {
1258
1658
  ...this.requestSettings(),
1259
1659
  ...(kvUnified ? { cacheMarkers: 'cm-owned' } : {}),
1260
1660
  };
1261
- return { request, ...(continuePrompt ? { continuePrompt } : {}) };
1661
+ if (options.dryRun)
1662
+ dryCompileStats.set(request, renderStats);
1663
+ return { request, ...(continuePrompt ? { continuePrompt } : {}), compiled, binding };
1262
1664
  }
1263
1665
  /**
1264
1666
  * The request fields that come from this agent's own settings: its model
1265
- * config, prompt caching and cache TTL, prefill message, provider
1266
- * parameters and participant name. Every request the agent sends takes
1267
- * them from here, a framework turn's (assembleActivationRequest) and the
1268
- * direct API's (runInferenceWithInjections), so a setting reaches both or
1269
- * neither.
1667
+ * config, thinking binding, prompt caching and cache TTL, prefill message,
1668
+ * provider parameters and participant name. Every request the agent sends
1669
+ * takes them from here, a framework turn's (assembleActivationRequest) and
1670
+ * the direct API's (runInferenceWithInjections), so a setting reaches both
1671
+ * or neither.
1270
1672
  */
1271
1673
  requestSettings() {
1674
+ const thinking = this.requestThinking();
1272
1675
  return {
1273
1676
  config: {
1274
1677
  model: this.model,
1275
1678
  maxTokens: this.maxTokens,
1276
1679
  ...(this.temperature !== undefined && { temperature: this.temperature }),
1277
- ...(this.thinking !== undefined && { thinking: this.thinking }),
1680
+ ...(thinking !== undefined && { thinking }),
1278
1681
  },
1279
1682
  promptCaching: this.promptCaching,
1280
1683
  cacheTtl: this.cacheTtl,
@@ -1283,6 +1686,70 @@ export class Agent {
1283
1686
  assistantParticipant: this.name,
1284
1687
  };
1285
1688
  }
1689
+ /**
1690
+ * The thinking config a request carries: the agent's own, with the binding
1691
+ * control added when `thinkingBinding.dropBlock` asks for it. A model whose
1692
+ * thinking is always on takes the control whatever `enabled` says, so an
1693
+ * agent with no thinking config of its own still sends one, holding only
1694
+ * the control and `enabled: false`. Membrane sends nothing from it to any
1695
+ * other model, since thinking is off there.
1696
+ */
1697
+ requestThinking() {
1698
+ if (!this.thinkingDropBlock)
1699
+ return this.thinking;
1700
+ const own = this.thinking !== null && typeof this.thinking === 'object' ? this.thinking : { enabled: false };
1701
+ return { ...own, blockBinding: { prefixMismatchBehavior: 'drop_block' } };
1702
+ }
1703
+ /** The stream's way to tell the context manager what its later rounds sent, with the head its compile was given:
1704
+ * where the agent's model binds its thinking (context-manager's `noteRequestSent`). */
1705
+ requestNotes(binding, compiled) {
1706
+ const identity = binding.identity;
1707
+ // Each note names the compile the stream was built from, so a note can't vouch for this stream under a record a
1708
+ // later committing compile with binds wrote. A compile that reports no provenance gives the stream nothing to name, and the
1709
+ // stream notes nothing: its replies go without their thinking at the next compile, never refused.
1710
+ const compileId = compiled.provenance?.compileId;
1711
+ if (!identity || compileId === undefined)
1712
+ return {};
1713
+ const cm = this.contextManager;
1714
+ return { noteRequestSent: (rows) => cm.noteRequestSent(rows, identity, compileId) };
1715
+ }
1716
+ /**
1717
+ * The binding a compile of this agent is told of (bindingCompileOptions), and a preview of its context too: the
1718
+ * participant whose messages are its replies is its own name. Undefined where the model doesn't bind.
1719
+ * @internal For the framework's preview and its budget rule; not a host API.
1720
+ */
1721
+ thinkingBindingOption() {
1722
+ return this.thinkingBinds ? { binds: true, dropBlock: this.thinkingDropBlock, participant: this.name } : undefined;
1723
+ }
1724
+ /**
1725
+ * What a compile the agent sends tells the context manager when the model binds its thinking
1726
+ * (`thinkingBinding.binds`): the binding as set, with the agent's own name as the participant whose messages
1727
+ * are its replies (an agent stores its replies under its name), and a digest of each part of the request ahead of
1728
+ * its messages, so a changed one can stand for a first difference where the context manager keeps a
1729
+ * thinking-binding record. The system text is the one the request will carry, built from the system-position
1730
+ * injections given to the compile as the kv-unified prefix hash builds it; the tools are the ones it will carry, in
1731
+ * their order; `request` covers the thinking config, `maxTokens` and `providerParams`, where a host puts its own
1732
+ * thinking config and `tool_choice`, and `prefillUserMessage`, which membrane sends as a leading user turn ahead
1733
+ * of a conversation that would begin with the assistant. Nothing without `binds`: the compile is as it was.
1734
+ */
1735
+ bindingCompileOptions(tools, systemInjections) {
1736
+ const thinkingBinding = this.thinkingBindingOption();
1737
+ if (!thinkingBinding)
1738
+ return {};
1739
+ const { config, providerParams, prefillUserMessage } = this.requestSettings();
1740
+ return {
1741
+ thinkingBinding,
1742
+ identity: {
1743
+ system: wireDigest(this.buildSystemPrompt(systemInjections)),
1744
+ tools: wireDigest(tools),
1745
+ model: wireDigest(this.model),
1746
+ request: wireDigest({
1747
+ thinking: config.thinking ?? null, maxTokens: config.maxTokens, providerParams: providerParams ?? null,
1748
+ prefillUserMessage: prefillUserMessage ?? null,
1749
+ }),
1750
+ },
1751
+ };
1752
+ }
1286
1753
  /** The request `assembleActivationRequest` builds (see there), for preview
1287
1754
  * and debug tooling: what this agent's next activation would send. */
1288
1755
  async buildActivationRequest(availableTools, injections, budget, compressionTools = availableTools, options = {}) {
@@ -1359,7 +1826,7 @@ export class Agent {
1359
1826
  // Compiled only once each withheld stub's annotation has finished,
1360
1827
  // including one that began during the compile, and after a stub edit that
1361
1828
  // failed has been retried (see afterAnnotations).
1362
- const { request, continuePrompt } = await this.toolResultGuard.afterAnnotations(() => this.assembleActivationRequest(availableTools, injections, budget, compressionTools, options));
1829
+ const { request, continuePrompt, compiled, binding } = await this.toolResultGuard.afterAnnotations(() => this.assembleActivationRequest(availableTools, injections, budget, compressionTools, options));
1363
1830
  request.messages = this.toolResultGuard.prepareRequest(request.messages, true);
1364
1831
  const receiptAware = this.contextManager
1365
1832
  .getStrategy?.();
@@ -1385,6 +1852,12 @@ export class Agent {
1385
1852
  emitTokens: true,
1386
1853
  emitBlocks: false,
1387
1854
  emitUsage: true,
1855
+ // A caller that retries itself (the framework's turns: errorPolicy,
1856
+ // provider holds, stated waits, each attempt a fresh compile a stop can
1857
+ // cancel) has membrane send a failed round once and hand the error up:
1858
+ // since membrane 0.7 its own schedules, ten minutes at a 529, would
1859
+ // otherwise run inside each of the caller's attempts, out of its sight.
1860
+ ...(options.membraneRetries === false ? { retry: false } : {}),
1388
1861
  // Retry a content-policy refusal at the provider seam rather than at
1389
1862
  // the framework level: membrane replays the SAME request immediately
1390
1863
  // (cache-warm), where a framework-level requeue would recompile and
@@ -1403,6 +1876,10 @@ export class Agent {
1403
1876
  stream,
1404
1877
  request,
1405
1878
  ...(continuePrompt ? { continuePrompt } : {}),
1879
+ // Read against the messages the stream sends, which membrane's report indexes (RoundReport's coordinates).
1880
+ placeDrops: (entries) => placeThinkingDrops(entries, request.messages, compiled),
1881
+ ...this.requestNotes(binding, compiled),
1882
+ ...(compiled.recordedAfter !== undefined ? { thinkingRecordedAfter: compiled.recordedAfter } : {}),
1406
1883
  ...(kvEnabled
1407
1884
  ? {
1408
1885
  takeKvSubmission: () => kvQueue.shift(),
@@ -1473,9 +1950,9 @@ export class Agent {
1473
1950
  console.error(`[assistant-persist] agent=${this.name}: refusing to store a thinking-only assistant ` +
1474
1951
  `message (${content.length} block(s), no text and no tool_use) — the turn produced no ` +
1475
1952
  `output. See the refusal/inference-failed record for why.`);
1476
- return;
1953
+ return undefined;
1477
1954
  }
1478
- this.contextManager.addMessage(this.name, content, metadata);
1955
+ return this.contextManager.addMessage(this.name, content, metadata);
1479
1956
  }
1480
1957
  /**
1481
1958
  * Transition back to streaming state after tool results are provided.
@@ -1693,7 +2170,7 @@ export class Agent {
1693
2170
  toolUseId: r.id,
1694
2171
  content: isError
1695
2172
  ? truncateForHistory(typeof error === 'string' ? error.toWellFormed() : error, DEFAULT_TOOL_RESULT_INLINE_MAX_CHARS)
1696
- : nonErrorResultText(r.result, DEFAULT_TOOL_RESULT_INLINE_MAX_CHARS),
2173
+ : nonErrorResultText(r.result, DEFAULT_TOOL_RESULT_INLINE_MAX_CHARS, { toolName: r.name }),
1697
2174
  isError,
1698
2175
  };
1699
2176
  });