@asyra/ai-agent-runtime 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (262) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +9 -5
  3. package/dist/action-batch.d.ts.map +1 -1
  4. package/dist/action-batch.js.map +1 -1
  5. package/dist/action-registry.d.ts +2 -2
  6. package/dist/action-registry.d.ts.map +1 -1
  7. package/dist/action-registry.js +100 -65
  8. package/dist/action-registry.js.map +1 -1
  9. package/dist/audit.d.ts.map +1 -1
  10. package/dist/audit.js.map +1 -1
  11. package/dist/batch-exchange-types.d.ts +21 -0
  12. package/dist/batch-exchange-types.d.ts.map +1 -0
  13. package/dist/batch-exchange-types.js +2 -0
  14. package/dist/batch-exchange-types.js.map +1 -0
  15. package/dist/capability-search.d.ts +46 -0
  16. package/dist/capability-search.d.ts.map +1 -0
  17. package/dist/capability-search.js +210 -0
  18. package/dist/capability-search.js.map +1 -0
  19. package/dist/index.d.ts +37 -4
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +28 -2
  22. package/dist/index.js.map +1 -1
  23. package/dist/invocation.d.ts +46 -0
  24. package/dist/invocation.d.ts.map +1 -0
  25. package/dist/invocation.js +71 -0
  26. package/dist/invocation.js.map +1 -0
  27. package/dist/json-value.d.ts +3 -0
  28. package/dist/json-value.d.ts.map +1 -0
  29. package/dist/json-value.js +50 -0
  30. package/dist/json-value.js.map +1 -0
  31. package/dist/knowledge-types.d.ts +81 -0
  32. package/dist/knowledge-types.d.ts.map +1 -0
  33. package/dist/knowledge-types.js +2 -0
  34. package/dist/knowledge-types.js.map +1 -0
  35. package/dist/knowledge.d.ts +17 -0
  36. package/dist/knowledge.d.ts.map +1 -0
  37. package/dist/knowledge.js +585 -0
  38. package/dist/knowledge.js.map +1 -0
  39. package/dist/named-result-inputs.d.ts +9 -0
  40. package/dist/named-result-inputs.d.ts.map +1 -0
  41. package/dist/named-result-inputs.js +94 -0
  42. package/dist/named-result-inputs.js.map +1 -0
  43. package/dist/node/action-observation.d.ts +15 -0
  44. package/dist/node/action-observation.d.ts.map +1 -0
  45. package/dist/node/action-observation.js +126 -0
  46. package/dist/node/action-observation.js.map +1 -0
  47. package/dist/node/batch-exchange.d.ts +19 -0
  48. package/dist/node/batch-exchange.d.ts.map +1 -0
  49. package/dist/node/batch-exchange.js +105 -0
  50. package/dist/node/batch-exchange.js.map +1 -0
  51. package/dist/node/file-record-collector.d.ts +11 -0
  52. package/dist/node/file-record-collector.d.ts.map +1 -0
  53. package/dist/node/file-record-collector.js +142 -0
  54. package/dist/node/file-record-collector.js.map +1 -0
  55. package/dist/node/index.d.ts +22 -0
  56. package/dist/node/index.d.ts.map +1 -0
  57. package/dist/node/index.js +22 -0
  58. package/dist/node/index.js.map +1 -0
  59. package/dist/node/information-delivery.d.ts +90 -0
  60. package/dist/node/information-delivery.d.ts.map +1 -0
  61. package/dist/node/information-delivery.js +144 -0
  62. package/dist/node/information-delivery.js.map +1 -0
  63. package/dist/node/knowledge-file.d.ts +22 -0
  64. package/dist/node/knowledge-file.d.ts.map +1 -0
  65. package/dist/node/knowledge-file.js +106 -0
  66. package/dist/node/knowledge-file.js.map +1 -0
  67. package/dist/node/native-provider-config.d.ts +12 -0
  68. package/dist/node/native-provider-config.d.ts.map +1 -0
  69. package/dist/node/native-provider-config.js +58 -0
  70. package/dist/node/native-provider-config.js.map +1 -0
  71. package/dist/node/native-provider.d.ts +36 -0
  72. package/dist/node/native-provider.d.ts.map +1 -0
  73. package/dist/node/native-provider.js +209 -0
  74. package/dist/node/native-provider.js.map +1 -0
  75. package/dist/node/native-rpc-transport.d.ts +39 -0
  76. package/dist/node/native-rpc-transport.d.ts.map +1 -0
  77. package/dist/node/native-rpc-transport.js +171 -0
  78. package/dist/node/native-rpc-transport.js.map +1 -0
  79. package/dist/node/native-session.d.ts +50 -0
  80. package/dist/node/native-session.d.ts.map +1 -0
  81. package/dist/node/native-session.js +200 -0
  82. package/dist/node/native-session.js.map +1 -0
  83. package/dist/node/payload.d.ts +12 -0
  84. package/dist/node/payload.d.ts.map +1 -0
  85. package/dist/node/payload.js +69 -0
  86. package/dist/node/payload.js.map +1 -0
  87. package/dist/node/provider-content.d.ts +9 -0
  88. package/dist/node/provider-content.d.ts.map +1 -0
  89. package/dist/node/provider-content.js +2 -0
  90. package/dist/node/provider-content.js.map +1 -0
  91. package/dist/node/provider-conversations.d.ts +21 -0
  92. package/dist/node/provider-conversations.d.ts.map +1 -0
  93. package/dist/node/provider-conversations.js +98 -0
  94. package/dist/node/provider-conversations.js.map +1 -0
  95. package/dist/node/record-collector.d.ts +27 -0
  96. package/dist/node/record-collector.d.ts.map +1 -0
  97. package/dist/node/record-collector.js +175 -0
  98. package/dist/node/record-collector.js.map +1 -0
  99. package/dist/node/record-sink.d.ts +4 -0
  100. package/dist/node/record-sink.d.ts.map +1 -0
  101. package/dist/node/record-sink.js +218 -0
  102. package/dist/node/record-sink.js.map +1 -0
  103. package/dist/node/report-cli.d.ts +21 -0
  104. package/dist/node/report-cli.d.ts.map +1 -0
  105. package/dist/node/report-cli.js +285 -0
  106. package/dist/node/report-cli.js.map +1 -0
  107. package/dist/node/responses-provider.d.ts +53 -0
  108. package/dist/node/responses-provider.d.ts.map +1 -0
  109. package/dist/node/responses-provider.js +542 -0
  110. package/dist/node/responses-provider.js.map +1 -0
  111. package/dist/node/responses-tool-search.d.ts +74 -0
  112. package/dist/node/responses-tool-search.d.ts.map +1 -0
  113. package/dist/node/responses-tool-search.js +100 -0
  114. package/dist/node/responses-tool-search.js.map +1 -0
  115. package/dist/node/source-identity.d.ts +10 -0
  116. package/dist/node/source-identity.d.ts.map +1 -0
  117. package/dist/node/source-identity.js +85 -0
  118. package/dist/node/source-identity.js.map +1 -0
  119. package/dist/node/sqlite-tool-store.d.ts +18 -0
  120. package/dist/node/sqlite-tool-store.d.ts.map +1 -0
  121. package/dist/node/sqlite-tool-store.js +198 -0
  122. package/dist/node/sqlite-tool-store.js.map +1 -0
  123. package/dist/node/tool-host-library.d.ts +97 -0
  124. package/dist/node/tool-host-library.d.ts.map +1 -0
  125. package/dist/node/tool-host-library.js +368 -0
  126. package/dist/node/tool-host-library.js.map +1 -0
  127. package/dist/node/tool-provider.d.ts +65 -0
  128. package/dist/node/tool-provider.d.ts.map +1 -0
  129. package/dist/node/tool-provider.js +2 -0
  130. package/dist/node/tool-provider.js.map +1 -0
  131. package/dist/profiler/assessment.d.ts +30 -0
  132. package/dist/profiler/assessment.d.ts.map +1 -0
  133. package/dist/profiler/assessment.js +111 -0
  134. package/dist/profiler/assessment.js.map +1 -0
  135. package/dist/profiler/evaluation.d.ts +288 -0
  136. package/dist/profiler/evaluation.d.ts.map +1 -0
  137. package/dist/profiler/evaluation.js +513 -0
  138. package/dist/profiler/evaluation.js.map +1 -0
  139. package/dist/profiler/record-delivery.d.ts +20 -0
  140. package/dist/profiler/record-delivery.d.ts.map +1 -0
  141. package/dist/profiler/record-delivery.js +279 -0
  142. package/dist/profiler/record-delivery.js.map +1 -0
  143. package/dist/profiler/record-outbox.d.ts +48 -0
  144. package/dist/profiler/record-outbox.d.ts.map +1 -0
  145. package/dist/profiler/record-outbox.js +126 -0
  146. package/dist/profiler/record-outbox.js.map +1 -0
  147. package/dist/profiler/recorder.d.ts +35 -0
  148. package/dist/profiler/recorder.d.ts.map +1 -0
  149. package/dist/profiler/recorder.js +864 -0
  150. package/dist/profiler/recorder.js.map +1 -0
  151. package/dist/profiler/records.d.ts +89 -0
  152. package/dist/profiler/records.d.ts.map +1 -0
  153. package/dist/profiler/records.js +216 -0
  154. package/dist/profiler/records.js.map +1 -0
  155. package/dist/profiler/timing.d.ts +21 -0
  156. package/dist/profiler/timing.d.ts.map +1 -0
  157. package/dist/profiler/timing.js +197 -0
  158. package/dist/profiler/timing.js.map +1 -0
  159. package/dist/profiler/trace.d.ts +31 -0
  160. package/dist/profiler/trace.d.ts.map +1 -0
  161. package/dist/profiler/trace.js +66 -0
  162. package/dist/profiler/trace.js.map +1 -0
  163. package/dist/provider-retry.d.ts.map +1 -1
  164. package/dist/provider-retry.js +1 -0
  165. package/dist/provider-retry.js.map +1 -1
  166. package/dist/provider.d.ts +46 -1
  167. package/dist/provider.d.ts.map +1 -1
  168. package/dist/provider.js +34 -0
  169. package/dist/provider.js.map +1 -1
  170. package/dist/providers/exchange-provider.d.ts +32 -0
  171. package/dist/providers/exchange-provider.d.ts.map +1 -0
  172. package/dist/providers/exchange-provider.js +348 -0
  173. package/dist/providers/exchange-provider.js.map +1 -0
  174. package/dist/providers/generic-http.d.ts +2 -1
  175. package/dist/providers/generic-http.d.ts.map +1 -1
  176. package/dist/providers/generic-http.js +12 -5
  177. package/dist/providers/generic-http.js.map +1 -1
  178. package/dist/recipe-admission.d.ts +5 -0
  179. package/dist/recipe-admission.d.ts.map +1 -0
  180. package/dist/recipe-admission.js +533 -0
  181. package/dist/recipe-admission.js.map +1 -0
  182. package/dist/recipe-execution.d.ts +93 -0
  183. package/dist/recipe-execution.d.ts.map +1 -0
  184. package/dist/recipe-execution.js +562 -0
  185. package/dist/recipe-execution.js.map +1 -0
  186. package/dist/recipe-format.d.ts +18 -0
  187. package/dist/recipe-format.d.ts.map +1 -0
  188. package/dist/recipe-format.js +94 -0
  189. package/dist/recipe-format.js.map +1 -0
  190. package/dist/recipe-schema.d.ts +67 -0
  191. package/dist/recipe-schema.d.ts.map +1 -0
  192. package/dist/recipe-schema.js +959 -0
  193. package/dist/recipe-schema.js.map +1 -0
  194. package/dist/recipe-types.d.ts +86 -0
  195. package/dist/recipe-types.d.ts.map +1 -0
  196. package/dist/recipe-types.js +2 -0
  197. package/dist/recipe-types.js.map +1 -0
  198. package/dist/redaction.d.ts.map +1 -1
  199. package/dist/redaction.js.map +1 -1
  200. package/dist/result-context.d.ts +70 -0
  201. package/dist/result-context.d.ts.map +1 -0
  202. package/dist/result-context.js +186 -0
  203. package/dist/result-context.js.map +1 -0
  204. package/dist/result-delivery.d.ts +64 -0
  205. package/dist/result-delivery.d.ts.map +1 -0
  206. package/dist/result-delivery.js +212 -0
  207. package/dist/result-delivery.js.map +1 -0
  208. package/dist/result-media.d.ts +8 -0
  209. package/dist/result-media.d.ts.map +1 -0
  210. package/dist/result-media.js +14 -0
  211. package/dist/result-media.js.map +1 -0
  212. package/dist/runtime.d.ts +70 -10
  213. package/dist/runtime.d.ts.map +1 -1
  214. package/dist/runtime.js +811 -162
  215. package/dist/runtime.js.map +1 -1
  216. package/dist/schema/index.d.ts +6 -0
  217. package/dist/schema/index.d.ts.map +1 -0
  218. package/dist/schema/index.js +6 -0
  219. package/dist/schema/index.js.map +1 -0
  220. package/dist/schema/native-input.d.ts +2 -0
  221. package/dist/schema/native-input.d.ts.map +1 -0
  222. package/dist/schema/native-input.js +170 -0
  223. package/dist/schema/native-input.js.map +1 -0
  224. package/dist/schema/owner-invocation.d.ts +19 -0
  225. package/dist/schema/owner-invocation.d.ts.map +1 -0
  226. package/dist/schema/owner-invocation.js +40 -0
  227. package/dist/schema/owner-invocation.js.map +1 -0
  228. package/dist/schema/result-delivery.d.ts +57 -0
  229. package/dist/schema/result-delivery.d.ts.map +1 -0
  230. package/dist/schema/result-delivery.js +380 -0
  231. package/dist/schema/result-delivery.js.map +1 -0
  232. package/dist/schema/tool-leases.d.ts +63 -0
  233. package/dist/schema/tool-leases.d.ts.map +1 -0
  234. package/dist/schema/tool-leases.js +439 -0
  235. package/dist/schema/tool-leases.js.map +1 -0
  236. package/dist/schema/validation.d.ts +19 -0
  237. package/dist/schema/validation.d.ts.map +1 -0
  238. package/dist/schema/validation.js +502 -0
  239. package/dist/schema/validation.js.map +1 -0
  240. package/dist/tool-contract.d.ts +105 -0
  241. package/dist/tool-contract.d.ts.map +1 -0
  242. package/dist/tool-contract.js +318 -0
  243. package/dist/tool-contract.js.map +1 -0
  244. package/dist/tool-input-error.d.ts +8 -0
  245. package/dist/tool-input-error.d.ts.map +1 -0
  246. package/dist/tool-input-error.js +10 -0
  247. package/dist/tool-input-error.js.map +1 -0
  248. package/dist/tool-library.d.ts +43 -0
  249. package/dist/tool-library.d.ts.map +1 -0
  250. package/dist/tool-library.js +204 -0
  251. package/dist/tool-library.js.map +1 -0
  252. package/dist/tool-scheduler.d.ts +10 -0
  253. package/dist/tool-scheduler.d.ts.map +1 -0
  254. package/dist/tool-scheduler.js +46 -0
  255. package/dist/tool-scheduler.js.map +1 -0
  256. package/dist/tool-store.d.ts +109 -0
  257. package/dist/tool-store.d.ts.map +1 -0
  258. package/dist/tool-store.js +536 -0
  259. package/dist/tool-store.js.map +1 -0
  260. package/dist/types.d.ts +45 -8
  261. package/dist/types.d.ts.map +1 -1
  262. package/package.json +33 -3
package/dist/runtime.js CHANGED
@@ -1,8 +1,22 @@
1
+ import { detachAiJsonValue } from './json-value.js';
2
+ import { AiToolContractError } from './tool-contract.js';
3
+ import { isExecutionActivity } from './provider.js';
4
+ import { createAiExecutionProfiler } from './profiler/recorder.js';
1
5
  import { AiActionRegistryError, createAiActionRegistry } from './action-registry.js';
2
6
  import { AiAuditError, createAiRuntimeAudit } from './audit.js';
3
- import { AiActionBatchResolutionError, resolveAiActionBatchWithRegistry } from './action-batch.js';
7
+ import { AiActionBatchResolutionError, AiActionBatchContractError, resolveAiActionBatchWithRegistry } from './action-batch.js';
4
8
  import { AiRetryPolicyError, MAX_AI_PROVIDER_ATTEMPTS, shouldRetryAiProviderFailure, toAiProviderRequestFailure } from './provider-retry.js';
5
9
  import { AI_REDACTED_VALUE, redactAiValue } from './redaction.js';
10
+ /** Explicit host evidence for a mutation member or final history settlement.
11
+ * It never performs rollback or infers retained writes. */
12
+ export class AiTransactionSettlementError extends Error {
13
+ constructor(cause, status) {
14
+ super('AI request transaction settlement reported by its host.');
15
+ this.cause = cause;
16
+ this.status = status;
17
+ this.name = 'AiTransactionSettlementError';
18
+ }
19
+ }
6
20
  export const AI_ACTION_BATCH_TRANSACTION_LABEL = 'AI-assisted action';
7
21
  export class AiTransactionError extends Error {
8
22
  constructor() {
@@ -13,11 +27,48 @@ export class AiTransactionError extends Error {
13
27
  }
14
28
  }
15
29
  export class AiExecutionError extends Error {
16
- constructor() {
30
+ constructor(receipt) {
17
31
  super('AI action execution was aborted.');
32
+ this.receipt = receipt;
18
33
  this.code = 'AI_EXECUTION_ABORTED';
19
34
  this.stage = 'execution';
20
35
  this.name = 'AiExecutionError';
36
+ if (receipt) {
37
+ this.receipt = Object.freeze({
38
+ ...receipt,
39
+ result: detachAiJsonValue(receipt.result)
40
+ });
41
+ }
42
+ }
43
+ }
44
+ /** An executor-recognized authored input rejection. Settlement is reported
45
+ * independently by the transaction host; this error never authorizes a retry. */
46
+ export class AiActionInputError extends Error {
47
+ constructor(publicMessage, issue) {
48
+ super(publicMessage);
49
+ this.code = 'AI_ACTION_INPUT_INVALID';
50
+ this.stage = 'execution';
51
+ this.name = 'AiActionInputError';
52
+ this.issue = detachAiJsonValue(issue);
53
+ }
54
+ }
55
+ /** Registered executors may explicitly expose a bounded, safe explanation.
56
+ * Never construct this from raw provider, transport, or canonical exceptions. */
57
+ export class AiActionExecutionError extends Error {
58
+ constructor(publicMessage, receipt) {
59
+ super(publicMessage.trim() && Array.from(publicMessage).length <= 1000
60
+ ? publicMessage
61
+ : 'AI action execution failed.');
62
+ this.receipt = receipt;
63
+ this.code = 'AI_EXECUTION_FAILED';
64
+ this.stage = 'execution';
65
+ this.name = 'AiActionExecutionError';
66
+ if (receipt) {
67
+ this.receipt = Object.freeze({
68
+ ...receipt,
69
+ result: detachAiJsonValue(receipt.result)
70
+ });
71
+ }
21
72
  }
22
73
  }
23
74
  export class AiPermissionError extends Error {
@@ -172,27 +223,47 @@ const assertTransactionNotAborted = (signal) => {
172
223
  };
173
224
  export const runAiActionBatchTransaction = async (runner, signal, execute) => {
174
225
  assertTransactionNotAborted(signal);
175
- return runner.run(AI_ACTION_BATCH_TRANSACTION_LABEL, async () => {
226
+ return runner.run(AI_ACTION_BATCH_TRANSACTION_LABEL, async (runMutation) => {
176
227
  assertTransactionNotAborted(signal);
177
- const result = await execute();
228
+ const result = await execute(runMutation);
178
229
  assertTransactionNotAborted(signal);
179
230
  return result;
180
- });
231
+ }, { signal });
181
232
  };
182
233
  const assertExecutionNotAborted = (signal) => {
183
234
  if (signal.aborted) {
184
235
  throw new AiExecutionError();
185
236
  }
186
237
  };
187
- export const executeAiActions = async (batch, signal, redactionOptions = {}) => {
238
+ export const runAiMutation = async (context, mutate, settled) => {
239
+ assertExecutionNotAborted(context.signal);
240
+ const guardedMutation = () => {
241
+ assertExecutionNotAborted(context.signal);
242
+ return mutate();
243
+ };
244
+ if (context.runMutation) {
245
+ return context.runMutation(guardedMutation, settled);
246
+ }
247
+ const value = guardedMutation();
248
+ settled?.(value);
249
+ return value;
250
+ };
251
+ export const executeAiActions = async (batch, signal, redactionOptions = {}, runMutation, observation) => {
188
252
  const actionResults = [];
189
253
  const context = Object.freeze({
190
- signal
254
+ ...observation,
255
+ signal,
256
+ ...(runMutation ? { runMutation } : {})
191
257
  });
192
258
  for (const action of batch.actions) {
193
259
  assertExecutionNotAborted(signal);
194
260
  const result = await action.execute(action.arguments, context);
195
- assertExecutionNotAborted(signal);
261
+ if (signal.aborted) {
262
+ throw new AiExecutionError({
263
+ result: redactAiValue(result, redactionOptions),
264
+ settlement: 'completed'
265
+ });
266
+ }
196
267
  actionResults.push(Object.freeze({
197
268
  actionId: action.id,
198
269
  actionName: action.name,
@@ -220,7 +291,7 @@ const emitAiRuntimeProgress = (observer, signal, update, redactionOptions) => {
220
291
  ? redactedBatchId
221
292
  : AI_REDACTED_VALUE;
222
293
  }
223
- observer(Object.freeze({
294
+ return observer(Object.freeze({
224
295
  ...update,
225
296
  ...(batchId === undefined ? {} : { batchId })
226
297
  }));
@@ -250,6 +321,9 @@ const runAbortable = async (signal, operation) => {
250
321
  }
251
322
  };
252
323
  const stableFailure = (error, fallback) => {
324
+ if (error instanceof AiActionBatchContractError) {
325
+ return toAiProviderRequestFailure(error, 1);
326
+ }
253
327
  if (error instanceof AiActionBatchResolutionError) {
254
328
  return {
255
329
  code: error.code,
@@ -271,6 +345,13 @@ const stableFailure = (error, fallback) => {
271
345
  stage: error.stage
272
346
  };
273
347
  }
348
+ if (error instanceof AiToolContractError) {
349
+ return {
350
+ code: 'AI_EXECUTION_FAILED',
351
+ message: error.message.slice(0, 1000),
352
+ stage: 'execution'
353
+ };
354
+ }
274
355
  if (error instanceof AiTransactionError) {
275
356
  return {
276
357
  code: error.code,
@@ -278,7 +359,9 @@ const stableFailure = (error, fallback) => {
278
359
  stage: error.stage
279
360
  };
280
361
  }
281
- if (error instanceof AiExecutionError) {
362
+ if (error instanceof AiActionInputError ||
363
+ error instanceof AiExecutionError ||
364
+ error instanceof AiActionExecutionError) {
282
365
  return {
283
366
  code: error.code,
284
367
  message: error.message,
@@ -380,6 +463,13 @@ const createFailedResult = (failure, evidence, redactionOptions) => Object.freez
380
463
  : {
381
464
  batchId: evidence.batch.batchId
382
465
  }),
466
+ ...(evidence.executionStarted
467
+ ? {
468
+ transaction: Object.freeze({
469
+ status: evidence.transactionStatus ?? 'unknown'
470
+ })
471
+ }
472
+ : {}),
383
473
  code: failure.code,
384
474
  message: failure.message,
385
475
  ...(evidence.preview === undefined
@@ -413,7 +503,16 @@ const createCancelledResult = (reason, evidence, redactionOptions) => {
413
503
  if (evidence.preview) {
414
504
  result.preview = evidence.preview;
415
505
  }
416
- return Object.freeze(result);
506
+ return Object.freeze({
507
+ ...result,
508
+ ...(evidence.executionStarted
509
+ ? {
510
+ transaction: Object.freeze({
511
+ status: evidence.transactionStatus ?? 'unknown'
512
+ })
513
+ }
514
+ : {})
515
+ });
417
516
  };
418
517
  const validateRuntimeOptions = (options) => {
419
518
  const retryPolicy = options?.retryPolicy;
@@ -448,6 +547,8 @@ class DefaultAiAgentRuntime {
448
547
  this.activeInvocations = new Set();
449
548
  this.disposed = false;
450
549
  const options = validateRuntimeOptions(input.options);
550
+ this.preserveProgress = input.options?.failurePolicy === 'preserve-progress';
551
+ this.createRecordingSink = input.createRecordingSink;
451
552
  this.provider = input.provider;
452
553
  this.contextProvider = input.contextProvider;
453
554
  this.permissionPolicy = input.permissionPolicy;
@@ -464,6 +565,49 @@ class DefaultAiAgentRuntime {
464
565
  resolveAiActionBatch(batch, options) {
465
566
  return resolveAiActionBatchWithRegistry(batch, this.registry, options);
466
567
  }
568
+ observe(input) {
569
+ if (this.disposed ||
570
+ !/^[a-zA-Z0-9_-]{1,160}$/.test(input.sourceRequestId)) {
571
+ return;
572
+ }
573
+ let sink;
574
+ try {
575
+ sink = this.createRecordingSink?.();
576
+ if (!sink) {
577
+ return;
578
+ }
579
+ const observation = createAiExecutionProfiler({
580
+ intent: '',
581
+ context: {},
582
+ actions: [],
583
+ attempt: 1,
584
+ ...(input.metadata === undefined
585
+ ? {}
586
+ : {
587
+ metadata: redactAiValue(input.metadata, this.redactionOptions)
588
+ })
589
+ }, 'none', {
590
+ sink,
591
+ sourceRequestId: input.sourceRequestId,
592
+ provider: 'host',
593
+ purpose: input.purpose.slice(0, 160),
594
+ log: () => undefined
595
+ });
596
+ observation.trace('host_observation', redactAiValue(input.evidence ?? {}, this.redactionOptions));
597
+ observation.finish('completed');
598
+ }
599
+ catch {
600
+ /* Host observation cannot affect publication. */
601
+ }
602
+ finally {
603
+ try {
604
+ void sink?.flush().catch(() => undefined);
605
+ }
606
+ catch {
607
+ /* Nonblocking. */
608
+ }
609
+ }
610
+ }
467
611
  run(request) {
468
612
  if (this.disposed) {
469
613
  return Promise.resolve(createFailedResult({
@@ -491,15 +635,67 @@ class DefaultAiAgentRuntime {
491
635
  }, this.redactionOptions))
492
636
  };
493
637
  this.activeInvocations.add(active);
638
+ let recording;
639
+ let sink;
640
+ try {
641
+ sink = this.createRecordingSink?.();
642
+ if (sink) {
643
+ recording = createAiExecutionProfiler({
644
+ intent: request.intent,
645
+ context: {},
646
+ actions: [],
647
+ attempt: 1,
648
+ ...(request.metadata === undefined
649
+ ? {}
650
+ : { metadata: request.metadata })
651
+ }, 'runtime', {
652
+ sink,
653
+ lifecycle: true,
654
+ provider: 'runtime',
655
+ purpose: 'user-request',
656
+ log: () => undefined
657
+ });
658
+ }
659
+ }
660
+ catch {
661
+ /* Recording admission cannot prevent product execution. */
662
+ }
663
+ let metadata = request.metadata === undefined
664
+ ? undefined
665
+ : redactAiValue(request.metadata, this.redactionOptions);
666
+ if (recording &&
667
+ (metadata === undefined ||
668
+ (metadata !== null &&
669
+ typeof metadata === 'object' &&
670
+ !Array.isArray(metadata)))) {
671
+ metadata = {
672
+ ...metadata,
673
+ sourceRequestId: recording.requestId
674
+ };
675
+ }
494
676
  active.settlement = this.runInvocation({
495
677
  intent: request.intent,
496
- ...(request.metadata === undefined
497
- ? {}
498
- : {
499
- metadata: redactAiValue(request.metadata, this.redactionOptions)
500
- }),
678
+ ...(metadata === undefined ? {} : { metadata }),
501
679
  signal: controller.signal
502
- }, controller.signal, request.progressObserver).finally(() => {
680
+ }, controller.signal, request.progressObserver, recording)
681
+ .then((result) => {
682
+ recording?.trace('settlement', { outcome: result.status });
683
+ recording?.finish(result.status === 'executed' ? 'completed' : result.status);
684
+ return recording
685
+ ? Object.freeze({ ...result, recordingId: recording.requestId })
686
+ : result;
687
+ }, (error) => {
688
+ recording?.finish(controller.signal.aborted ? 'cancelled' : 'failed');
689
+ throw error;
690
+ })
691
+ .finally(() => {
692
+ // Product settlement never waits for diagnostic I/O.
693
+ try {
694
+ void sink?.flush().catch(() => undefined);
695
+ }
696
+ catch {
697
+ /* Non-authoritative observer. */
698
+ }
503
699
  request.signal.removeEventListener('abort', abortInvocation);
504
700
  this.activeInvocations.delete(active);
505
701
  });
@@ -525,12 +721,39 @@ class DefaultAiAgentRuntime {
525
721
  throw failed.reason;
526
722
  }
527
723
  }
528
- async runInvocation(request, signal, progressObserver) {
724
+ async runInvocation(request, signal, progressObserver, recording) {
529
725
  let evidence = {
530
726
  retryCount: 0
531
727
  };
728
+ let runMutation;
729
+ let failedAction;
730
+ let failedActionId = null;
731
+ let actionStartedAt;
532
732
  let currentStage = 'context';
533
- const emitProgress = (update) => emitAiRuntimeProgress(progressObserver, signal, update, this.redactionOptions);
733
+ let progressSequence = 0;
734
+ const emitProgress = (update) => {
735
+ const event = {
736
+ ...update,
737
+ ...(update.activity
738
+ ? { activity: { ...update.activity, sequence: ++progressSequence } }
739
+ : {})
740
+ };
741
+ const decision = emitAiRuntimeProgress(progressObserver, signal, event, this.redactionOptions);
742
+ recording?.trace('progress_projection', {
743
+ phase: event.phase,
744
+ activity: event.activity,
745
+ tool: event.tool,
746
+ decision
747
+ });
748
+ };
749
+ let providerFailure;
750
+ let attempt = 1;
751
+ const allResults = [];
752
+ const batchIds = new Set();
753
+ let acceptingBatches = false;
754
+ let batchPending = false;
755
+ let callbackFailure;
756
+ let batchSettlement;
534
757
  try {
535
758
  const intent = typeof request.intent === 'string' ? request.intent.trim() : '';
536
759
  if (!intent) {
@@ -540,183 +763,603 @@ class DefaultAiAgentRuntime {
540
763
  stage: 'runtime'
541
764
  }, evidence, this.redactionOptions);
542
765
  }
766
+ if (signal.aborted) {
767
+ throw INVOCATION_ABORTED;
768
+ }
543
769
  emitProgress({
544
- attempt: 1,
770
+ attempt,
545
771
  phase: 'context',
546
772
  summary: 'Understanding the request'
547
773
  });
548
- const context = redactAiValue(await runAbortable(signal, () => this.contextProvider.getContext({
549
- intent,
550
- signal
551
- })), this.redactionOptions);
774
+ let contextRead = 0;
775
+ const readContext = async () => {
776
+ const end = recording?.span({
777
+ callId: `context-${++contextRead}`,
778
+ owner: 'app',
779
+ purpose: 'Read current request context'
780
+ });
781
+ try {
782
+ return redactAiValue(await runAbortable(signal, () => this.contextProvider.getContext({ intent, signal })), this.redactionOptions);
783
+ }
784
+ finally {
785
+ end?.();
786
+ }
787
+ };
788
+ let context = await readContext();
789
+ let contextStale = false;
790
+ const refreshContext = async () => {
791
+ currentStage = 'context';
792
+ context = await readContext();
793
+ contextStale = false;
794
+ return context;
795
+ };
552
796
  currentStage = 'registry';
553
797
  const actions = this.registry.list();
554
- currentStage = 'provider';
555
- let attempt = 1;
556
- let resolved;
557
- while (true) {
798
+ let preparationSequence = 0;
799
+ const observePreparation = async (purpose, work) => {
800
+ const end = recording?.span({
801
+ callId: `preparation-${++preparationSequence}`,
802
+ owner: 'app',
803
+ purpose
804
+ });
805
+ try {
806
+ return await work();
807
+ }
808
+ finally {
809
+ end?.();
810
+ }
811
+ };
812
+ const executePrepared = async (actionBatch) => {
813
+ failedAction = undefined;
814
+ failedActionId = null;
815
+ actionStartedAt = undefined;
816
+ if (contextStale) {
817
+ await refreshContext();
818
+ }
819
+ currentStage = 'resolution';
558
820
  emitProgress({
559
821
  attempt,
560
- phase: 'provider',
561
- summary: 'Requesting an action batch'
822
+ phase: 'resolution',
823
+ summary: 'Resolving app actions'
562
824
  });
563
- try {
564
- const actionBatch = await runAbortable(signal, () => this.provider.requestActionBatch(Object.freeze({
565
- actions,
825
+ const resolved = await observePreparation('Resolve action batch', () => this.resolveAiActionBatch(actionBatch, { signal }));
826
+ if (batchIds.has(resolved.batchId)) {
827
+ throw new AiActionBatchResolutionError('AI_ACTION_BATCH_DUPLICATE_ACTION_ID', 'A prepared batch cannot execute twice in one invocation.');
828
+ }
829
+ batchIds.add(resolved.batchId);
830
+ evidence = {
831
+ ...evidence,
832
+ batch: resolved,
833
+ retryCount: attempt - 1
834
+ };
835
+ currentStage = 'permission';
836
+ emitProgress({
837
+ actionCount: resolved.actions.length,
838
+ attempt,
839
+ batchId: resolved.batchId,
840
+ phase: 'permission',
841
+ summary: 'Checking action permissions'
842
+ });
843
+ const permissionReady = await observePreparation('Evaluate action permissions', () => evaluateAiActionBatchPermissions(resolved, context, this.permissionPolicy));
844
+ currentStage = 'confirmation';
845
+ if (permissionReady.confirmationRequired) {
846
+ emitProgress({
847
+ actionCount: permissionReady.actions.length,
566
848
  attempt,
567
- context,
568
- intent,
569
- ...(request.metadata === undefined
570
- ? {}
571
- : {
572
- metadata: request.metadata
573
- })
574
- }), {
575
- signal
576
- }));
577
- currentStage = 'resolution';
849
+ batchId: permissionReady.batchId,
850
+ phase: 'confirmation',
851
+ summary: 'Waiting for confirmation'
852
+ });
853
+ }
854
+ let confirmed;
855
+ try {
856
+ confirmed = await observePreparation('Resolve action confirmation', () => confirmAiActionBatch(permissionReady, this.confirmationHandler, signal, this.redactionOptions));
857
+ }
858
+ catch (error) {
859
+ evidence = {
860
+ ...evidence,
861
+ preview: createAiActionBatchPreview(permissionReady, this.redactionOptions)
862
+ };
863
+ throw error;
864
+ }
865
+ evidence = {
866
+ ...evidence,
867
+ preview: confirmed.preview
868
+ };
869
+ currentStage = 'execution';
870
+ evidence = { ...evidence, executionStarted: true };
871
+ const actionResults = [];
872
+ for (const action of confirmed.actions) {
873
+ const actionCallId = globalThis.crypto.randomUUID();
874
+ const description = action.summary;
875
+ const authored = description &&
876
+ typeof description === 'object' &&
877
+ !Array.isArray(description) &&
878
+ 'kind' in description &&
879
+ description.kind === 'work' &&
880
+ 'text' in description &&
881
+ typeof description.text === 'string'
882
+ ? description.text
883
+ : undefined;
578
884
  emitProgress({
885
+ ...(authored
886
+ ? {
887
+ toolStatus: 'running',
888
+ activity: {
889
+ kind: 'work',
890
+ callId: actionCallId,
891
+ sequence: 0
892
+ }
893
+ }
894
+ : {}),
895
+ actionCount: 1,
579
896
  attempt,
580
- phase: 'resolution',
581
- summary: 'Resolving app actions'
897
+ batchId: confirmed.batchId,
898
+ phase: 'execution',
899
+ tool: action.name,
900
+ summary: authored ??
901
+ (typeof action.summary === 'string'
902
+ ? action.summary
903
+ : 'Preparing the drawing')
582
904
  });
583
- resolved = this.resolveAiActionBatch(actionBatch, {
584
- signal
905
+ failedAction = action.name;
906
+ failedActionId = action.id;
907
+ actionStartedAt = performance.now();
908
+ recording?.trace('action_started', {
909
+ actionId: action.id,
910
+ batchId: confirmed.batchId,
911
+ callId: actionCallId,
912
+ actionName: action.name,
913
+ actor: 'app',
914
+ purpose: action.summary,
915
+ arguments: action.arguments
585
916
  });
586
- break;
917
+ let childSequence = 0;
918
+ const actionMutation = runMutation
919
+ ? async (mutate, settled) => {
920
+ const executor = runMutation;
921
+ if (!executor) {
922
+ throw new AiExecutionError();
923
+ }
924
+ const callId = `${actionCallId}:mutation-${++childSequence}`;
925
+ const endAdmission = recording?.span({
926
+ callId: `${callId}:admission`,
927
+ parentCallId: actionCallId,
928
+ owner: 'app',
929
+ purpose: 'Await mutation admission'
930
+ });
931
+ let admitted = false;
932
+ try {
933
+ return await executor(() => {
934
+ admitted = true;
935
+ endAdmission?.();
936
+ const endMutation = recording?.span({
937
+ callId,
938
+ parentCallId: actionCallId,
939
+ owner: 'app',
940
+ purpose: 'Apply canonical mutation'
941
+ });
942
+ try {
943
+ return mutate();
944
+ }
945
+ finally {
946
+ endMutation?.();
947
+ }
948
+ }, settled);
949
+ }
950
+ finally {
951
+ if (!admitted) {
952
+ endAdmission?.();
953
+ }
954
+ }
955
+ }
956
+ : undefined;
957
+ let completed;
958
+ try {
959
+ completed = await executeAiActions({ ...confirmed, actions: [action] }, signal, this.redactionOptions, actionMutation, {
960
+ reportProgress: (update) => emitProgress({ ...update, attempt, tool: action.name }),
961
+ observe: async (stage, purpose, work) => {
962
+ const end = recording?.span({
963
+ callId: `${actionCallId}:${stage}-${++childSequence}`,
964
+ parentCallId: actionCallId,
965
+ owner: 'app',
966
+ purpose
967
+ });
968
+ try {
969
+ return await work();
970
+ }
971
+ finally {
972
+ end?.();
973
+ }
974
+ }
975
+ });
976
+ recording?.trace('action_completed', {
977
+ actionId: action.id,
978
+ batchId: confirmed.batchId,
979
+ callId: actionCallId,
980
+ actionName: action.name,
981
+ result: completed.actionResults[0]?.result
982
+ });
983
+ }
984
+ catch (error) {
985
+ const receipt = error instanceof AiActionExecutionError ||
986
+ error instanceof AiExecutionError
987
+ ? error.receipt
988
+ : undefined;
989
+ if (receipt) {
990
+ allResults.push(Object.freeze({
991
+ actionId: action.id,
992
+ actionName: action.name,
993
+ result: redactAiValue(receipt.result, this.redactionOptions)
994
+ }));
995
+ }
996
+ recording?.trace('action_failed', {
997
+ ...(receipt
998
+ ? { result: allResults[allResults.length - 1]?.result }
999
+ : {}),
1000
+ actionId: action.id,
1001
+ batchId: confirmed.batchId,
1002
+ callId: actionCallId,
1003
+ actionName: action.name
1004
+ });
1005
+ throw error;
1006
+ }
1007
+ finally {
1008
+ if (authored) {
1009
+ emitProgress({
1010
+ attempt,
1011
+ batchId: confirmed.batchId,
1012
+ phase: 'execution',
1013
+ tool: action.name,
1014
+ toolStatus: 'completed',
1015
+ summary: 'Action execution ended',
1016
+ activity: {
1017
+ kind: 'system',
1018
+ callId: actionCallId,
1019
+ sequence: 0
1020
+ }
1021
+ });
1022
+ }
1023
+ }
1024
+ allResults.push(...completed.actionResults);
1025
+ actionResults.push(...completed.actionResults);
1026
+ failedAction = undefined;
587
1027
  }
588
- catch (error) {
589
- if (signal.aborted || error === INVOCATION_ABORTED) {
590
- throw INVOCATION_ABORTED;
1028
+ const execution = Object.freeze({
1029
+ actionResults: Object.freeze(actionResults)
1030
+ });
1031
+ return { confirmed, execution };
1032
+ };
1033
+ currentStage = 'transaction';
1034
+ const executed = await runAiActionBatchTransaction({
1035
+ run: async (label, execute, options) => {
1036
+ let callbackFailed = false;
1037
+ let callbackError;
1038
+ let endHistory;
1039
+ try {
1040
+ return await this.transactionRunner.run(label, async (scope) => {
1041
+ try {
1042
+ return await execute(scope);
1043
+ }
1044
+ catch (error) {
1045
+ callbackFailed = true;
1046
+ callbackError = error;
1047
+ throw error;
1048
+ }
1049
+ finally {
1050
+ endHistory = recording?.span({
1051
+ callId: 'history-settlement',
1052
+ owner: 'app',
1053
+ purpose: 'Settle request history group'
1054
+ });
1055
+ }
1056
+ }, options);
591
1057
  }
592
- if (error instanceof AiActionBatchResolutionError) {
1058
+ catch (error) {
1059
+ if (error instanceof AiTransactionSettlementError) {
1060
+ evidence = { ...evidence, transactionStatus: error.status };
1061
+ if (error.status === 'unknown') {
1062
+ currentStage = 'transaction';
1063
+ providerFailure = undefined;
1064
+ }
1065
+ throw error.cause;
1066
+ }
1067
+ // A conforming runner preserves the callback error only after rollback.
1068
+ // A different rejection belongs to the transaction owner itself.
1069
+ if (callbackFailed && error === callbackError) {
1070
+ evidence = { ...evidence, transactionStatus: 'rolled-back' };
1071
+ }
1072
+ else {
1073
+ evidence = { ...evidence, transactionStatus: 'unknown' };
1074
+ currentStage = 'transaction';
1075
+ providerFailure = undefined;
1076
+ }
593
1077
  throw error;
594
1078
  }
595
- currentStage = 'provider';
596
- const providerFailure = toAiProviderRequestFailure(error, attempt);
597
- if (!shouldRetryAiProviderFailure(providerFailure, this.retryPolicy)) {
598
- const failed = createFailedResult({
599
- code: providerFailure.code,
600
- message: providerFailure.message,
601
- stage: providerFailure.stage
602
- }, {
603
- retryCount: attempt - 1
604
- }, this.redactionOptions);
1079
+ finally {
1080
+ endHistory?.();
1081
+ }
1082
+ }
1083
+ }, signal, async (scope) => {
1084
+ runMutation = scope;
1085
+ try {
1086
+ let finalBatch;
1087
+ while (true) {
1088
+ currentStage = 'provider';
605
1089
  emitProgress({
606
1090
  attempt,
607
- outcome: 'failed',
608
- phase: 'settled',
609
- summary: 'Failed'
1091
+ phase: 'provider',
1092
+ summary: 'Requesting an action batch'
610
1093
  });
611
- return failed;
1094
+ acceptingBatches = true;
1095
+ const finishProvider = recording?.span({
1096
+ callId: `provider-${attempt}`,
1097
+ owner: 'provider',
1098
+ purpose: 'Await provider action batches'
1099
+ });
1100
+ const providerAttempt = attempt;
1101
+ let lastProgressSequence = 0;
1102
+ try {
1103
+ finalBatch = await runAbortable(signal, () => this.provider.requestActionBatch(Object.freeze({
1104
+ actions,
1105
+ attempt,
1106
+ context,
1107
+ intent,
1108
+ ...(request.metadata === undefined
1109
+ ? {}
1110
+ : { metadata: request.metadata })
1111
+ }), {
1112
+ signal,
1113
+ executeBatch: async (batch) => {
1114
+ if (!acceptingBatches ||
1115
+ batchPending ||
1116
+ signal.aborted) {
1117
+ callbackFailure = new AiExecutionError();
1118
+ throw callbackFailure;
1119
+ }
1120
+ batchPending = true;
1121
+ let settle;
1122
+ batchSettlement = new Promise((resolve) => {
1123
+ settle = resolve;
1124
+ });
1125
+ const resultOffset = allResults.length;
1126
+ try {
1127
+ const { execution } = await executePrepared(batch);
1128
+ contextStale = true;
1129
+ const updatedContext = await refreshContext();
1130
+ currentStage = 'provider';
1131
+ return Object.freeze({
1132
+ actionResults: execution.actionResults,
1133
+ context: updatedContext
1134
+ });
1135
+ }
1136
+ catch (error) {
1137
+ if (signal.aborted || error === INVOCATION_ABORTED) {
1138
+ throw INVOCATION_ABORTED;
1139
+ }
1140
+ const stage = currentStage;
1141
+ const actionExecutionMs = stage === 'execution' &&
1142
+ actionStartedAt !== undefined
1143
+ ? Math.max(0, performance.now() - actionStartedAt)
1144
+ : null;
1145
+ const actionName = failedAction ?? null;
1146
+ const ownerError = error instanceof AiTransactionSettlementError
1147
+ ? error.cause
1148
+ : error;
1149
+ const failure = stableFailure(ownerError, {
1150
+ code: 'AI_EXECUTION_FAILED',
1151
+ message: 'The batch could not complete.',
1152
+ stage
1153
+ });
1154
+ contextStale = true;
1155
+ try {
1156
+ await refreshContext();
1157
+ }
1158
+ catch {
1159
+ if (signal.aborted) {
1160
+ throw INVOCATION_ABORTED;
1161
+ }
1162
+ }
1163
+ let settlement = stage === 'execution' || stage === 'context'
1164
+ ? 'unknown'
1165
+ : 'not-started';
1166
+ if (error instanceof AiTransactionSettlementError) {
1167
+ if (error.status === 'rolled-back') {
1168
+ settlement = 'not-started';
1169
+ }
1170
+ else if (error.status === 'committed') {
1171
+ settlement = 'completed';
1172
+ }
1173
+ }
1174
+ if (error instanceof AiActionExecutionError &&
1175
+ error.receipt) {
1176
+ settlement = error.receipt.settlement;
1177
+ }
1178
+ if (error instanceof AiToolContractError) {
1179
+ settlement =
1180
+ error.inspection?.settlement ?? 'not-started';
1181
+ }
1182
+ currentStage = 'provider';
1183
+ return Object.freeze({
1184
+ actionResults: allResults.slice(resultOffset),
1185
+ context,
1186
+ failure: {
1187
+ code: failure.code,
1188
+ message: failure.message,
1189
+ ...(ownerError instanceof AiActionInputError
1190
+ ? {
1191
+ inputIssue: redactAiValue(ownerError.issue, this.redactionOptions)
1192
+ }
1193
+ : {}),
1194
+ stage,
1195
+ actionName,
1196
+ actionId: stage === 'execution' ? failedActionId : null,
1197
+ actionExecutionMs,
1198
+ settlement,
1199
+ ...(error instanceof AiToolContractError
1200
+ ? {
1201
+ contractStage: error.stage,
1202
+ ...(error.inspection
1203
+ ? {
1204
+ observedResult: redactAiValue(error.inspection.value, this.redactionOptions)
1205
+ }
1206
+ : {})
1207
+ }
1208
+ : {}),
1209
+ contextFresh: !contextStale
1210
+ }
1211
+ });
1212
+ }
1213
+ finally {
1214
+ batchPending = false;
1215
+ settle();
1216
+ }
1217
+ },
1218
+ onProgress: (event) => {
1219
+ if (!acceptingBatches ||
1220
+ attempt !== providerAttempt ||
1221
+ signal.aborted ||
1222
+ !event ||
1223
+ typeof event.tool !== 'string' ||
1224
+ !/^[a-zA-Z0-9_-]{1,64}$/.test(event.tool) ||
1225
+ !['running', 'completed'].includes(event.status)) {
1226
+ return;
1227
+ }
1228
+ if (event.activity) {
1229
+ const activity = event.activity;
1230
+ if (!isExecutionActivity(activity) ||
1231
+ activity.sequence <= lastProgressSequence) {
1232
+ return;
1233
+ }
1234
+ lastProgressSequence = activity.sequence;
1235
+ }
1236
+ emitProgress({
1237
+ attempt,
1238
+ phase: 'provider',
1239
+ tool: event.tool,
1240
+ toolStatus: event.status,
1241
+ ...(event.activity
1242
+ ? { activity: event.activity }
1243
+ : {}),
1244
+ ...(typeof event.message === 'string' &&
1245
+ Array.from(event.message).length <= 1000
1246
+ ? { message: event.message }
1247
+ : {}),
1248
+ summary: event.status === 'running'
1249
+ ? 'Running a tool'
1250
+ : 'Tool completed'
1251
+ });
1252
+ }
1253
+ }));
1254
+ if (callbackFailure) {
1255
+ throw callbackFailure;
1256
+ }
1257
+ if (batchPending) {
1258
+ throw new AiExecutionError();
1259
+ }
1260
+ break;
1261
+ }
1262
+ catch (error) {
1263
+ if (signal.aborted || error === INVOCATION_ABORTED) {
1264
+ throw INVOCATION_ABORTED;
1265
+ }
1266
+ if (callbackFailure) {
1267
+ throw callbackFailure;
1268
+ }
1269
+ const failure = toAiProviderRequestFailure(error, attempt);
1270
+ if (batchIds.size > 0 ||
1271
+ !shouldRetryAiProviderFailure(failure, this.retryPolicy)) {
1272
+ providerFailure = failure;
1273
+ throw error;
1274
+ }
1275
+ attempt += 1;
1276
+ evidence = { retryCount: attempt - 1 };
1277
+ }
1278
+ finally {
1279
+ acceptingBatches = false;
1280
+ finishProvider?.();
1281
+ await batchSettlement;
1282
+ }
612
1283
  }
613
- attempt += 1;
614
- evidence = {
615
- retryCount: attempt - 1
616
- };
617
- }
618
- }
619
- evidence = {
620
- batch: resolved,
621
- retryCount: attempt - 1
622
- };
623
- currentStage = 'permission';
624
- emitProgress({
625
- actionCount: resolved.actions.length,
626
- attempt,
627
- batchId: resolved.batchId,
628
- phase: 'permission',
629
- summary: 'Checking action permissions'
630
- });
631
- const permissionReady = await evaluateAiActionBatchPermissions(resolved, context, this.permissionPolicy);
632
- currentStage = 'confirmation';
633
- if (permissionReady.confirmationRequired) {
634
- emitProgress({
635
- actionCount: permissionReady.actions.length,
636
- attempt,
637
- batchId: permissionReady.batchId,
638
- phase: 'confirmation',
639
- summary: 'Waiting for confirmation'
640
- });
641
- }
642
- let confirmed;
643
- try {
644
- confirmed = await confirmAiActionBatch(permissionReady, this.confirmationHandler, signal, this.redactionOptions);
645
- }
646
- catch (error) {
647
- if (error instanceof AiConfirmationError &&
648
- error.code === 'AI_CONFIRMATION_CANCELLED') {
649
- const cancelled = createCancelledResult('confirmation-cancelled', {
650
- ...evidence,
651
- preview: createAiActionBatchPreview(permissionReady, this.redactionOptions)
1284
+ const { confirmed } = await executePrepared(finalBatch);
1285
+ currentStage = 'audit';
1286
+ const audit = createAiRuntimeAudit({
1287
+ actionResults: allResults,
1288
+ ...(confirmed.explanation === undefined
1289
+ ? {}
1290
+ : { explanation: confirmed.explanation }),
1291
+ outcome: 'executed',
1292
+ batchId: confirmed.batchId,
1293
+ retryCount: evidence.retryCount
652
1294
  }, this.redactionOptions);
653
- emitProgress({
654
- actionCount: permissionReady.actions.length,
655
- attempt,
656
- batchId: permissionReady.batchId,
657
- outcome: 'cancelled',
658
- phase: 'settled',
659
- summary: 'Cancelled'
1295
+ currentStage = 'transaction';
1296
+ return Object.freeze({
1297
+ actionResults: Object.freeze([...allResults]),
1298
+ audit,
1299
+ batchId: confirmed.batchId,
1300
+ preview: confirmed.preview,
1301
+ status: 'executed',
1302
+ transaction: Object.freeze({ status: 'committed' })
1303
+ });
1304
+ }
1305
+ catch (error) {
1306
+ if (runMutation ||
1307
+ !this.preserveProgress ||
1308
+ !evidence.executionStarted ||
1309
+ signal.aborted ||
1310
+ error === INVOCATION_ABORTED ||
1311
+ (error instanceof AiConfirmationError &&
1312
+ error.code === 'AI_CONFIRMATION_CANCELLED')) {
1313
+ throw error;
1314
+ }
1315
+ const failed = createFailedResult(providerFailure ??
1316
+ stableFailure(error, STAGE_FAILURES[currentStage]), evidence, this.redactionOptions);
1317
+ // Returning normally asks the canonical transaction owner to commit.
1318
+ // A settlement error still escapes and must never claim retained progress.
1319
+ return Object.freeze({
1320
+ ...failed,
1321
+ actionResults: Object.freeze([...allResults]),
1322
+ ...(failedAction ? { failedAction } : {}),
1323
+ audit: createAiRuntimeAudit({
1324
+ actionResults: allResults,
1325
+ outcome: 'failed',
1326
+ retryCount: evidence.retryCount,
1327
+ ...(evidence.batch ? { batchId: evidence.batch.batchId } : {})
1328
+ }, this.redactionOptions),
1329
+ transaction: Object.freeze({ status: 'committed' })
660
1330
  });
661
- return cancelled;
662
1331
  }
663
- throw error;
664
- }
665
- evidence = {
666
- ...evidence,
667
- preview: confirmed.preview
668
- };
669
- currentStage = 'transaction';
670
- emitProgress({
671
- actionCount: confirmed.actions.length,
672
- attempt,
673
- batchId: confirmed.batchId,
674
- phase: 'execution',
675
- summary: 'Applying changes'
676
- });
677
- const execution = await runAiActionBatchTransaction(this.transactionRunner, signal, async () => {
678
- currentStage = 'execution';
679
- const result = await executeAiActions(confirmed, signal, this.redactionOptions);
680
- currentStage = 'transaction';
681
- return result;
682
- });
683
- currentStage = 'audit';
684
- const audit = createAiRuntimeAudit({
685
- actionResults: execution.actionResults,
686
- ...(confirmed.explanation === undefined
687
- ? {}
688
- : {
689
- explanation: confirmed.explanation
690
- }),
691
- outcome: 'executed',
692
- batchId: confirmed.batchId,
693
- retryCount: evidence.retryCount
694
- }, this.redactionOptions);
695
- const executed = Object.freeze({
696
- actionResults: execution.actionResults,
697
- audit,
698
- batchId: confirmed.batchId,
699
- preview: confirmed.preview,
700
- status: 'executed',
701
- transaction: Object.freeze({
702
- status: 'committed'
703
- })
704
1332
  });
705
1333
  emitProgress({
706
- actionCount: confirmed.actions.length,
1334
+ actionCount: allResults.length,
707
1335
  attempt,
708
- batchId: confirmed.batchId,
709
- outcome: 'executed',
1336
+ batchId: executed.batchId,
1337
+ outcome: executed.status === 'executed' ? 'executed' : 'failed',
710
1338
  phase: 'settled',
711
- summary: 'Completed'
1339
+ summary: executed.status === 'executed' ? 'Completed' : 'Failed'
712
1340
  });
713
1341
  return executed;
714
1342
  }
715
1343
  catch (error) {
716
1344
  if (signal.aborted || error === INVOCATION_ABORTED) {
717
- return createCancelledResult('aborted', evidence, this.redactionOptions);
1345
+ return Object.freeze({
1346
+ ...createCancelledResult('aborted', evidence, this.redactionOptions),
1347
+ ...(allResults.length && evidence.transactionStatus !== 'rolled-back'
1348
+ ? { actionResults: Object.freeze([...allResults]) }
1349
+ : {})
1350
+ });
718
1351
  }
719
- const failed = createFailedResult(stableFailure(error, STAGE_FAILURES[currentStage]), evidence, this.redactionOptions);
1352
+ if (error instanceof AiConfirmationError &&
1353
+ error.code === 'AI_CONFIRMATION_CANCELLED') {
1354
+ emitProgress({
1355
+ attempt,
1356
+ outcome: 'cancelled',
1357
+ phase: 'settled',
1358
+ summary: 'Cancelled'
1359
+ });
1360
+ return createCancelledResult('confirmation-cancelled', evidence, this.redactionOptions);
1361
+ }
1362
+ const failed = createFailedResult(providerFailure ?? stableFailure(error, STAGE_FAILURES[currentStage]), evidence, this.redactionOptions);
720
1363
  emitProgress({
721
1364
  attempt: evidence.retryCount + 1,
722
1365
  outcome: 'failed',
@@ -728,7 +1371,13 @@ class DefaultAiAgentRuntime {
728
1371
  }),
729
1372
  summary: 'Failed'
730
1373
  });
731
- return failed;
1374
+ return evidence.transactionStatus === 'committed'
1375
+ ? Object.freeze({
1376
+ ...failed,
1377
+ actionResults: Object.freeze([...allResults]),
1378
+ ...(failedAction ? { failedAction } : {})
1379
+ })
1380
+ : failed;
732
1381
  }
733
1382
  }
734
1383
  }