agentfootprint 7.17.0 → 7.19.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 (202) hide show
  1. package/AGENTS.md +1 -1
  2. package/CLAUDE.md +2 -2
  3. package/ai-instructions/claude-code/SKILL.md +1 -1
  4. package/dist/adapters/hosting/agentcore.js +23 -9
  5. package/dist/adapters/hosting/agentcore.js.map +1 -1
  6. package/dist/core/Agent.js +57 -2
  7. package/dist/core/Agent.js.map +1 -1
  8. package/dist/core/RunnerBase.js +16 -1
  9. package/dist/core/RunnerBase.js.map +1 -1
  10. package/dist/core/agent/AgentBuilder.js +117 -1
  11. package/dist/core/agent/AgentBuilder.js.map +1 -1
  12. package/dist/core/agent/middleware/errors.js +54 -0
  13. package/dist/core/agent/middleware/errors.js.map +1 -0
  14. package/dist/core/agent/middleware/index.js +23 -0
  15. package/dist/core/agent/middleware/index.js.map +1 -0
  16. package/dist/core/agent/middleware/ledger.js +61 -0
  17. package/dist/core/agent/middleware/ledger.js.map +1 -0
  18. package/dist/core/agent/middleware/outcomes.js +66 -0
  19. package/dist/core/agent/middleware/outcomes.js.map +1 -0
  20. package/dist/core/agent/middleware/runChain.js +144 -0
  21. package/dist/core/agent/middleware/runChain.js.map +1 -0
  22. package/dist/core/agent/middleware/types.js +41 -0
  23. package/dist/core/agent/middleware/types.js.map +1 -0
  24. package/dist/core/agent/stages/prepareFinal.js +10 -0
  25. package/dist/core/agent/stages/prepareFinal.js.map +1 -1
  26. package/dist/core/agent/stages/route.js +62 -1
  27. package/dist/core/agent/stages/route.js.map +1 -1
  28. package/dist/core/agent/stages/seed.js +130 -85
  29. package/dist/core/agent/stages/seed.js.map +1 -1
  30. package/dist/core/agent/stages/toolCalls.js +208 -8
  31. package/dist/core/agent/stages/toolCalls.js.map +1 -1
  32. package/dist/core/durabilityBarrier.js +68 -0
  33. package/dist/core/durabilityBarrier.js.map +1 -0
  34. package/dist/core/pause.js +19 -1
  35. package/dist/core/pause.js.map +1 -1
  36. package/dist/esm/adapters/hosting/agentcore.d.ts +4 -4
  37. package/dist/esm/adapters/hosting/agentcore.js +24 -10
  38. package/dist/esm/adapters/hosting/agentcore.js.map +1 -1
  39. package/dist/esm/core/Agent.d.ts +9 -1
  40. package/dist/esm/core/Agent.js +58 -3
  41. package/dist/esm/core/Agent.js.map +1 -1
  42. package/dist/esm/core/RunnerBase.js +16 -1
  43. package/dist/esm/core/RunnerBase.js.map +1 -1
  44. package/dist/esm/core/agent/AgentBuilder.d.ts +97 -0
  45. package/dist/esm/core/agent/AgentBuilder.js +117 -1
  46. package/dist/esm/core/agent/AgentBuilder.js.map +1 -1
  47. package/dist/esm/core/agent/buildAgentChart.d.ts +2 -2
  48. package/dist/esm/core/agent/middleware/errors.d.ts +51 -0
  49. package/dist/esm/core/agent/middleware/errors.js +50 -0
  50. package/dist/esm/core/agent/middleware/errors.js.map +1 -0
  51. package/dist/esm/core/agent/middleware/index.d.ts +16 -0
  52. package/dist/esm/core/agent/middleware/index.js +16 -0
  53. package/dist/esm/core/agent/middleware/index.js.map +1 -0
  54. package/dist/esm/core/agent/middleware/ledger.d.ts +40 -0
  55. package/dist/esm/core/agent/middleware/ledger.js +57 -0
  56. package/dist/esm/core/agent/middleware/ledger.js.map +1 -0
  57. package/dist/esm/core/agent/middleware/outcomes.d.ts +45 -0
  58. package/dist/esm/core/agent/middleware/outcomes.js +60 -0
  59. package/dist/esm/core/agent/middleware/outcomes.js.map +1 -0
  60. package/dist/esm/core/agent/middleware/runChain.d.ts +104 -0
  61. package/dist/esm/core/agent/middleware/runChain.js +139 -0
  62. package/dist/esm/core/agent/middleware/runChain.js.map +1 -0
  63. package/dist/esm/core/agent/middleware/types.d.ts +191 -0
  64. package/dist/esm/core/agent/middleware/types.js +40 -0
  65. package/dist/esm/core/agent/middleware/types.js.map +1 -0
  66. package/dist/esm/core/agent/stages/prepareFinal.d.ts +10 -0
  67. package/dist/esm/core/agent/stages/prepareFinal.js +10 -0
  68. package/dist/esm/core/agent/stages/prepareFinal.js.map +1 -1
  69. package/dist/esm/core/agent/stages/route.d.ts +29 -0
  70. package/dist/esm/core/agent/stages/route.js +60 -0
  71. package/dist/esm/core/agent/stages/route.js.map +1 -1
  72. package/dist/esm/core/agent/stages/seed.d.ts +16 -1
  73. package/dist/esm/core/agent/stages/seed.js +130 -85
  74. package/dist/esm/core/agent/stages/seed.js.map +1 -1
  75. package/dist/esm/core/agent/stages/toolCalls.d.ts +44 -0
  76. package/dist/esm/core/agent/stages/toolCalls.js +208 -8
  77. package/dist/esm/core/agent/stages/toolCalls.js.map +1 -1
  78. package/dist/esm/core/agent/types.d.ts +18 -0
  79. package/dist/esm/core/durabilityBarrier.d.ts +61 -0
  80. package/dist/esm/core/durabilityBarrier.js +63 -0
  81. package/dist/esm/core/durabilityBarrier.js.map +1 -0
  82. package/dist/esm/core/pause.d.ts +42 -0
  83. package/dist/esm/core/pause.js +17 -0
  84. package/dist/esm/core/pause.js.map +1 -1
  85. package/dist/esm/events/dispatcher.d.ts +1 -1
  86. package/dist/esm/events/dispatcher.js.map +1 -1
  87. package/dist/esm/events/payloads.d.ts +26 -0
  88. package/dist/esm/events/registry.d.ts +5 -1
  89. package/dist/esm/events/registry.js +4 -0
  90. package/dist/esm/events/registry.js.map +1 -1
  91. package/dist/esm/hosting/durability.d.ts +92 -0
  92. package/dist/esm/hosting/durability.js +174 -0
  93. package/dist/esm/hosting/durability.js.map +1 -0
  94. package/dist/esm/hosting/envelope.d.ts +75 -14
  95. package/dist/esm/hosting/envelope.js +141 -16
  96. package/dist/esm/hosting/envelope.js.map +1 -1
  97. package/dist/esm/hosting/errors.d.ts +60 -11
  98. package/dist/esm/hosting/errors.js +92 -18
  99. package/dist/esm/hosting/errors.js.map +1 -1
  100. package/dist/esm/hosting/httpHost.d.ts +17 -1
  101. package/dist/esm/hosting/httpHost.js +42 -6
  102. package/dist/esm/hosting/httpHost.js.map +1 -1
  103. package/dist/esm/hosting/index.d.ts +7 -4
  104. package/dist/esm/hosting/index.js +6 -3
  105. package/dist/esm/hosting/index.js.map +1 -1
  106. package/dist/esm/hosting/nodeHost.d.ts +4 -2
  107. package/dist/esm/hosting/nodeHost.js +14 -3
  108. package/dist/esm/hosting/nodeHost.js.map +1 -1
  109. package/dist/esm/hosting/standingAgent.d.ts +22 -7
  110. package/dist/esm/hosting/standingAgent.js +144 -32
  111. package/dist/esm/hosting/standingAgent.js.map +1 -1
  112. package/dist/esm/hosting/types.d.ts +193 -19
  113. package/dist/esm/index.d.ts +2 -1
  114. package/dist/esm/index.js +13 -1
  115. package/dist/esm/index.js.map +1 -1
  116. package/dist/esm/lib/mcp/mcpServe.js +39 -6
  117. package/dist/esm/lib/mcp/mcpServe.js.map +1 -1
  118. package/dist/esm/lib/mcp/types.d.ts +16 -0
  119. package/dist/events/dispatcher.js.map +1 -1
  120. package/dist/events/registry.js +4 -0
  121. package/dist/events/registry.js.map +1 -1
  122. package/dist/hosting/durability.js +178 -0
  123. package/dist/hosting/durability.js.map +1 -0
  124. package/dist/hosting/envelope.js +146 -18
  125. package/dist/hosting/envelope.js.map +1 -1
  126. package/dist/hosting/errors.js +95 -19
  127. package/dist/hosting/errors.js.map +1 -1
  128. package/dist/hosting/httpHost.js +42 -6
  129. package/dist/hosting/httpHost.js.map +1 -1
  130. package/dist/hosting/index.js +10 -2
  131. package/dist/hosting/index.js.map +1 -1
  132. package/dist/hosting/nodeHost.js +14 -3
  133. package/dist/hosting/nodeHost.js.map +1 -1
  134. package/dist/hosting/standingAgent.js +142 -30
  135. package/dist/hosting/standingAgent.js.map +1 -1
  136. package/dist/index.js +31 -14
  137. package/dist/index.js.map +1 -1
  138. package/dist/lib/mcp/mcpServe.js +39 -6
  139. package/dist/lib/mcp/mcpServe.js.map +1 -1
  140. package/dist/types/adapters/hosting/agentcore.d.ts +4 -4
  141. package/dist/types/adapters/hosting/agentcore.d.ts.map +1 -1
  142. package/dist/types/core/Agent.d.ts +9 -1
  143. package/dist/types/core/Agent.d.ts.map +1 -1
  144. package/dist/types/core/RunnerBase.d.ts.map +1 -1
  145. package/dist/types/core/agent/AgentBuilder.d.ts +97 -0
  146. package/dist/types/core/agent/AgentBuilder.d.ts.map +1 -1
  147. package/dist/types/core/agent/buildAgentChart.d.ts +2 -2
  148. package/dist/types/core/agent/buildAgentChart.d.ts.map +1 -1
  149. package/dist/types/core/agent/middleware/errors.d.ts +52 -0
  150. package/dist/types/core/agent/middleware/errors.d.ts.map +1 -0
  151. package/dist/types/core/agent/middleware/index.d.ts +17 -0
  152. package/dist/types/core/agent/middleware/index.d.ts.map +1 -0
  153. package/dist/types/core/agent/middleware/ledger.d.ts +41 -0
  154. package/dist/types/core/agent/middleware/ledger.d.ts.map +1 -0
  155. package/dist/types/core/agent/middleware/outcomes.d.ts +46 -0
  156. package/dist/types/core/agent/middleware/outcomes.d.ts.map +1 -0
  157. package/dist/types/core/agent/middleware/runChain.d.ts +105 -0
  158. package/dist/types/core/agent/middleware/runChain.d.ts.map +1 -0
  159. package/dist/types/core/agent/middleware/types.d.ts +192 -0
  160. package/dist/types/core/agent/middleware/types.d.ts.map +1 -0
  161. package/dist/types/core/agent/stages/prepareFinal.d.ts +10 -0
  162. package/dist/types/core/agent/stages/prepareFinal.d.ts.map +1 -1
  163. package/dist/types/core/agent/stages/route.d.ts +29 -0
  164. package/dist/types/core/agent/stages/route.d.ts.map +1 -1
  165. package/dist/types/core/agent/stages/seed.d.ts +16 -1
  166. package/dist/types/core/agent/stages/seed.d.ts.map +1 -1
  167. package/dist/types/core/agent/stages/toolCalls.d.ts +44 -0
  168. package/dist/types/core/agent/stages/toolCalls.d.ts.map +1 -1
  169. package/dist/types/core/agent/types.d.ts +18 -0
  170. package/dist/types/core/agent/types.d.ts.map +1 -1
  171. package/dist/types/core/durabilityBarrier.d.ts +62 -0
  172. package/dist/types/core/durabilityBarrier.d.ts.map +1 -0
  173. package/dist/types/core/pause.d.ts +42 -0
  174. package/dist/types/core/pause.d.ts.map +1 -1
  175. package/dist/types/events/dispatcher.d.ts +1 -1
  176. package/dist/types/events/dispatcher.d.ts.map +1 -1
  177. package/dist/types/events/payloads.d.ts +26 -0
  178. package/dist/types/events/payloads.d.ts.map +1 -1
  179. package/dist/types/events/registry.d.ts +5 -1
  180. package/dist/types/events/registry.d.ts.map +1 -1
  181. package/dist/types/hosting/durability.d.ts +93 -0
  182. package/dist/types/hosting/durability.d.ts.map +1 -0
  183. package/dist/types/hosting/envelope.d.ts +75 -14
  184. package/dist/types/hosting/envelope.d.ts.map +1 -1
  185. package/dist/types/hosting/errors.d.ts +60 -11
  186. package/dist/types/hosting/errors.d.ts.map +1 -1
  187. package/dist/types/hosting/httpHost.d.ts +17 -1
  188. package/dist/types/hosting/httpHost.d.ts.map +1 -1
  189. package/dist/types/hosting/index.d.ts +7 -4
  190. package/dist/types/hosting/index.d.ts.map +1 -1
  191. package/dist/types/hosting/nodeHost.d.ts +4 -2
  192. package/dist/types/hosting/nodeHost.d.ts.map +1 -1
  193. package/dist/types/hosting/standingAgent.d.ts +22 -7
  194. package/dist/types/hosting/standingAgent.d.ts.map +1 -1
  195. package/dist/types/hosting/types.d.ts +193 -19
  196. package/dist/types/hosting/types.d.ts.map +1 -1
  197. package/dist/types/index.d.ts +2 -1
  198. package/dist/types/index.d.ts.map +1 -1
  199. package/dist/types/lib/mcp/mcpServe.d.ts.map +1 -1
  200. package/dist/types/lib/mcp/types.d.ts +16 -0
  201. package/dist/types/lib/mcp/types.d.ts.map +1 -1
  202. package/package.json +1 -1
@@ -0,0 +1,191 @@
1
+ /**
2
+ * middleware/types — PUBLIC. The shape of a governance chain.
3
+ *
4
+ * Pattern: Chain of Responsibility (GoF), with the one dangerous answer
5
+ * removed at the type level.
6
+ * Role: core/ layer. Two chains, one vocabulary:
7
+ *
8
+ * `toolMiddleware` wraps every tool dispatch
9
+ * `messageMiddleware` wraps the message boundary — the input
10
+ * before the model sees it, the output
11
+ * before the caller receives it
12
+ *
13
+ * Emits: N/A. A middleware is a pure decision. It never touches scope,
14
+ * never emits and never writes — the stage does all of that, so
15
+ * "record everything that happened" lives in ONE place rather
16
+ * than being re-implemented per middleware.
17
+ *
18
+ * ## The law that shapes these types
19
+ *
20
+ * **A middleware cannot answer for the tool.** The outcome union has three
21
+ * arms — allow, deny, ask — and no `result` arm. There is no spelling of
22
+ * "here is what the tool would have returned". Whatever the chain decides,
23
+ * the answer the model finally reads is the real tool's output or a
24
+ * refusal. That is not a convention a reviewer has to enforce; it is the
25
+ * absence of a field.
26
+ *
27
+ * **A transform declares itself.** `allow(value, why)` requires a reason
28
+ * whenever it changes something, and the stage commits BOTH the original
29
+ * and the transformed value into the run's ledger. A prompt scrubbed by a
30
+ * middleware that hid its own scrubbing would poison every slice taken
31
+ * afterwards: the trace would show text nobody ever sent.
32
+ *
33
+ * **`ask` exists only where a pause exists.** `ToolOutcome` has it because
34
+ * tool dispatch runs inside a footprintjs pausable stage — the same door
35
+ * `checkIn` and `askHuman` already go through. `MessageOutcome` does not,
36
+ * because the message boundary is a plain stage, and inventing a second
37
+ * pause to give it one would be a worse answer than not offering it.
38
+ */
39
+ import type { LLMMessage } from '../../../adapters/types.js';
40
+ import type { MemoryIdentity } from '../../../memory/identity/types.js';
41
+ /**
42
+ * Let the call through — optionally with a replacement for what the chain
43
+ * carries forward.
44
+ *
45
+ * `allow()` passes the value along untouched. `allow(value, why)` replaces
46
+ * it and says why; the `why` is not decoration, it is the row the ledger
47
+ * shows a person asking "who changed this, and what did it look like
48
+ * before?".
49
+ */
50
+ export interface AllowOutcome<T> {
51
+ readonly kind: 'allow';
52
+ /** The replacement value. Absent = pass through unchanged. */
53
+ readonly value?: T;
54
+ /** Why the value changed. Present whenever `value` is. */
55
+ readonly why?: string;
56
+ }
57
+ /**
58
+ * Refuse the call. For a tool, `reason` reaches the model verbatim as the
59
+ * tool result and the run continues — a denial is data the agent can adapt
60
+ * to, not a crash. For a message, `reason` surfaces as a
61
+ * `MessageDeniedError` at the API boundary.
62
+ */
63
+ export interface DenyOutcome {
64
+ readonly kind: 'deny';
65
+ readonly reason: string;
66
+ }
67
+ /** Suspend the run and put the question to a person. Tool dispatch only. */
68
+ export interface AskOutcome {
69
+ readonly kind: 'ask';
70
+ readonly payload: AskPayload;
71
+ }
72
+ /** What a person is being asked. Carried verbatim to the checkpoint. */
73
+ export interface AskPayload {
74
+ /** The question, in your own words. Shown to whoever answers. */
75
+ readonly question: string;
76
+ /** Anything else the answering UI should render. Never interpreted here. */
77
+ readonly detail?: unknown;
78
+ }
79
+ /**
80
+ * Everything a tool middleware may answer. Closed, and every arm has a
81
+ * home in this codebase: allow rides the normal dispatch, deny rides the
82
+ * synthetic tool result every other gate already uses, ask rides the
83
+ * pausable-stage checkpoint that `checkIn` rides.
84
+ */
85
+ export type ToolOutcome = AllowOutcome<Readonly<Record<string, unknown>>> | DenyOutcome | AskOutcome;
86
+ /** Everything a message middleware may answer. No `ask` — see the header. */
87
+ export type MessageOutcome = AllowOutcome<string> | DenyOutcome;
88
+ /** The call a tool middleware is deciding about. */
89
+ export interface ToolMiddlewareContext {
90
+ readonly toolName: string;
91
+ /** Matches `stream.tool_start.toolCallId` for this dispatch. */
92
+ readonly toolCallId: string;
93
+ /** ReAct iteration this call belongs to. */
94
+ readonly iteration: number;
95
+ /**
96
+ * The args as THIS middleware sees them — every earlier transform in the
97
+ * chain already applied. The first middleware sees what the model asked
98
+ * for; the last sees what the tool is about to receive.
99
+ */
100
+ readonly args: Readonly<Record<string, unknown>>;
101
+ /** Conversation so far, including the assistant turn that made this call. */
102
+ readonly history: readonly LLMMessage[];
103
+ /** Multi-tenant run identity, when the run carried one. */
104
+ readonly identity?: MemoryIdentity;
105
+ /** Abort signal from `run({ env: { signal } })`. */
106
+ readonly signal?: AbortSignal;
107
+ }
108
+ /** The message a message middleware is deciding about. */
109
+ export interface MessageMiddlewareContext {
110
+ /**
111
+ * `'input'` runs at the very top of the run, BEFORE the user's message is
112
+ * committed — so the window strategies, the injections, the slots, the
113
+ * request bytes and every later slice all see the transformed text and
114
+ * agree with each other. `'output'` runs where the final answer is
115
+ * captured, so the record and the caller receive the same string.
116
+ */
117
+ readonly phase: 'input' | 'output';
118
+ /** The content as THIS middleware sees it — earlier transforms applied. */
119
+ readonly content: string;
120
+ /** Conversation so far. Empty at `'input'`. */
121
+ readonly history: readonly LLMMessage[];
122
+ readonly identity?: MemoryIdentity;
123
+ readonly signal?: AbortSignal;
124
+ }
125
+ /**
126
+ * One link in the tool-dispatch chain.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * const noProdWrites: ToolMiddleware = {
131
+ * name: 'no-prod-writes',
132
+ * onToolCall: (call) =>
133
+ * call.args.env === 'prod' ? deny('writes to prod need a change ticket') : allow(),
134
+ * };
135
+ * ```
136
+ */
137
+ export interface ToolMiddleware {
138
+ /** Identifies this middleware in every ledger row and event it produces. */
139
+ readonly name: string;
140
+ onToolCall(call: ToolMiddlewareContext): ToolOutcome | Promise<ToolOutcome>;
141
+ }
142
+ /**
143
+ * One link in the message chain. Runs at both phases unless it decides
144
+ * otherwise by reading `msg.phase`.
145
+ *
146
+ * @example
147
+ * ```ts
148
+ * const scrubSSNs: MessageMiddleware = {
149
+ * name: 'scrub-ssns',
150
+ * onMessage: (msg) => {
151
+ * const clean = msg.content.replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[ssn]');
152
+ * return clean === msg.content ? allow() : allow(clean, 'masked a US SSN');
153
+ * },
154
+ * };
155
+ * ```
156
+ */
157
+ export interface MessageMiddleware {
158
+ readonly name: string;
159
+ onMessage(msg: MessageMiddlewareContext): MessageOutcome | Promise<MessageOutcome>;
160
+ }
161
+ /**
162
+ * One row per middleware decision, committed to `scope.middlewareDecisions`.
163
+ *
164
+ * Every decision files a row, including the pass-throughs. A chain that
165
+ * only recorded its refusals would leave you unable to tell "the middleware
166
+ * looked and was fine with it" apart from "the middleware never ran" — and
167
+ * those are different facts about a run.
168
+ */
169
+ export interface MiddlewareDecision {
170
+ /** The middleware's `name`. */
171
+ readonly middleware: string;
172
+ /** Which chain this row came from. */
173
+ readonly at: 'tool' | 'message';
174
+ /** Message chain only. */
175
+ readonly phase?: 'input' | 'output';
176
+ /** Tool chain only. */
177
+ readonly toolName?: string;
178
+ /** Tool chain only. */
179
+ readonly toolCallId?: string;
180
+ /** ReAct iteration. `0` for the `'input'` phase, which runs before iter 1. */
181
+ readonly iteration: number;
182
+ readonly outcome: 'allow' | 'deny' | 'ask';
183
+ /** True when this row changed the value the chain carries forward. */
184
+ readonly changed: boolean;
185
+ /** The transform's `why`, the denial's `reason`, or the ask's `question`. */
186
+ readonly why?: string;
187
+ /** The value before this middleware. Present only when `changed`. */
188
+ readonly before?: unknown;
189
+ /** The value after this middleware. Present only when `changed`. */
190
+ readonly after?: unknown;
191
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * middleware/types — PUBLIC. The shape of a governance chain.
3
+ *
4
+ * Pattern: Chain of Responsibility (GoF), with the one dangerous answer
5
+ * removed at the type level.
6
+ * Role: core/ layer. Two chains, one vocabulary:
7
+ *
8
+ * `toolMiddleware` wraps every tool dispatch
9
+ * `messageMiddleware` wraps the message boundary — the input
10
+ * before the model sees it, the output
11
+ * before the caller receives it
12
+ *
13
+ * Emits: N/A. A middleware is a pure decision. It never touches scope,
14
+ * never emits and never writes — the stage does all of that, so
15
+ * "record everything that happened" lives in ONE place rather
16
+ * than being re-implemented per middleware.
17
+ *
18
+ * ## The law that shapes these types
19
+ *
20
+ * **A middleware cannot answer for the tool.** The outcome union has three
21
+ * arms — allow, deny, ask — and no `result` arm. There is no spelling of
22
+ * "here is what the tool would have returned". Whatever the chain decides,
23
+ * the answer the model finally reads is the real tool's output or a
24
+ * refusal. That is not a convention a reviewer has to enforce; it is the
25
+ * absence of a field.
26
+ *
27
+ * **A transform declares itself.** `allow(value, why)` requires a reason
28
+ * whenever it changes something, and the stage commits BOTH the original
29
+ * and the transformed value into the run's ledger. A prompt scrubbed by a
30
+ * middleware that hid its own scrubbing would poison every slice taken
31
+ * afterwards: the trace would show text nobody ever sent.
32
+ *
33
+ * **`ask` exists only where a pause exists.** `ToolOutcome` has it because
34
+ * tool dispatch runs inside a footprintjs pausable stage — the same door
35
+ * `checkIn` and `askHuman` already go through. `MessageOutcome` does not,
36
+ * because the message boundary is a plain stage, and inventing a second
37
+ * pause to give it one would be a worse answer than not offering it.
38
+ */
39
+ export {};
40
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/core/agent/middleware/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG"}
@@ -13,6 +13,16 @@
13
13
  *
14
14
  * Pure function — no closure over Agent class state. Imported and
15
15
  * passed directly to `flowChart(...)` in buildAgentChart.
16
+ *
17
+ * NOT the seam for `messageMiddleware`'s `'output'` half, deliberately.
18
+ * This stage runs inside the Final BRANCH subflow, whose state does not
19
+ * merge back into the run (a branch mount hands its outputMapper the
20
+ * branch's RESULT, not its scope). Rows filed here would land in an
21
+ * isolated commit log and never reach `snapshot.sharedState`, splitting
22
+ * one ledger across two places. The chain runs one stage earlier instead
23
+ * — in the Route decider, in the main chart — and rewrites
24
+ * `llmLatestContent`, which is the value this stage copies. See
25
+ * `stages/route.ts`.
16
26
  */
17
27
  import type { TypedScope } from 'footprintjs';
18
28
  import type { AgentState } from '../types.js';
@@ -13,6 +13,16 @@
13
13
  *
14
14
  * Pure function — no closure over Agent class state. Imported and
15
15
  * passed directly to `flowChart(...)` in buildAgentChart.
16
+ *
17
+ * NOT the seam for `messageMiddleware`'s `'output'` half, deliberately.
18
+ * This stage runs inside the Final BRANCH subflow, whose state does not
19
+ * merge back into the run (a branch mount hands its outputMapper the
20
+ * branch's RESULT, not its scope). Rows filed here would land in an
21
+ * isolated commit log and never reach `snapshot.sharedState`, splitting
22
+ * one ledger across two places. The chain runs one stage earlier instead
23
+ * — in the Route decider, in the main chart — and rewrites
24
+ * `llmLatestContent`, which is the value this stage copies. See
25
+ * `stages/route.ts`.
16
26
  */
17
27
  import { typedEmit } from '../../../recorders/core/typedEmit.js';
18
28
  export const prepareFinalStage = (scope) => {
@@ -1 +1 @@
1
- {"version":3,"file":"prepareFinal.js","sourceRoot":"","sources":["../../../../../src/core/agent/stages/prepareFinal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,sCAAsC,CAAC;AAGjE,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,KAA6B,EAAQ,EAAE;IACvE,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,CAAC;IAClC,KAAK,CAAC,YAAY,GAAG,KAAK,CAAC,gBAAgB,CAAC;IAC5C,gEAAgE;IAChE,mEAAmE;IACnE,oEAAoE;IACpE,iEAAiE;IACjE,+DAA+D;IAC/D,MAAM,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IAC5C,MAAM,WAAW,GAAG,cAAc,KAAK,SAAS,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,CAAC;IAC9E,6DAA6D;IAC7D,wCAAwC;IACxC,KAAK,CAAC,WAAW,GAAG;QAClB,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,WAAW,EAAE;QAC5C;YACE,IAAI,EAAE,WAAW;YACjB,OAAO,EAAE,KAAK,CAAC,YAAY;YAC3B,GAAG,CAAC,WAAW,IAAI,EAAE,cAAc,EAAE,CAAC;SACvC;KACF,CAAC;IAEF,SAAS,CAAC,KAAK,EAAE,oCAAoC,EAAE;QACrD,SAAS,EAAE,CAAC;QACZ,SAAS,EAAE,SAAS;QACpB,aAAa,EAAE,CAAC;KACjB,CAAC,CAAC;IACH,SAAS,CAAC,KAAK,EAAE,+BAA+B,EAAE;QAChD,SAAS,EAAE,CAAC;QACZ,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,SAAS;QACzB,UAAU,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,WAAW;KAC3C,CAAC,CAAC;AACL,CAAC,CAAC"}
1
+ {"version":3,"file":"prepareFinal.js","sourceRoot":"","sources":["../../../../../src/core/agent/stages/prepareFinal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,sCAAsC,CAAC;AAGjE,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,KAA6B,EAAQ,EAAE;IACvE,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,CAAC;IAClC,KAAK,CAAC,YAAY,GAAG,KAAK,CAAC,gBAAgB,CAAC;IAC5C,gEAAgE;IAChE,mEAAmE;IACnE,oEAAoE;IACpE,iEAAiE;IACjE,+DAA+D;IAC/D,MAAM,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IAC5C,MAAM,WAAW,GAAG,cAAc,KAAK,SAAS,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,CAAC;IAC9E,6DAA6D;IAC7D,wCAAwC;IACxC,KAAK,CAAC,WAAW,GAAG;QAClB,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,WAAW,EAAE;QAC5C;YACE,IAAI,EAAE,WAAW;YACjB,OAAO,EAAE,KAAK,CAAC,YAAY;YAC3B,GAAG,CAAC,WAAW,IAAI,EAAE,cAAc,EAAE,CAAC;SACvC;KACF,CAAC;IAEF,SAAS,CAAC,KAAK,EAAE,oCAAoC,EAAE;QACrD,SAAS,EAAE,CAAC;QACZ,SAAS,EAAE,SAAS;QACpB,aAAa,EAAE,CAAC;KACjB,CAAC,CAAC;IACH,SAAS,CAAC,KAAK,EAAE,+BAA+B,EAAE;QAChD,SAAS,EAAE,CAAC;QACZ,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,SAAS;QACzB,UAAU,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,WAAW;KAC3C,CAAC,CAAC;AACL,CAAC,CAAC"}
@@ -14,5 +14,34 @@
14
14
  */
15
15
  import type { TypedScope } from 'footprintjs';
16
16
  import type { AgentState } from '../types.js';
17
+ import type { MessageMiddleware } from '../middleware/types.js';
17
18
  export type RouteBranch = 'tool-calls' | 'final';
18
19
  export declare const routeDeciderStage: (scope: TypedScope<AgentState>) => RouteBranch;
20
+ /**
21
+ * Build the Route decider, optionally carrying the `'output'` half of the
22
+ * message chain.
23
+ *
24
+ * ## Why the chain runs HERE and not in PrepareFinal
25
+ *
26
+ * PrepareFinal is where `finalContent` is set, which makes it look like the
27
+ * output seam. It is not, for one structural reason: it lives inside the Final
28
+ * BRANCH subflow, and a branch mount hands its `outputMapper` the branch's
29
+ * RESULT, not its scope — so nothing that stage writes reaches the run's
30
+ * shared state. Ledger rows filed there would sit in an isolated commit log,
31
+ * and one ledger would be split across two places a reader has to know about.
32
+ *
33
+ * The decider is one stage earlier, in the main chart, and it is the first
34
+ * moment the run KNOWS this turn is the final answer. Its writes commit before
35
+ * the branch resolves (footprintjs commits a decider stage ahead of matching
36
+ * the branch), and the value it rewrites — `llmLatestContent` — is exactly
37
+ * what PrepareFinal copies into `finalContent`. So the caller, the committed
38
+ * record, the `newMessages` the memory writes persist, and the ledger row all
39
+ * carry the same string. One seam, one answer.
40
+ *
41
+ * The `'tool-calls'` path is untouched: a turn that is still calling tools has
42
+ * not produced an answer, and running an output rule over a half-finished turn
43
+ * would be running it over something that is not the output.
44
+ *
45
+ * Empty chain → the exact synchronous decider this file has always exported.
46
+ */
47
+ export declare function buildRouteDeciderStage(messageMiddleware?: readonly MessageMiddleware[]): (scope: TypedScope<AgentState>) => RouteBranch | Promise<RouteBranch>;
@@ -13,6 +13,8 @@
13
13
  * passed directly to `addDeciderFunction(...)` in buildAgentChart.
14
14
  */
15
15
  import { typedEmit } from '../../../recorders/core/typedEmit.js';
16
+ import { runMessageChain } from '../middleware/runChain.js';
17
+ import { recordDecisions } from '../middleware/ledger.js';
16
18
  export const routeDeciderStage = (scope) => {
17
19
  const toolCalls = scope.llmLatestToolCalls;
18
20
  const iteration = scope.iteration;
@@ -29,4 +31,62 @@ export const routeDeciderStage = (scope) => {
29
31
  });
30
32
  return chosen;
31
33
  };
34
+ /**
35
+ * Build the Route decider, optionally carrying the `'output'` half of the
36
+ * message chain.
37
+ *
38
+ * ## Why the chain runs HERE and not in PrepareFinal
39
+ *
40
+ * PrepareFinal is where `finalContent` is set, which makes it look like the
41
+ * output seam. It is not, for one structural reason: it lives inside the Final
42
+ * BRANCH subflow, and a branch mount hands its `outputMapper` the branch's
43
+ * RESULT, not its scope — so nothing that stage writes reaches the run's
44
+ * shared state. Ledger rows filed there would sit in an isolated commit log,
45
+ * and one ledger would be split across two places a reader has to know about.
46
+ *
47
+ * The decider is one stage earlier, in the main chart, and it is the first
48
+ * moment the run KNOWS this turn is the final answer. Its writes commit before
49
+ * the branch resolves (footprintjs commits a decider stage ahead of matching
50
+ * the branch), and the value it rewrites — `llmLatestContent` — is exactly
51
+ * what PrepareFinal copies into `finalContent`. So the caller, the committed
52
+ * record, the `newMessages` the memory writes persist, and the ledger row all
53
+ * carry the same string. One seam, one answer.
54
+ *
55
+ * The `'tool-calls'` path is untouched: a turn that is still calling tools has
56
+ * not produced an answer, and running an output rule over a half-finished turn
57
+ * would be running it over something that is not the output.
58
+ *
59
+ * Empty chain → the exact synchronous decider this file has always exported.
60
+ */
61
+ export function buildRouteDeciderStage(messageMiddleware) {
62
+ const chain = messageMiddleware ?? [];
63
+ if (chain.length === 0)
64
+ return routeDeciderStage;
65
+ return async (scope) => {
66
+ const chosen = routeDeciderStage(scope);
67
+ if (chosen !== 'final')
68
+ return chosen;
69
+ const verdict = await runMessageChain(chain, {
70
+ phase: 'output',
71
+ content: scope.llmLatestContent,
72
+ history: [...scope.history],
73
+ iteration: scope.iteration,
74
+ ...(scope.runIdentity && { identity: scope.runIdentity }),
75
+ });
76
+ recordDecisions(scope, verdict.decisions);
77
+ if (verdict.kind === 'deny') {
78
+ // The answer is NOT released. It stays in the commit log where the run
79
+ // put it, under whatever redaction the run configured, and the boundary
80
+ // raises instead of returning — handing the caller a refusal in place of
81
+ // an answer is the one substitution they must never make unknowingly.
82
+ scope.messageDeniedReason = verdict.reason;
83
+ scope.messageDeniedPhase = 'output';
84
+ scope.messageDeniedBy = verdict.middleware;
85
+ }
86
+ // Committed either way: on a refusal this is what was withheld, and the
87
+ // ledger row beside it says who withheld it and why.
88
+ scope.llmLatestContent = verdict.content;
89
+ return chosen;
90
+ };
91
+ }
32
92
  //# sourceMappingURL=route.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"route.js","sourceRoot":"","sources":["../../../../../src/core/agent/stages/route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,sCAAsC,CAAC;AAKjE,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,KAA6B,EAAe,EAAE;IAC9E,MAAM,SAAS,GAAG,KAAK,CAAC,kBAAiD,CAAC;IAC1E,MAAM,SAAS,GAAG,KAAK,CAAC,SAAmB,CAAC;IAC5C,MAAM,MAAM,GACV,SAAS,CAAC,MAAM,GAAG,CAAC,IAAI,SAAS,GAAG,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC;IAEnF,SAAS,CAAC,KAAK,EAAE,oCAAoC,EAAE;QACrD,SAAS,EAAE,CAAC;QACZ,SAAS,EAAE,SAAS;QACpB,MAAM;QACN,SAAS,EACP,MAAM,KAAK,YAAY;YACrB,CAAC,CAAC,iBAAiB,SAAS,CAAC,MAAM,eAAe;YAClD,CAAC,CAAC,SAAS,IAAI,KAAK,CAAC,aAAa;gBAClC,CAAC,CAAC,uCAAuC;gBACzC,CAAC,CAAC,2CAA2C;KAClD,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC"}
1
+ {"version":3,"file":"route.js","sourceRoot":"","sources":["../../../../../src/core/agent/stages/route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,sCAAsC,CAAC;AAIjE,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAI1D,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,KAA6B,EAAe,EAAE;IAC9E,MAAM,SAAS,GAAG,KAAK,CAAC,kBAAiD,CAAC;IAC1E,MAAM,SAAS,GAAG,KAAK,CAAC,SAAmB,CAAC;IAC5C,MAAM,MAAM,GACV,SAAS,CAAC,MAAM,GAAG,CAAC,IAAI,SAAS,GAAG,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC;IAEnF,SAAS,CAAC,KAAK,EAAE,oCAAoC,EAAE;QACrD,SAAS,EAAE,CAAC;QACZ,SAAS,EAAE,SAAS;QACpB,MAAM;QACN,SAAS,EACP,MAAM,KAAK,YAAY;YACrB,CAAC,CAAC,iBAAiB,SAAS,CAAC,MAAM,eAAe;YAClD,CAAC,CAAC,SAAS,IAAI,KAAK,CAAC,aAAa;gBAClC,CAAC,CAAC,uCAAuC;gBACzC,CAAC,CAAC,2CAA2C;KAClD,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,sBAAsB,CACpC,iBAAgD;IAEhD,MAAM,KAAK,GAAG,iBAAiB,IAAI,EAAE,CAAC;IACtC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,iBAAiB,CAAC;IACjD,OAAO,KAAK,EAAE,KAAK,EAAE,EAAE;QACrB,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC;QACxC,IAAI,MAAM,KAAK,OAAO;YAAE,OAAO,MAAM,CAAC;QAEtC,MAAM,OAAO,GAAG,MAAM,eAAe,CAAC,KAAK,EAAE;YAC3C,KAAK,EAAE,QAAQ;YACf,OAAO,EAAE,KAAK,CAAC,gBAAgB;YAC/B,OAAO,EAAE,CAAC,GAAI,KAAK,CAAC,OAAiC,CAAC;YACtD,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,GAAG,CAAC,KAAK,CAAC,WAAW,IAAI,EAAE,QAAQ,EAAE,KAAK,CAAC,WAAW,EAAE,CAAC;SAC1D,CAAC,CAAC;QACH,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;QAC1C,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC5B,uEAAuE;YACvE,wEAAwE;YACxE,yEAAyE;YACzE,sEAAsE;YACtE,KAAK,CAAC,mBAAmB,GAAG,OAAO,CAAC,MAAM,CAAC;YAC3C,KAAK,CAAC,kBAAkB,GAAG,QAAQ,CAAC;YACpC,KAAK,CAAC,eAAe,GAAG,OAAO,CAAC,UAAU,CAAC;QAC7C,CAAC;QACD,wEAAwE;QACxE,qDAAqD;QACrD,KAAK,CAAC,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC;QACzC,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC"}
@@ -19,6 +19,7 @@
19
19
  import type { TypedScope } from 'footprintjs';
20
20
  import type { LLMMessage, LLMToolSchema } from '../../../adapters/types.js';
21
21
  import type { AgentInput, AgentState, RunConfig } from '../types.js';
22
+ import type { MessageMiddleware } from '../middleware/types.js';
22
23
  export interface SeedStageDeps {
23
24
  /** Resolved `clampIterations(opts.maxIterations ?? 10)`. Frozen at
24
25
  * chart-build time. */
@@ -53,10 +54,24 @@ export interface SeedStageDeps {
53
54
  * written, so the commit log is byte-identical to earlier releases.
54
55
  */
55
56
  readonly resolveRunConfig?: (input: AgentInput) => RunConfig | undefined;
57
+ /**
58
+ * The message chain (`.messageMiddleware(...)`), walked here at the
59
+ * `'input'` phase — BEFORE `userMessage` and `history` are written.
60
+ *
61
+ * This is the only placement that keeps the run honest. Everything
62
+ * downstream reads `scope.history`: the window strategies, the injection
63
+ * engine, all three slots, the request that goes on the wire, and every
64
+ * slice taken afterwards. Transform later than this and those components
65
+ * disagree about what the user actually said — the trace would show one
66
+ * message and the model would have answered another.
67
+ *
68
+ * Empty / undefined → seed stays the synchronous stage it always was.
69
+ */
70
+ readonly messageMiddleware?: readonly MessageMiddleware[];
56
71
  }
57
72
  /**
58
73
  * Build the seed stage function for an Agent instance. Captures both
59
74
  * the chart-build-time constants and the per-run mutable accessors
60
75
  * via the deps object.
61
76
  */
62
- export declare function buildSeedStage(deps: SeedStageDeps): (scope: TypedScope<AgentState>) => void;
77
+ export declare function buildSeedStage(deps: SeedStageDeps): (scope: TypedScope<AgentState>) => void | Promise<void>;
@@ -17,99 +17,144 @@
17
17
  * features need.
18
18
  */
19
19
  import { typedEmit } from '../../../recorders/core/typedEmit.js';
20
+ import { runMessageChain } from '../middleware/runChain.js';
21
+ import { recordDecisions } from '../middleware/ledger.js';
20
22
  /**
21
23
  * Build the seed stage function for an Agent instance. Captures both
22
24
  * the chart-build-time constants and the per-run mutable accessors
23
25
  * via the deps object.
24
26
  */
25
27
  export function buildSeedStage(deps) {
26
- return (scope) => {
27
- const args = scope.$getArgs();
28
- scope.userMessage = args.message;
29
- // If `resumeOnError(...)` set the side channel, restore the
30
- // checkpointed conversation history. The next iteration sees
31
- // the prior messages and continues from the failure point.
32
- // Always clear the field after reading so subsequent runs
33
- // (without resumeOnError) start fresh.
34
- const resumeHistory = deps.consumePendingResumeHistory();
35
- if (resumeHistory && resumeHistory.length > 0) {
36
- scope.history = [...resumeHistory];
37
- }
38
- else {
39
- scope.history = [{ role: 'user', content: args.message }];
40
- }
41
- // Default identity uses the runId so multi-run isolation works
42
- // without consumer changes; explicit identity (multi-tenant)
43
- // overrides via `agent.run({ identity })`.
44
- scope.runIdentity = args.identity ?? {
45
- conversationId: deps.getCurrentRunId() ?? 'default',
28
+ const chain = deps.messageMiddleware ?? [];
29
+ // No chain → the same synchronous function this stage has always been.
30
+ // Not an optimisation: an agent without middleware must produce the same
31
+ // stage shape, the same committed keys and the same request bytes as before.
32
+ if (chain.length === 0) {
33
+ return (scope) => {
34
+ seedFrom(scope, scope.$getArgs().message, deps);
46
35
  };
47
- scope.newMessages = [];
48
- scope.turnNumber = 1;
49
- // Permissive default — explicit cap will land when PricingTable
50
- // gets a context-window field. Memory pickByBudget treats anything
51
- // ≥ minimumTokens as "fits", so this just enables the budget path.
52
- scope.contextTokensRemaining = 32_000;
53
- scope.iteration = 1;
54
- scope.maxIterations = deps.maxIterations;
55
- scope.finalContent = '';
56
- scope.totalInputTokens = 0;
57
- scope.totalOutputTokens = 0;
58
- scope.turnStartMs = Date.now();
59
- scope.systemPromptInjections = [];
60
- scope.messagesInjections = [];
61
- scope.toolsInjections = [];
62
- scope.llmLatestContent = '';
63
- scope.llmLatestToolCalls = [];
64
- // v2.14 — initialize thinking blocks. Empty array means "no thinking
65
- // this iteration"; the NormalizeThinking sub-subflow overwrites
66
- // this AFTER each CallLLM when a ThinkingHandler is configured.
67
- scope.thinkingBlocks = [];
68
- scope.pausedToolCallId = '';
69
- scope.pausedToolName = '';
70
- scope.pausedToolStartMs = 0;
71
- scope.cumTokensInput = 0;
72
- scope.cumTokensOutput = 0;
73
- scope.cumEstimatedUsd = 0;
74
- scope.costBudgetHit = false;
75
- scope.activeInjections = [];
76
- scope.activatedInjectionIds = [];
77
- scope.dynamicToolSchemas = deps.toolSchemas;
78
- // Cache layer state (v2.6) — initialized to inert defaults.
79
- // CacheDecision subflow populates `cacheMarkers` per iteration;
80
- // UpdateSkillHistory + CacheGate consume `cachingDisabled`,
81
- // `recentHitRate`, `skillHistory`. Empty defaults mean the
82
- // CacheGate falls through to 'apply-markers' on iter 1 (no
83
- // history yet → no churn detected; recentHitRate undefined →
84
- // hit-rate floor doesn't fire).
85
- scope.cacheMarkers = [];
86
- scope.cachingDisabled = deps.cachingDisabled;
87
- scope.recentHitRate = undefined;
88
- scope.skillHistory = [];
89
- // Skill-graph cursor — reset per turn so each new user message re-enters the
90
- // graph through the entry router (cold start). The Injection Engine advances
91
- // it each iteration; undefined for agents without a skillGraph().
92
- scope.currentSkillId = undefined;
93
- // `.configure()` — resolved ONCE here (seed runs exactly once per run)
94
- // and written to scope, which means the run's commit log records the
95
- // model and instructions the run actually used. A run that changed its
96
- // own model without committing that fact would produce a trace that
97
- // reads as if the built-in default answered.
98
- //
99
- // Only what the resolver actually returned is written: an agent with no
100
- // `.configure()`, or one whose resolver returned `{}`, commits nothing
101
- // extra and behaves exactly as before.
102
- if (deps.resolveRunConfig) {
103
- const resolved = deps.resolveRunConfig(args);
104
- if (resolved?.model !== undefined)
105
- scope.resolvedModel = resolved.model;
106
- if (resolved?.instructions !== undefined)
107
- scope.resolvedInstructions = resolved.instructions;
108
- }
109
- typedEmit(scope, 'agentfootprint.agent.turn_start', {
110
- turnIndex: 0,
111
- userPrompt: args.message,
36
+ }
37
+ return async (scope) => {
38
+ const args = scope.$getArgs();
39
+ const verdict = await runMessageChain(chain, {
40
+ phase: 'input',
41
+ content: args.message,
42
+ history: [],
43
+ // The input boundary runs before iteration 1 exists.
44
+ iteration: 0,
45
+ ...(args.identity && { identity: args.identity }),
112
46
  });
47
+ recordDecisions(scope, verdict.decisions);
48
+ if (verdict.kind === 'deny') {
49
+ // Seed the run anyway, with the content as it stood when it was
50
+ // refused, then stop. Committing it costs nothing (a refusal is a fact
51
+ // about a run, and hiding what was refused would make the record
52
+ // useless), and a fully-seeded state means `resumeOnError` and every
53
+ // recorder see the shape they expect rather than a half-built one.
54
+ seedFrom(scope, verdict.content, deps);
55
+ scope.messageDeniedReason = verdict.reason;
56
+ scope.messageDeniedPhase = 'input';
57
+ scope.messageDeniedBy = verdict.middleware;
58
+ // Stops the chart here: no injections, no slots, no LLM call. The
59
+ // boundary turns these flags into a MessageDeniedError.
60
+ scope.$break(`message denied at input: ${verdict.reason}`);
61
+ return;
62
+ }
63
+ seedFrom(scope, verdict.content, deps);
64
+ };
65
+ }
66
+ /**
67
+ * Initialise every mutable field of `AgentState` from `message` + the run
68
+ * args. Split out so the message the run proceeds with can come either
69
+ * straight from the caller or from the `'input'` middleware chain — one
70
+ * initialiser, so the two paths cannot drift.
71
+ */
72
+ function seedFrom(scope, message, deps) {
73
+ const args = scope.$getArgs();
74
+ scope.userMessage = message;
75
+ // If `resumeOnError(...)` set the side channel, restore the
76
+ // checkpointed conversation history. The next iteration sees
77
+ // the prior messages and continues from the failure point.
78
+ // Always clear the field after reading so subsequent runs
79
+ // (without resumeOnError) start fresh.
80
+ const resumeHistory = deps.consumePendingResumeHistory();
81
+ if (resumeHistory && resumeHistory.length > 0) {
82
+ scope.history = [...resumeHistory];
83
+ }
84
+ else {
85
+ scope.history = [{ role: 'user', content: message }];
86
+ }
87
+ // Default identity uses the runId so multi-run isolation works
88
+ // without consumer changes; explicit identity (multi-tenant)
89
+ // overrides via `agent.run({ identity })`.
90
+ scope.runIdentity = args.identity ?? {
91
+ conversationId: deps.getCurrentRunId() ?? 'default',
113
92
  };
93
+ scope.newMessages = [];
94
+ scope.turnNumber = 1;
95
+ // Permissive default — explicit cap will land when PricingTable
96
+ // gets a context-window field. Memory pickByBudget treats anything
97
+ // ≥ minimumTokens as "fits", so this just enables the budget path.
98
+ scope.contextTokensRemaining = 32_000;
99
+ scope.iteration = 1;
100
+ scope.maxIterations = deps.maxIterations;
101
+ scope.finalContent = '';
102
+ scope.totalInputTokens = 0;
103
+ scope.totalOutputTokens = 0;
104
+ scope.turnStartMs = Date.now();
105
+ scope.systemPromptInjections = [];
106
+ scope.messagesInjections = [];
107
+ scope.toolsInjections = [];
108
+ scope.llmLatestContent = '';
109
+ scope.llmLatestToolCalls = [];
110
+ // v2.14 — initialize thinking blocks. Empty array means "no thinking
111
+ // this iteration"; the NormalizeThinking sub-subflow overwrites
112
+ // this AFTER each CallLLM when a ThinkingHandler is configured.
113
+ scope.thinkingBlocks = [];
114
+ scope.pausedToolCallId = '';
115
+ scope.pausedToolName = '';
116
+ scope.pausedToolStartMs = 0;
117
+ scope.cumTokensInput = 0;
118
+ scope.cumTokensOutput = 0;
119
+ scope.cumEstimatedUsd = 0;
120
+ scope.costBudgetHit = false;
121
+ scope.activeInjections = [];
122
+ scope.activatedInjectionIds = [];
123
+ scope.dynamicToolSchemas = deps.toolSchemas;
124
+ // Cache layer state (v2.6) — initialized to inert defaults.
125
+ // CacheDecision subflow populates `cacheMarkers` per iteration;
126
+ // UpdateSkillHistory + CacheGate consume `cachingDisabled`,
127
+ // `recentHitRate`, `skillHistory`. Empty defaults mean the
128
+ // CacheGate falls through to 'apply-markers' on iter 1 (no
129
+ // history yet → no churn detected; recentHitRate undefined →
130
+ // hit-rate floor doesn't fire).
131
+ scope.cacheMarkers = [];
132
+ scope.cachingDisabled = deps.cachingDisabled;
133
+ scope.recentHitRate = undefined;
134
+ scope.skillHistory = [];
135
+ // Skill-graph cursor — reset per turn so each new user message re-enters the
136
+ // graph through the entry router (cold start). The Injection Engine advances
137
+ // it each iteration; undefined for agents without a skillGraph().
138
+ scope.currentSkillId = undefined;
139
+ // `.configure()` — resolved ONCE here (seed runs exactly once per run)
140
+ // and written to scope, which means the run's commit log records the
141
+ // model and instructions the run actually used. A run that changed its
142
+ // own model without committing that fact would produce a trace that
143
+ // reads as if the built-in default answered.
144
+ //
145
+ // Only what the resolver actually returned is written: an agent with no
146
+ // `.configure()`, or one whose resolver returned `{}`, commits nothing
147
+ // extra and behaves exactly as before.
148
+ if (deps.resolveRunConfig) {
149
+ const resolved = deps.resolveRunConfig(args);
150
+ if (resolved?.model !== undefined)
151
+ scope.resolvedModel = resolved.model;
152
+ if (resolved?.instructions !== undefined)
153
+ scope.resolvedInstructions = resolved.instructions;
154
+ }
155
+ typedEmit(scope, 'agentfootprint.agent.turn_start', {
156
+ turnIndex: 0,
157
+ userPrompt: message,
158
+ });
114
159
  }
115
160
  //# sourceMappingURL=seed.js.map