@asyra/ai-agent-runtime 0.5.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 (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -0
  3. package/dist/action-batch.d.ts +31 -0
  4. package/dist/action-batch.d.ts.map +1 -0
  5. package/dist/action-batch.js +143 -0
  6. package/dist/action-batch.js.map +1 -0
  7. package/dist/action-registry.d.ts +7 -0
  8. package/dist/action-registry.d.ts.map +1 -0
  9. package/dist/action-registry.js +122 -0
  10. package/dist/action-registry.js.map +1 -0
  11. package/dist/audit.d.ts +30 -0
  12. package/dist/audit.d.ts.map +1 -0
  13. package/dist/audit.js +42 -0
  14. package/dist/audit.js.map +1 -0
  15. package/dist/index.d.ts +17 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +9 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/provider-retry.d.ts +26 -0
  20. package/dist/provider-retry.d.ts.map +1 -0
  21. package/dist/provider-retry.js +79 -0
  22. package/dist/provider-retry.js.map +1 -0
  23. package/dist/provider.d.ts +40 -0
  24. package/dist/provider.d.ts.map +1 -0
  25. package/dist/provider.js +11 -0
  26. package/dist/provider.js.map +1 -0
  27. package/dist/providers/generic-http.d.ts +24 -0
  28. package/dist/providers/generic-http.d.ts.map +1 -0
  29. package/dist/providers/generic-http.js +333 -0
  30. package/dist/providers/generic-http.js.map +1 -0
  31. package/dist/redaction.d.ts +7 -0
  32. package/dist/redaction.d.ts.map +1 -0
  33. package/dist/redaction.js +69 -0
  34. package/dist/redaction.js.map +1 -0
  35. package/dist/runtime.d.ts +164 -0
  36. package/dist/runtime.d.ts.map +1 -0
  37. package/dist/runtime.js +736 -0
  38. package/dist/runtime.js.map +1 -0
  39. package/dist/types.d.ts +27 -0
  40. package/dist/types.d.ts.map +1 -0
  41. package/dist/types.js +2 -0
  42. package/dist/types.js.map +1 -0
  43. package/package.json +42 -0
@@ -0,0 +1,736 @@
1
+ import { AiActionRegistryError, createAiActionRegistry } from './action-registry.js';
2
+ import { AiAuditError, createAiRuntimeAudit } from './audit.js';
3
+ import { AiActionBatchResolutionError, resolveAiActionBatchWithRegistry } from './action-batch.js';
4
+ import { AiRetryPolicyError, MAX_AI_PROVIDER_ATTEMPTS, shouldRetryAiProviderFailure, toAiProviderRequestFailure } from './provider-retry.js';
5
+ import { AI_REDACTED_VALUE, redactAiValue } from './redaction.js';
6
+ export const AI_ACTION_BATCH_TRANSACTION_LABEL = 'AI-assisted action';
7
+ export class AiTransactionError extends Error {
8
+ constructor() {
9
+ super('AI action batch transaction was aborted.');
10
+ this.code = 'AI_TRANSACTION_ABORTED';
11
+ this.stage = 'transaction';
12
+ this.name = 'AiTransactionError';
13
+ }
14
+ }
15
+ export class AiExecutionError extends Error {
16
+ constructor() {
17
+ super('AI action execution was aborted.');
18
+ this.code = 'AI_EXECUTION_ABORTED';
19
+ this.stage = 'execution';
20
+ this.name = 'AiExecutionError';
21
+ }
22
+ }
23
+ export class AiPermissionError extends Error {
24
+ constructor(code, message, deniedActionIds = []) {
25
+ super(message);
26
+ this.stage = 'permission';
27
+ this.name = 'AiPermissionError';
28
+ this.code = code;
29
+ this.deniedActionIds = Object.freeze([...deniedActionIds]);
30
+ }
31
+ }
32
+ export class AiConfirmationError extends Error {
33
+ constructor(code, message) {
34
+ super(message);
35
+ this.stage = 'confirmation';
36
+ this.name = 'AiConfirmationError';
37
+ this.code = code;
38
+ }
39
+ }
40
+ const permissionPolicyFailed = () => {
41
+ throw new AiPermissionError('AI_PERMISSION_POLICY_FAILED', 'App permission policy failed.');
42
+ };
43
+ const isPermissionDecision = (value) => value === 'allow' || value === 'confirm' || value === 'deny';
44
+ export const evaluateAiActionBatchPermissions = async (batch, context, policy) => {
45
+ const decisions = [];
46
+ for (const action of batch.actions) {
47
+ let decision;
48
+ try {
49
+ decision = await policy.evaluate({
50
+ action: Object.freeze({
51
+ arguments: action.arguments,
52
+ id: action.id,
53
+ name: action.name
54
+ }),
55
+ context
56
+ });
57
+ }
58
+ catch {
59
+ return permissionPolicyFailed();
60
+ }
61
+ if (!isPermissionDecision(decision)) {
62
+ return permissionPolicyFailed();
63
+ }
64
+ decisions.push(decision);
65
+ }
66
+ const deniedActionIds = batch.actions.flatMap((action, index) => decisions[index] === 'deny' ? [action.id] : []);
67
+ if (deniedActionIds.length > 0) {
68
+ throw new AiPermissionError('AI_PERMISSION_DENIED', 'App permission policy denied the complete action batch.', deniedActionIds);
69
+ }
70
+ const actions = batch.actions.map((action, index) => Object.freeze({
71
+ ...action,
72
+ permission: decisions[index]
73
+ }));
74
+ const ready = {
75
+ actions: Object.freeze(actions),
76
+ batchId: batch.batchId,
77
+ confirmationRequired: decisions.includes('confirm')
78
+ };
79
+ if (batch.explanation !== undefined) {
80
+ Object.defineProperty(ready, 'explanation', {
81
+ configurable: true,
82
+ enumerable: true,
83
+ value: batch.explanation,
84
+ writable: true
85
+ });
86
+ }
87
+ return Object.freeze(ready);
88
+ };
89
+ const confirmationError = (code, message) => {
90
+ throw new AiConfirmationError(code, message);
91
+ };
92
+ const createAiActionBatchPreview = (batch, redactionOptions) => {
93
+ const actions = batch.actions.map((action) => Object.freeze({
94
+ id: action.id,
95
+ name: action.name,
96
+ permission: action.permission,
97
+ summary: redactAiValue(action.summary, redactionOptions)
98
+ }));
99
+ const preview = {
100
+ actions: Object.freeze(actions),
101
+ batchId: batch.batchId
102
+ };
103
+ if (batch.explanation !== undefined) {
104
+ const explanation = redactAiValue(batch.explanation, redactionOptions);
105
+ Object.defineProperty(preview, 'explanation', {
106
+ configurable: true,
107
+ enumerable: true,
108
+ value: typeof explanation === 'string' ? explanation : '[REDACTED]',
109
+ writable: true
110
+ });
111
+ }
112
+ return Object.freeze(preview);
113
+ };
114
+ const createConfirmedActionBatch = (batch, preview, confirmation) => Object.freeze({
115
+ ...batch,
116
+ confirmation,
117
+ preview
118
+ });
119
+ const CONFIRMATION_ABORTED = Symbol('CONFIRMATION_ABORTED');
120
+ export const confirmAiActionBatch = async (batch, handler, signal, redactionOptions = {}) => {
121
+ if (signal.aborted) {
122
+ return confirmationError('AI_CONFIRMATION_ABORTED', 'AI action batch confirmation was aborted.');
123
+ }
124
+ const preview = createAiActionBatchPreview(batch, redactionOptions);
125
+ if (!batch.confirmationRequired) {
126
+ return createConfirmedActionBatch(batch, preview, 'bypassed');
127
+ }
128
+ let abortListener;
129
+ const aborted = new Promise((_resolve, reject) => {
130
+ abortListener = () => reject(CONFIRMATION_ABORTED);
131
+ signal.addEventListener('abort', abortListener, {
132
+ once: true
133
+ });
134
+ });
135
+ try {
136
+ const decision = await Promise.race([
137
+ Promise.resolve().then(() => handler.confirm(preview, {
138
+ signal
139
+ })),
140
+ aborted
141
+ ]);
142
+ if (signal.aborted) {
143
+ return confirmationError('AI_CONFIRMATION_ABORTED', 'AI action batch confirmation was aborted.');
144
+ }
145
+ if (typeof decision !== 'boolean') {
146
+ return confirmationError('AI_CONFIRMATION_HANDLER_FAILED', 'App confirmation handler failed.');
147
+ }
148
+ if (!decision) {
149
+ return confirmationError('AI_CONFIRMATION_CANCELLED', 'AI action batch confirmation was cancelled.');
150
+ }
151
+ return createConfirmedActionBatch(batch, preview, 'accepted');
152
+ }
153
+ catch (error) {
154
+ if (error instanceof AiConfirmationError) {
155
+ throw error;
156
+ }
157
+ if (signal.aborted || error === CONFIRMATION_ABORTED) {
158
+ return confirmationError('AI_CONFIRMATION_ABORTED', 'AI action batch confirmation was aborted.');
159
+ }
160
+ return confirmationError('AI_CONFIRMATION_HANDLER_FAILED', 'App confirmation handler failed.');
161
+ }
162
+ finally {
163
+ if (abortListener) {
164
+ signal.removeEventListener('abort', abortListener);
165
+ }
166
+ }
167
+ };
168
+ const assertTransactionNotAborted = (signal) => {
169
+ if (signal.aborted) {
170
+ throw new AiTransactionError();
171
+ }
172
+ };
173
+ export const runAiActionBatchTransaction = async (runner, signal, execute) => {
174
+ assertTransactionNotAborted(signal);
175
+ return runner.run(AI_ACTION_BATCH_TRANSACTION_LABEL, async () => {
176
+ assertTransactionNotAborted(signal);
177
+ const result = await execute();
178
+ assertTransactionNotAborted(signal);
179
+ return result;
180
+ });
181
+ };
182
+ const assertExecutionNotAborted = (signal) => {
183
+ if (signal.aborted) {
184
+ throw new AiExecutionError();
185
+ }
186
+ };
187
+ export const executeAiActions = async (batch, signal, redactionOptions = {}) => {
188
+ const actionResults = [];
189
+ const context = Object.freeze({
190
+ signal
191
+ });
192
+ for (const action of batch.actions) {
193
+ assertExecutionNotAborted(signal);
194
+ const result = await action.execute(action.arguments, context);
195
+ assertExecutionNotAborted(signal);
196
+ actionResults.push(Object.freeze({
197
+ actionId: action.id,
198
+ actionName: action.name,
199
+ result: redactAiValue(result, redactionOptions)
200
+ }));
201
+ }
202
+ return Object.freeze({
203
+ actionResults: Object.freeze(actionResults)
204
+ });
205
+ };
206
+ const INVOCATION_ABORTED = Symbol('INVOCATION_ABORTED');
207
+ const emitAiRuntimeProgress = (observer, signal, update, redactionOptions) => {
208
+ if (!observer || signal.aborted) {
209
+ return;
210
+ }
211
+ try {
212
+ let batchId = update.batchId;
213
+ if (batchId !== undefined) {
214
+ const redacted = redactAiValue({ batchId }, redactionOptions);
215
+ const redactedBatchId = typeof redacted === 'object' && redacted !== null
216
+ ? Reflect.get(redacted, 'batchId')
217
+ : undefined;
218
+ batchId =
219
+ typeof redactedBatchId === 'string'
220
+ ? redactedBatchId
221
+ : AI_REDACTED_VALUE;
222
+ }
223
+ observer(Object.freeze({
224
+ ...update,
225
+ ...(batchId === undefined ? {} : { batchId })
226
+ }));
227
+ }
228
+ catch {
229
+ // Progress is observational and cannot alter runtime execution.
230
+ }
231
+ };
232
+ const runAbortable = async (signal, operation) => {
233
+ if (signal.aborted) {
234
+ throw INVOCATION_ABORTED;
235
+ }
236
+ let abortListener;
237
+ const aborted = new Promise((_resolve, reject) => {
238
+ abortListener = () => reject(INVOCATION_ABORTED);
239
+ signal.addEventListener('abort', abortListener, {
240
+ once: true
241
+ });
242
+ });
243
+ try {
244
+ return await Promise.race([Promise.resolve().then(operation), aborted]);
245
+ }
246
+ finally {
247
+ if (abortListener) {
248
+ signal.removeEventListener('abort', abortListener);
249
+ }
250
+ }
251
+ };
252
+ const stableFailure = (error, fallback) => {
253
+ if (error instanceof AiActionBatchResolutionError) {
254
+ return {
255
+ code: error.code,
256
+ message: error.message,
257
+ stage: error.stage
258
+ };
259
+ }
260
+ if (error instanceof AiPermissionError) {
261
+ return {
262
+ code: error.code,
263
+ message: error.message,
264
+ stage: error.stage
265
+ };
266
+ }
267
+ if (error instanceof AiConfirmationError) {
268
+ return {
269
+ code: error.code,
270
+ message: error.message,
271
+ stage: error.stage
272
+ };
273
+ }
274
+ if (error instanceof AiTransactionError) {
275
+ return {
276
+ code: error.code,
277
+ message: error.message,
278
+ stage: error.stage
279
+ };
280
+ }
281
+ if (error instanceof AiExecutionError) {
282
+ return {
283
+ code: error.code,
284
+ message: error.message,
285
+ stage: error.stage
286
+ };
287
+ }
288
+ if (error instanceof AiRetryPolicyError) {
289
+ return {
290
+ code: error.code,
291
+ message: error.message,
292
+ stage: 'provider'
293
+ };
294
+ }
295
+ if (error instanceof AiActionRegistryError) {
296
+ return {
297
+ code: error.code,
298
+ message: error.message,
299
+ stage: 'registry'
300
+ };
301
+ }
302
+ if (error instanceof AiAuditError) {
303
+ return {
304
+ code: error.code,
305
+ message: error.message,
306
+ stage: error.stage
307
+ };
308
+ }
309
+ return fallback;
310
+ };
311
+ const STAGE_FAILURES = Object.freeze({
312
+ audit: Object.freeze({
313
+ code: 'AI_AUDIT_FAILED',
314
+ message: 'AI audit output failed.',
315
+ stage: 'audit'
316
+ }),
317
+ confirmation: Object.freeze({
318
+ code: 'AI_CONFIRMATION_HANDLER_FAILED',
319
+ message: 'App confirmation handler failed.',
320
+ stage: 'confirmation'
321
+ }),
322
+ context: Object.freeze({
323
+ code: 'AI_CONTEXT_FAILED',
324
+ message: 'AI context collection failed.',
325
+ stage: 'context'
326
+ }),
327
+ execution: Object.freeze({
328
+ code: 'AI_EXECUTION_FAILED',
329
+ message: 'AI action execution failed.',
330
+ stage: 'execution'
331
+ }),
332
+ permission: Object.freeze({
333
+ code: 'AI_PERMISSION_POLICY_FAILED',
334
+ message: 'App permission policy failed.',
335
+ stage: 'permission'
336
+ }),
337
+ provider: Object.freeze({
338
+ code: 'AI_RETRY_POLICY_FAILED',
339
+ message: 'AI provider retry policy failed.',
340
+ stage: 'provider'
341
+ }),
342
+ registry: Object.freeze({
343
+ code: 'AI_ACTION_REGISTRY_FAILED',
344
+ message: 'AI action registry failed.',
345
+ stage: 'registry'
346
+ }),
347
+ runtime: Object.freeze({
348
+ code: 'AI_RUNTIME_FAILED',
349
+ message: 'AI runtime failed.',
350
+ stage: 'runtime'
351
+ }),
352
+ transaction: Object.freeze({
353
+ code: 'AI_TRANSACTION_FAILED',
354
+ message: 'AI action batch transaction failed.',
355
+ stage: 'transaction'
356
+ }),
357
+ resolution: Object.freeze({
358
+ code: 'AI_RESOLUTION_FAILED',
359
+ message: 'AI action batch resolution failed.',
360
+ stage: 'resolution'
361
+ })
362
+ });
363
+ const createFailedResult = (failure, evidence, redactionOptions) => Object.freeze({
364
+ audit: createAiRuntimeAudit({
365
+ ...(evidence.batch?.explanation === undefined
366
+ ? {}
367
+ : {
368
+ explanation: evidence.batch.explanation
369
+ }),
370
+ ...(evidence.batch?.batchId === undefined
371
+ ? {}
372
+ : {
373
+ batchId: evidence.batch.batchId
374
+ }),
375
+ outcome: 'failed',
376
+ retryCount: evidence.retryCount
377
+ }, redactionOptions),
378
+ ...(evidence.batch?.batchId === undefined
379
+ ? {}
380
+ : {
381
+ batchId: evidence.batch.batchId
382
+ }),
383
+ code: failure.code,
384
+ message: failure.message,
385
+ ...(evidence.preview === undefined
386
+ ? {}
387
+ : {
388
+ preview: evidence.preview
389
+ }),
390
+ retryCount: evidence.retryCount,
391
+ stage: failure.stage,
392
+ status: 'failed'
393
+ });
394
+ const createCancelledResult = (reason, evidence, redactionOptions) => {
395
+ const result = {
396
+ audit: createAiRuntimeAudit({
397
+ ...(evidence.batch?.explanation === undefined
398
+ ? {}
399
+ : {
400
+ explanation: evidence.batch.explanation
401
+ }),
402
+ ...(evidence.batch?.batchId === undefined
403
+ ? {}
404
+ : {
405
+ batchId: evidence.batch.batchId
406
+ }),
407
+ outcome: 'cancelled',
408
+ retryCount: evidence.retryCount
409
+ }, redactionOptions),
410
+ reason,
411
+ status: 'cancelled'
412
+ };
413
+ if (evidence.preview) {
414
+ result.preview = evidence.preview;
415
+ }
416
+ return Object.freeze(result);
417
+ };
418
+ const validateRuntimeOptions = (options) => {
419
+ const retryPolicy = options?.retryPolicy;
420
+ if (retryPolicy &&
421
+ (!Number.isInteger(retryPolicy.maxAttempts) ||
422
+ retryPolicy.maxAttempts < 1 ||
423
+ retryPolicy.maxAttempts > MAX_AI_PROVIDER_ATTEMPTS)) {
424
+ throw new AiRetryPolicyError();
425
+ }
426
+ const redaction = Object.freeze({
427
+ additionalSecretKeys: Object.freeze([
428
+ ...(options?.redaction?.additionalSecretKeys ?? [])
429
+ ])
430
+ });
431
+ const validated = {
432
+ redaction
433
+ };
434
+ if (retryPolicy) {
435
+ validated.retryPolicy = Object.freeze({
436
+ maxAttempts: retryPolicy.maxAttempts,
437
+ ...(retryPolicy.shouldRetry
438
+ ? {
439
+ shouldRetry: retryPolicy.shouldRetry
440
+ }
441
+ : {})
442
+ });
443
+ }
444
+ return Object.freeze(validated);
445
+ };
446
+ class DefaultAiAgentRuntime {
447
+ constructor(input) {
448
+ this.activeInvocations = new Set();
449
+ this.disposed = false;
450
+ const options = validateRuntimeOptions(input.options);
451
+ this.provider = input.provider;
452
+ this.contextProvider = input.contextProvider;
453
+ this.permissionPolicy = input.permissionPolicy;
454
+ this.confirmationHandler = input.confirmationHandler;
455
+ this.transactionRunner = input.transactionRunner;
456
+ this.redactionOptions = options.redaction;
457
+ this.retryPolicy = options.retryPolicy;
458
+ this.ownedResources = Object.freeze([...(input.ownedResources ?? [])]);
459
+ this.registry = createAiActionRegistry();
460
+ for (const action of input.actionDefinitions) {
461
+ this.registry.register(action);
462
+ }
463
+ }
464
+ resolveAiActionBatch(batch, options) {
465
+ return resolveAiActionBatchWithRegistry(batch, this.registry, options);
466
+ }
467
+ run(request) {
468
+ if (this.disposed) {
469
+ return Promise.resolve(createFailedResult({
470
+ code: 'AI_RUNTIME_DISPOSED',
471
+ message: 'AI runtime has been disposed.',
472
+ stage: 'runtime'
473
+ }, {
474
+ retryCount: 0
475
+ }, this.redactionOptions));
476
+ }
477
+ const controller = new AbortController();
478
+ const abortInvocation = () => controller.abort(request.signal.reason);
479
+ if (request.signal.aborted) {
480
+ abortInvocation();
481
+ }
482
+ else {
483
+ request.signal.addEventListener('abort', abortInvocation, {
484
+ once: true
485
+ });
486
+ }
487
+ const active = {
488
+ controller,
489
+ settlement: Promise.resolve(createCancelledResult('aborted', {
490
+ retryCount: 0
491
+ }, this.redactionOptions))
492
+ };
493
+ this.activeInvocations.add(active);
494
+ active.settlement = this.runInvocation({
495
+ intent: request.intent,
496
+ ...(request.metadata === undefined
497
+ ? {}
498
+ : {
499
+ metadata: redactAiValue(request.metadata, this.redactionOptions)
500
+ }),
501
+ signal: controller.signal
502
+ }, controller.signal, request.progressObserver).finally(() => {
503
+ request.signal.removeEventListener('abort', abortInvocation);
504
+ this.activeInvocations.delete(active);
505
+ });
506
+ return active.settlement;
507
+ }
508
+ dispose() {
509
+ if (!this.disposal) {
510
+ this.disposal = this.disposeRuntime();
511
+ }
512
+ return this.disposal;
513
+ }
514
+ async disposeRuntime() {
515
+ this.disposed = true;
516
+ const active = [...this.activeInvocations];
517
+ for (const invocation of active) {
518
+ invocation.controller.abort();
519
+ }
520
+ await Promise.allSettled(active.map((invocation) => invocation.settlement));
521
+ this.registry.dispose();
522
+ const cleanups = await Promise.allSettled(this.ownedResources.map((resource) => Promise.resolve().then(() => resource.dispose())));
523
+ const failed = cleanups.find((result) => result.status === 'rejected');
524
+ if (failed) {
525
+ throw failed.reason;
526
+ }
527
+ }
528
+ async runInvocation(request, signal, progressObserver) {
529
+ let evidence = {
530
+ retryCount: 0
531
+ };
532
+ let currentStage = 'context';
533
+ const emitProgress = (update) => emitAiRuntimeProgress(progressObserver, signal, update, this.redactionOptions);
534
+ try {
535
+ const intent = typeof request.intent === 'string' ? request.intent.trim() : '';
536
+ if (!intent) {
537
+ return createFailedResult({
538
+ code: 'AI_RUNTIME_INVALID_INTENT',
539
+ message: 'AI runtime requires a non-empty intent.',
540
+ stage: 'runtime'
541
+ }, evidence, this.redactionOptions);
542
+ }
543
+ emitProgress({
544
+ attempt: 1,
545
+ phase: 'context',
546
+ summary: 'Understanding the request'
547
+ });
548
+ const context = redactAiValue(await runAbortable(signal, () => this.contextProvider.getContext({
549
+ intent,
550
+ signal
551
+ })), this.redactionOptions);
552
+ currentStage = 'registry';
553
+ const actions = this.registry.list();
554
+ currentStage = 'provider';
555
+ let attempt = 1;
556
+ let resolved;
557
+ while (true) {
558
+ emitProgress({
559
+ attempt,
560
+ phase: 'provider',
561
+ summary: 'Requesting an action batch'
562
+ });
563
+ try {
564
+ const actionBatch = await runAbortable(signal, () => this.provider.requestActionBatch(Object.freeze({
565
+ actions,
566
+ attempt,
567
+ context,
568
+ intent,
569
+ ...(request.metadata === undefined
570
+ ? {}
571
+ : {
572
+ metadata: request.metadata
573
+ })
574
+ }), {
575
+ signal
576
+ }));
577
+ currentStage = 'resolution';
578
+ emitProgress({
579
+ attempt,
580
+ phase: 'resolution',
581
+ summary: 'Resolving app actions'
582
+ });
583
+ resolved = this.resolveAiActionBatch(actionBatch, {
584
+ signal
585
+ });
586
+ break;
587
+ }
588
+ catch (error) {
589
+ if (signal.aborted || error === INVOCATION_ABORTED) {
590
+ throw INVOCATION_ABORTED;
591
+ }
592
+ if (error instanceof AiActionBatchResolutionError) {
593
+ throw error;
594
+ }
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);
605
+ emitProgress({
606
+ attempt,
607
+ outcome: 'failed',
608
+ phase: 'settled',
609
+ summary: 'Failed'
610
+ });
611
+ return failed;
612
+ }
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)
652
+ }, this.redactionOptions);
653
+ emitProgress({
654
+ actionCount: permissionReady.actions.length,
655
+ attempt,
656
+ batchId: permissionReady.batchId,
657
+ outcome: 'cancelled',
658
+ phase: 'settled',
659
+ summary: 'Cancelled'
660
+ });
661
+ return cancelled;
662
+ }
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
+ });
705
+ emitProgress({
706
+ actionCount: confirmed.actions.length,
707
+ attempt,
708
+ batchId: confirmed.batchId,
709
+ outcome: 'executed',
710
+ phase: 'settled',
711
+ summary: 'Completed'
712
+ });
713
+ return executed;
714
+ }
715
+ catch (error) {
716
+ if (signal.aborted || error === INVOCATION_ABORTED) {
717
+ return createCancelledResult('aborted', evidence, this.redactionOptions);
718
+ }
719
+ const failed = createFailedResult(stableFailure(error, STAGE_FAILURES[currentStage]), evidence, this.redactionOptions);
720
+ emitProgress({
721
+ attempt: evidence.retryCount + 1,
722
+ outcome: 'failed',
723
+ phase: 'settled',
724
+ ...(evidence.batch?.batchId === undefined
725
+ ? {}
726
+ : {
727
+ batchId: evidence.batch.batchId
728
+ }),
729
+ summary: 'Failed'
730
+ });
731
+ return failed;
732
+ }
733
+ }
734
+ }
735
+ export const createAiAgentRuntime = (input) => new DefaultAiAgentRuntime(input);
736
+ //# sourceMappingURL=runtime.js.map