@agentropy/runtime 0.0.0-bootstrap.0 → 0.1.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 (85) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +38 -1
  3. package/dist/a2a-client.d.ts +111 -0
  4. package/dist/a2a-client.js +386 -0
  5. package/dist/a2a-history.d.ts +27 -0
  6. package/dist/a2a-history.js +67 -0
  7. package/dist/a2a-http.d.ts +46 -0
  8. package/dist/a2a-http.js +183 -0
  9. package/dist/a2a-protocol.d.ts +77 -0
  10. package/dist/a2a-protocol.js +148 -0
  11. package/dist/a2a-push-receiver.d.ts +24 -0
  12. package/dist/a2a-push-receiver.js +161 -0
  13. package/dist/a2a-push.d.ts +85 -0
  14. package/dist/a2a-push.js +385 -0
  15. package/dist/a2a-server.d.ts +82 -0
  16. package/dist/a2a-server.js +523 -0
  17. package/dist/a2a-sse.d.ts +5 -0
  18. package/dist/a2a-sse.js +36 -0
  19. package/dist/a2a.d.ts +41 -0
  20. package/dist/a2a.js +40 -0
  21. package/dist/app.d.ts +256 -0
  22. package/dist/app.js +541 -0
  23. package/dist/audit.d.ts +229 -0
  24. package/dist/audit.js +718 -0
  25. package/dist/bounded-body.d.ts +32 -0
  26. package/dist/bounded-body.js +124 -0
  27. package/dist/communication.d.ts +62 -0
  28. package/dist/communication.js +142 -0
  29. package/dist/compaction.d.ts +24 -0
  30. package/dist/compaction.js +202 -0
  31. package/dist/federation.d.ts +108 -0
  32. package/dist/federation.js +241 -0
  33. package/dist/http-path.d.ts +7 -0
  34. package/dist/http-path.js +14 -0
  35. package/dist/human-actions.d.ts +62 -0
  36. package/dist/human-actions.js +359 -0
  37. package/dist/implementation.d.ts +47 -0
  38. package/dist/implementation.js +138 -0
  39. package/dist/inbox.d.ts +101 -0
  40. package/dist/inbox.js +389 -0
  41. package/dist/index.d.ts +32 -0
  42. package/dist/index.js +32 -0
  43. package/dist/ingress.d.ts +35 -0
  44. package/dist/ingress.js +86 -0
  45. package/dist/lifecycle.d.ts +45 -0
  46. package/dist/lifecycle.js +57 -0
  47. package/dist/limits.d.ts +43 -0
  48. package/dist/limits.js +71 -0
  49. package/dist/mcp.d.ts +111 -0
  50. package/dist/mcp.js +308 -0
  51. package/dist/memory.d.ts +25 -0
  52. package/dist/memory.js +134 -0
  53. package/dist/model-routing.d.ts +66 -0
  54. package/dist/model-routing.js +80 -0
  55. package/dist/otel.d.ts +60 -0
  56. package/dist/otel.js +72 -0
  57. package/dist/outbox.d.ts +116 -0
  58. package/dist/outbox.js +327 -0
  59. package/dist/policy-cache.d.ts +69 -0
  60. package/dist/policy-cache.js +178 -0
  61. package/dist/priority.d.ts +27 -0
  62. package/dist/priority.js +28 -0
  63. package/dist/quotas.d.ts +19 -0
  64. package/dist/quotas.js +47 -0
  65. package/dist/reasoning.d.ts +54 -0
  66. package/dist/reasoning.js +307 -0
  67. package/dist/registry.d.ts +101 -0
  68. package/dist/registry.js +369 -0
  69. package/dist/remote.d.ts +130 -0
  70. package/dist/remote.js +473 -0
  71. package/dist/runtime.d.ts +167 -0
  72. package/dist/runtime.js +1035 -0
  73. package/dist/skills.d.ts +86 -0
  74. package/dist/skills.js +376 -0
  75. package/dist/task-service.d.ts +239 -0
  76. package/dist/task-service.js +790 -0
  77. package/dist/tools.d.ts +140 -0
  78. package/dist/tools.js +476 -0
  79. package/dist/wake-index.d.ts +9 -0
  80. package/dist/wake-index.js +11 -0
  81. package/dist/wakeups.d.ts +142 -0
  82. package/dist/wakeups.js +501 -0
  83. package/dist/workflow.d.ts +36 -0
  84. package/dist/workflow.js +101 -0
  85. package/package.json +41 -5
@@ -0,0 +1,1035 @@
1
+ /**
2
+ * AgentRuntime and bounded in-process pool (runtime contract §1–2, ADR-0018): one execution per activation,
3
+ * leases with epochs (fencing), disposition mapping, retries with backoff, cooperative cancel with a grace
4
+ * period, lease-expiry recovery. Wake-up firing (T5) is owned by the scheduler/event layer.
5
+ */
6
+ import { AgentropyError, EXECUTION_MACHINE, nextOccurrence, assertTransition, enforcePolicy, isAgentropyError, normalizeInstant, toAgentropyError, validateAgainst, METRICS, SPANS, } from '@agentropy/core';
7
+ import { randomUUID } from 'node:crypto';
8
+ import { DEFAULT_LIMITS } from './limits.js';
9
+ import { DEFAULT_RETRY, hashKey, } from './task-service.js';
10
+ const EMPTY_SKILLS = {
11
+ list: () => [],
12
+ instructions: async (id) => Promise.reject(new AgentropyError('CapabilityNotDeclared', `Skill ${id} is not pinned`)),
13
+ resource: async (id) => Promise.reject(new AgentropyError('CapabilityNotDeclared', `Skill ${id} is not pinned`)),
14
+ };
15
+ /**
16
+ * Fair dispatch order (M3-02): round-robin across tenants, oldest first within each tenant, so one tenant's backlog
17
+ * cannot starve another's on a shared pool.
18
+ */
19
+ export function fairOrder(due) {
20
+ const queues = new Map();
21
+ for (const e of due) {
22
+ const k = e.value.tenantId ?? '';
23
+ const q = queues.get(k);
24
+ if (q)
25
+ q.push(e);
26
+ else
27
+ queues.set(k, [e]);
28
+ }
29
+ const out = [];
30
+ for (let i = 0; out.length < due.length; i++)
31
+ for (const q of queues.values())
32
+ if (i < q.length)
33
+ out.push(q[i]);
34
+ return out;
35
+ }
36
+ /** Applies the handler's checkpoint codec to a stored checkpoint (FEAT-028.3); never reinterprets silently. */
37
+ export function decodeCheckpoint(codec, data, storedVersion) {
38
+ if (data === undefined)
39
+ return undefined;
40
+ const current = codec?.version ?? 1;
41
+ const stored = storedVersion ?? 1;
42
+ if (stored === current)
43
+ return data;
44
+ const fail = (message) => new AgentropyError('IncompatibleVersion', message, {
45
+ details: { kind: 'checkpoint', stored, current },
46
+ });
47
+ if (stored > current || !codec?.upgrade)
48
+ throw fail(`Checkpoint version ${stored} cannot be read by a handler at version ${current}`);
49
+ try {
50
+ return codec.upgrade(structuredClone(data), stored);
51
+ }
52
+ catch {
53
+ throw fail(`Checkpoint upgrade from version ${stored} failed`);
54
+ }
55
+ }
56
+ /**
57
+ * A grace-period sleep that does not keep the process alive: nothing awaits it except a background fence, so a
58
+ * shutdown must not wait for it (FEAT-037.3).
59
+ */
60
+ const sleepUnref = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref());
61
+ const addMs = (iso, ms) => new Date(Date.parse(iso) + ms).toISOString();
62
+ export class AgentRuntime {
63
+ /** Executions handed over by `handOver`, whose late disposition is dropped. */
64
+ abandoned = new Set();
65
+ running = new Map();
66
+ o;
67
+ constructor(options) {
68
+ this.o = {
69
+ poolSize: 4,
70
+ leaseMs: 60_000,
71
+ cancelGraceMs: 30_000,
72
+ maxActivationMs: 600_000,
73
+ maxOutputBytes: DEFAULT_LIMITS.maxOutputBytes,
74
+ keepExecutions: 20,
75
+ gateRetry: { initialMs: 1_000, maxMs: 300_000, maxAttempts: 8 },
76
+ pdpTimeoutMs: 5_000,
77
+ maxCheckpointBytes: 64 * 1024,
78
+ workerId: `worker-${randomUUID()}`,
79
+ ...options,
80
+ };
81
+ this.o.tasks.onCancelRequested((taskId) => {
82
+ for (const [execId, r] of this.running)
83
+ if (r.taskId === taskId)
84
+ this.guard(this.cancelRunning(execId, r.controller));
85
+ });
86
+ }
87
+ /**
88
+ * Contains a background promise (cancel or timeout fence): its failure is counted and reported, never an
89
+ * unhandled rejection that would end the process and every other execution with it (FEAT-037.2).
90
+ */
91
+ guard(work) {
92
+ work.catch((err) => this.report(err));
93
+ }
94
+ /** Counts and reports a failure the host contains (see `onError`). */
95
+ report(err) {
96
+ const error = toAgentropyError(err);
97
+ this.o.tasks.telemetry.count(METRICS.schedulerErrors, 1, {
98
+ 'agentropy.error.code': error.code,
99
+ });
100
+ try {
101
+ this.o.onError?.(error);
102
+ }
103
+ catch {
104
+ // A failing error hook must not break the pool either.
105
+ }
106
+ }
107
+ get store() {
108
+ return this.o.tasks.o.store;
109
+ }
110
+ now() {
111
+ return this.o.tasks.o.now();
112
+ }
113
+ /** Recover expired leases, then lease due executions up to the free pool capacity. Returns how many started. */
114
+ async tick() {
115
+ await this.renewLeases();
116
+ await this.recoverExpiredLeases();
117
+ await this.o.relay?.drain();
118
+ const free = this.o.poolSize - this.running.size;
119
+ if (free <= 0)
120
+ return 0;
121
+ const now = this.now();
122
+ // Only what is due, from the `runAt` index (a backlog of retries waiting out their backoff costs nothing).
123
+ const due = fairOrder((await this.store.transaction((tx) => tx.find('executions', {
124
+ where: { state: 'queued' },
125
+ range: { field: 'runAt', lte: now },
126
+ limit: 1_000,
127
+ }))).filter((e) => !this.running.has(e.id)));
128
+ // Cheap pre-check so tenants at their concurrency limit are not re-admitted every tick; lease() re-checks.
129
+ const busy = new Map();
130
+ if (this.o.tasks.o.quotas)
131
+ for (const r of await this.store.transaction((tx) => tx.find('executions', { where: { state: 'running' } })))
132
+ if (r.value.tenantId)
133
+ busy.set(r.value.tenantId, (busy.get(r.value.tenantId) ?? 0) + 1);
134
+ let started = 0;
135
+ for (const e of due) {
136
+ if (started >= free)
137
+ break;
138
+ const tenant = e.value.tenantId;
139
+ const cap = tenant !== undefined
140
+ ? this.o.tasks.o.quotas?.(tenant)?.maxConcurrentExecutions
141
+ : undefined;
142
+ if (cap !== undefined && (busy.get(tenant) ?? 0) >= cap)
143
+ continue;
144
+ let leased;
145
+ try {
146
+ const admission = await this.admit(e);
147
+ if (!admission)
148
+ continue;
149
+ leased = await this.lease(e.id, admission);
150
+ }
151
+ catch (err) {
152
+ // A failed audit intent aborts the gate or lease transaction: nothing is dispatched; retried next tick.
153
+ if (isAgentropyError(err, 'AuditCommitUnavailable'))
154
+ continue;
155
+ throw err;
156
+ }
157
+ if (!leased)
158
+ continue;
159
+ if (tenant)
160
+ busy.set(tenant, (busy.get(tenant) ?? 0) + 1);
161
+ const controller = new AbortController();
162
+ let release;
163
+ const done = new Promise((r) => (release = r));
164
+ this.running.set(e.id, {
165
+ done,
166
+ release,
167
+ controller,
168
+ taskId: leased.task.id,
169
+ });
170
+ // An activation that outlives maxActivationMs is aborted, then fenced if it ignores the signal.
171
+ const limit = setTimeout(() => this.guard(this.timeoutRunning(e.id, controller)), this.o.maxActivationMs);
172
+ limit.unref();
173
+ void this.execute(leased.exec, leased.task, controller)
174
+ .catch((err) => this.report(err))
175
+ .finally(() => {
176
+ clearTimeout(limit);
177
+ this.forget(e.id);
178
+ });
179
+ started++;
180
+ }
181
+ return started;
182
+ }
183
+ /**
184
+ * Lease heartbeat (M2-01): extend the lease of every execution this pool is still running, so another worker
185
+ * sharing the store does not recover it as lost while it makes progress. Fenced by state and epoch. Called by
186
+ * every tick and, independently of ticks, by the heartbeat timer of a started app (FIX-051).
187
+ */
188
+ async renewLeases() {
189
+ if (!this.running.size)
190
+ return 0;
191
+ const ids = [...this.running.keys()];
192
+ const cancelled = [];
193
+ const fenced = [];
194
+ const renewed = await this.store.transaction(async (tx) => {
195
+ cancelled.length = fenced.length = 0;
196
+ let n = 0;
197
+ for (const id of ids) {
198
+ const e = await tx.get('executions', id);
199
+ if (!e || e.value.state !== 'running') {
200
+ // Another worker recovered this lease (we stalled past expiry): stop the handler, its result is fenced.
201
+ fenced.push(id);
202
+ continue;
203
+ }
204
+ await tx.update('executions', id, e.revision, {
205
+ ...e.value,
206
+ leaseExpiresAt: addMs(this.now(), this.o.leaseMs),
207
+ });
208
+ n++;
209
+ // A cancel accepted by another worker reaches this one through the store (M3-02).
210
+ const t = await tx.get('tasks', e.value.taskId);
211
+ if (t?.value.cancelRequestedAt)
212
+ cancelled.push(id);
213
+ }
214
+ return n;
215
+ });
216
+ for (const id of fenced)
217
+ this.running
218
+ .get(id)
219
+ ?.controller.abort(new AgentropyError('StaleRevision', 'Execution lease was lost'));
220
+ for (const id of cancelled) {
221
+ const r = this.running.get(id);
222
+ if (r && !r.controller.signal.aborted)
223
+ this.guard(this.cancelRunning(id, r.controller));
224
+ }
225
+ return renewed;
226
+ }
227
+ /** This worker's identity (M3-02). */
228
+ get workerId() {
229
+ return this.o.workerId;
230
+ }
231
+ /**
232
+ * Revocation checkpoint (D-20): signal every execution this pool is running under `grantRef` to stop. The
233
+ * handler sees its AbortSignal fire with `AuthorityExpired` (status revoked); its next protected effect is refused
234
+ * anyway (grants are checked per operation), and the task waits behind the dispatch gate. Committed effects are
235
+ * not rolled back: they stay in the effect journal for authorized compensation. Returns the affected task IDs.
236
+ */
237
+ async revokeAuthority(grantRef, tenantId) {
238
+ const affected = [];
239
+ for (const r of this.running.values()) {
240
+ const t = await this.store.transaction((tx) => tx.get('tasks', r.taskId));
241
+ if (t?.value.grantRef !== grantRef || t.value.tenantId !== tenantId)
242
+ continue;
243
+ r.controller.abort(new AgentropyError('AuthorityExpired', 'Delegated authority revoked', {
244
+ details: { status: 'revoked' },
245
+ }));
246
+ affected.push(t.id);
247
+ }
248
+ return affected;
249
+ }
250
+ /** Wait for every in-flight execution to settle. */
251
+ async idle() {
252
+ while (this.running.size)
253
+ await Promise.all([...this.running.values()].map((r) => r.done));
254
+ }
255
+ /**
256
+ * Hands this worker's running executions over (FEAT-072): signal every handler to stop, expire the leases now so any
257
+ * other worker recovers them at its next tick (E8, then the task's retry policy) instead of after `leaseMs`, and
258
+ * drop them from the pool. What a handler returns after this is discarded. For a worker that is about to exit, once
259
+ * its heartbeat has stopped; returns how many executions were handed over.
260
+ */
261
+ async handOver() {
262
+ const ids = [...this.running.keys()];
263
+ if (!ids.length)
264
+ return 0;
265
+ for (const id of ids) {
266
+ this.abandoned.add(id);
267
+ this.running
268
+ .get(id)
269
+ ?.controller.abort(new AgentropyError('ProviderUnavailable', 'The worker is shutting down'));
270
+ }
271
+ await this.store.transaction(async (tx) => {
272
+ for (const id of ids) {
273
+ const e = await tx.get('executions', id);
274
+ if (e?.value.state === 'running' &&
275
+ e.value.workerId === this.o.workerId)
276
+ await tx.update('executions', e.id, e.revision, {
277
+ ...e.value,
278
+ leaseExpiresAt: this.now(),
279
+ });
280
+ }
281
+ });
282
+ for (const id of ids)
283
+ this.forget(id);
284
+ return ids.length;
285
+ }
286
+ /** Drop an execution from the pool (settled, or fenced after a cancel grace period). */
287
+ forget(executionId) {
288
+ const r = this.running.get(executionId);
289
+ if (!r)
290
+ return;
291
+ this.running.delete(executionId);
292
+ r.release();
293
+ }
294
+ /** Tick and settle until no due work remains (bounded). */
295
+ async runUntilIdle(maxRounds = 100) {
296
+ for (let i = 0; i < maxRounds; i++) {
297
+ const started = await this.tick();
298
+ await this.idle();
299
+ if (started === 0)
300
+ break;
301
+ }
302
+ await this.o.relay?.drain();
303
+ }
304
+ get activeCount() {
305
+ return this.running.size;
306
+ }
307
+ /**
308
+ * ADR-0024 activation eligibility gate, evaluated before every lease with a fresh grant check and policy
309
+ * decision. A blocked task keeps its status (`assigned`) and its queued execution; the gate row records why,
310
+ * and when (if ever) to look again. Deadlines are enforced while gated (T9). Returns undefined when not admitted.
311
+ */
312
+ async admit(e) {
313
+ const now = this.now();
314
+ const [task, gate] = await this.store.transaction(async (tx) => [
315
+ await tx.get('tasks', e.value.taskId),
316
+ await tx.get('gates', e.value.taskId),
317
+ ]);
318
+ if (!task || task.value.status !== 'assigned')
319
+ return undefined;
320
+ if (task.value.deadline && task.value.deadline <= now) {
321
+ await this.store.transaction(async (tx) => {
322
+ const cur = await tx.get('tasks', task.id);
323
+ if (cur && cur.revision === task.revision)
324
+ await this.o.tasks.terminate(tx, cur, 'failed', 'T9', {
325
+ code: 'Timeout',
326
+ message: 'Task deadline passed',
327
+ });
328
+ });
329
+ return undefined;
330
+ }
331
+ // No busy retries: a gate waits for its scheduled check, or for reauthorization when it has none.
332
+ if (gate &&
333
+ (gate.value.nextCheckAt === null || gate.value.nextCheckAt > now))
334
+ return undefined;
335
+ const grantRef = gate?.value.grantRef ?? task.value.grantRef;
336
+ const verdict = await this.dispatchDecision(task.value, grantRef);
337
+ if (verdict === 'allow')
338
+ return {
339
+ taskRevision: task.revision,
340
+ gateRevision: gate?.revision ?? null,
341
+ ...(grantRef ? { grantRef } : {}),
342
+ };
343
+ await this.store.transaction(async (tx) => {
344
+ const t = await tx.get('tasks', task.id);
345
+ const g = await tx.get('gates', task.id);
346
+ // CAS on both the task and the gate: a concurrent scheduler or a cancel wins, this decision is dropped.
347
+ if (!t || t.revision !== task.revision)
348
+ return;
349
+ if ((g?.revision ?? null) !== (gate?.revision ?? null))
350
+ return;
351
+ await this.writeGate(tx, t, g, verdict, grantRef);
352
+ });
353
+ return undefined;
354
+ }
355
+ async writeGate(tx, t, g, reason, grantRef) {
356
+ const now = this.now();
357
+ const attempt = (g?.value.attempt ?? 0) + 1;
358
+ const r = this.o.gateRetry;
359
+ const retry = reason === 'policy-indeterminate' && attempt < r.maxAttempts;
360
+ const value = {
361
+ taskId: t.id,
362
+ taskRevision: t.revision,
363
+ reason,
364
+ nextCheckAt: retry
365
+ ? addMs(now, Math.min(r.maxMs, r.initialMs * 2 ** (attempt - 1)))
366
+ : null,
367
+ ...(grantRef ? { grantRef } : {}),
368
+ lastDecisionAt: now,
369
+ attempt,
370
+ };
371
+ this.o.tasks.telemetry.count(METRICS.dispatchGated, 1, {
372
+ 'agentropy.gate.reason': reason,
373
+ });
374
+ if (g)
375
+ await tx.update('gates', g.id, g.revision, value);
376
+ else
377
+ await tx.insert('gates', t.id, value);
378
+ await this.o.tasks.audit(tx, { id: t.value.callerId, tenantId: t.value.tenantId }, {
379
+ type: 'task.dispatch',
380
+ action: 'task:dispatch',
381
+ resource: { type: 'task', id: t.id },
382
+ decision: reason === 'policy-indeterminate' ? 'error' : 'deny',
383
+ details: { reason, attempt, retry },
384
+ correlationId: t.value.correlationId,
385
+ taskId: t.id,
386
+ });
387
+ }
388
+ /** Fresh grant check and policy decision for dispatching a task; never reuses an earlier Allow. */
389
+ async dispatchDecision(t, grantRef) {
390
+ const grants = this.o.tasks.o.grants;
391
+ if (grantRef && grants) {
392
+ let status;
393
+ try {
394
+ status = await grants.check(grantRef, t.tenantId);
395
+ }
396
+ catch {
397
+ return 'policy-indeterminate';
398
+ }
399
+ if (status === 'expired')
400
+ return 'authority-expired';
401
+ if (status !== 'valid')
402
+ return 'authority-revoked';
403
+ }
404
+ const principal = {
405
+ id: t.callerId,
406
+ type: t.callerType ?? 'user',
407
+ tenantId: t.tenantId,
408
+ ...(grantRef ? { delegatedAuthorityRef: grantRef } : {}),
409
+ };
410
+ const abort = new AbortController();
411
+ let timer;
412
+ try {
413
+ const decision = await Promise.race([
414
+ this.o.tasks.o.pdp.decide({
415
+ principal,
416
+ action: 'task:dispatch',
417
+ resource: {
418
+ type: 'agent-instance',
419
+ id: t.instanceId,
420
+ tenantId: t.tenantId,
421
+ },
422
+ }, abort.signal),
423
+ new Promise((_, reject) => {
424
+ timer = setTimeout(() => {
425
+ abort.abort();
426
+ reject(new Error('policy decision timed out'));
427
+ }, this.o.pdpTimeoutMs);
428
+ }),
429
+ ]);
430
+ const effect = decision?.effect;
431
+ if (effect === 'allow')
432
+ return 'allow';
433
+ if (effect === 'deny')
434
+ return 'policy-denied';
435
+ return 'policy-indeterminate';
436
+ }
437
+ catch {
438
+ return 'policy-indeterminate';
439
+ }
440
+ finally {
441
+ clearTimeout(timer);
442
+ }
443
+ }
444
+ /**
445
+ * Store-wide per-tenant concurrency (M3-02, `maxConcurrentExecutions`): counted inside the lease transaction over
446
+ * every worker's running executions, so workers sharing the store cannot overshoot together.
447
+ */
448
+ async tenantAtCapacity(tx, tenantId) {
449
+ if (!tenantId)
450
+ return false;
451
+ const limit = this.o.tasks.o.quotas?.(tenantId)?.maxConcurrentExecutions;
452
+ if (limit === undefined)
453
+ return false;
454
+ const running = (await tx.find('executions', {
455
+ where: { state: 'running', tenantId },
456
+ })).length;
457
+ return running >= limit;
458
+ }
459
+ /** E2+E3 with T3 in one transaction; the lease epoch fences every later write of this execution. */
460
+ async lease(executionId, admission) {
461
+ return this.store.transaction(async (tx) => {
462
+ const e = await tx.get('executions', executionId);
463
+ if (!e || e.value.state !== 'queued')
464
+ return undefined;
465
+ const t = (await tx.get('tasks', e.value.taskId));
466
+ if (t.value.status !== 'assigned')
467
+ return undefined;
468
+ if (await this.tenantAtCapacity(tx, t.value.tenantId))
469
+ return undefined;
470
+ // Lease fence (ADR-0024): the admission decision is only valid for the task and gate revisions it saw.
471
+ const gate = await tx.get('gates', t.id);
472
+ if (t.revision !== admission.taskRevision ||
473
+ (gate?.revision ?? null) !== admission.gateRevision)
474
+ return undefined;
475
+ if (gate) {
476
+ await tx.remove('gates', gate.id, gate.revision);
477
+ await this.o.tasks.audit(tx, { id: t.value.callerId, tenantId: t.value.tenantId }, {
478
+ type: 'task.dispatch',
479
+ action: 'task:dispatch',
480
+ resource: { type: 'task', id: t.id },
481
+ decision: 'allow',
482
+ details: { after: gate.value.reason, attempts: gate.value.attempt },
483
+ correlationId: t.value.correlationId,
484
+ taskId: t.id,
485
+ });
486
+ }
487
+ const epoch = (t.value.leaseEpoch ?? 0) + 1;
488
+ assertTransition(EXECUTION_MACHINE, 'queued', 'leased', 'E2');
489
+ assertTransition(EXECUTION_MACHINE, 'leased', 'running', 'E3');
490
+ const now = this.now();
491
+ const exec = await tx.update('executions', e.id, e.revision, {
492
+ ...e.value,
493
+ state: 'running',
494
+ leaseEpoch: epoch,
495
+ leaseExpiresAt: addMs(now, this.o.leaseMs),
496
+ startedAt: now,
497
+ tenantId: t.value.tenantId,
498
+ workerId: this.o.workerId,
499
+ });
500
+ const task = await this.o.tasks.transition(tx, t, 'running', 'T3', {
501
+ leaseEpoch: epoch,
502
+ ...(admission.grantRef ? { grantRef: admission.grantRef } : {}),
503
+ });
504
+ return { exec, task };
505
+ });
506
+ }
507
+ async execute(exec, task, controller) {
508
+ const t = task.value;
509
+ const telemetry = this.o.tasks.telemetry;
510
+ const started = performance.now();
511
+ let disposition;
512
+ let span;
513
+ let codecVersion = 1;
514
+ try {
515
+ const provider = this.o.implementations.get(t.snapshot.implementation.providerId, t.snapshot.implementation.providerVersion);
516
+ const agent = provider.createAgent(t.snapshot.implementation);
517
+ const resumed = await this.resumeState(t.taskId, exec.value.trigger);
518
+ const { wakeReason, causeTraceparent } = resumed;
519
+ codecVersion = agent.checkpointCodec?.version ?? 1;
520
+ const checkpoint = decodeCheckpoint(agent.checkpointCodec, resumed.checkpoint, resumed.checkpointVersion);
521
+ span = telemetry.startSpan(SPANS.execute, {
522
+ kind: 'consumer',
523
+ ...(t.traceparent ? { parent: t.traceparent } : {}),
524
+ ...(causeTraceparent ? { links: [causeTraceparent] } : {}),
525
+ attributes: {
526
+ 'agentropy.tenant.id': t.tenantId,
527
+ 'agentropy.task.id': t.taskId,
528
+ 'agentropy.execution.id': exec.id,
529
+ 'agentropy.agent.id': t.snapshot.definition.id,
530
+ 'agentropy.activation': exec.value.activation,
531
+ 'agentropy.attempt': exec.value.attempt,
532
+ 'agentropy.trigger': exec.value.trigger,
533
+ ...(wakeReason ? { 'agentropy.wake.kind': wakeReason.kind } : {}),
534
+ },
535
+ });
536
+ const invocation = {
537
+ taskId: t.taskId,
538
+ executionId: exec.id,
539
+ activation: exec.value.activation,
540
+ attempt: exec.value.attempt,
541
+ input: t.input,
542
+ trigger: exec.value.trigger,
543
+ ...(checkpoint !== undefined ? { checkpoint } : {}),
544
+ ...(wakeReason ? { wakeReason } : {}),
545
+ };
546
+ disposition = await agent.handle(invocation, this.context(t, exec, controller, span.traceparent));
547
+ // Validate a wake-up request before it reaches the transition transaction (invalid → non-retryable failure).
548
+ if (disposition.kind === 'waiting') {
549
+ if (!disposition.wakeup?.anyOf?.length) {
550
+ throw new AgentropyError('SchemaViolation', 'A waiting disposition needs at least one wake-up condition', { details: { reason: 'wakeup' } });
551
+ }
552
+ // Timers and the timeout are compared as strings: only UTC ISO-8601 instants get through (FEAT-038.3).
553
+ disposition = {
554
+ ...disposition,
555
+ wakeup: {
556
+ ...disposition.wakeup,
557
+ anyOf: disposition.wakeup.anyOf.map((c) => c.kind === 'timer'
558
+ ? { ...c, at: normalizeInstant(c.at, 'timer.at') }
559
+ : c),
560
+ ...(disposition.wakeup.timeoutAt !== undefined
561
+ ? {
562
+ timeoutAt: normalizeInstant(disposition.wakeup.timeoutAt, 'timeoutAt'),
563
+ }
564
+ : {}),
565
+ },
566
+ };
567
+ for (const c of disposition.wakeup.anyOf)
568
+ if (c.kind === 'schedule')
569
+ nextOccurrence(c.cron, c.timezone, this.now());
570
+ // Long-lived tasks cycle through activations; their checkpoint must stay bounded (R-37, AC-20).
571
+ const size = Buffer.byteLength(JSON.stringify(disposition.checkpoint ?? null));
572
+ if (size > this.o.maxCheckpointBytes)
573
+ throw new AgentropyError('SchemaViolation', `Checkpoint of ${size} bytes exceeds the ${this.o.maxCheckpointBytes}-byte limit`, {
574
+ details: {
575
+ reason: 'checkpointTooLarge',
576
+ size,
577
+ limit: this.o.maxCheckpointBytes,
578
+ },
579
+ });
580
+ // A human action's dueAt is its only timeout (human-actions.md "Expiry (single mechanism)").
581
+ if (disposition.wakeup.timeoutAt &&
582
+ disposition.wakeup.anyOf.some((c) => c.kind === 'human-action'))
583
+ throw new AgentropyError('SchemaViolation', 'A human-action wait must not set timeoutAt; the request dueAt is its timeout', { details: { reason: 'humanActionTimeout' } });
584
+ }
585
+ }
586
+ catch (err) {
587
+ disposition = {
588
+ kind: 'threw',
589
+ error: toAgentropyError(err, t.correlationId),
590
+ };
591
+ }
592
+ const outcome = disposition.kind === 'threw'
593
+ ? disposition.error.code
594
+ : disposition.kind === 'failed'
595
+ ? disposition.code
596
+ : undefined;
597
+ span?.setAttributes({ 'agentropy.disposition': disposition.kind });
598
+ if (outcome)
599
+ span?.fail(outcome);
600
+ span?.end();
601
+ telemetry.record(METRICS.executionDuration, performance.now() - started, {
602
+ 'agentropy.agent.id': t.snapshot.definition.id,
603
+ 'agentropy.disposition': disposition.kind,
604
+ });
605
+ await this.settle(exec, disposition, codecVersion);
606
+ }
607
+ /**
608
+ * Writes the disposition, retrying a store failure a few times. A fenced (stale-epoch) write is expected after lease
609
+ * loss, cancel grace expiry or a timeout fence: the result is discarded. If the store stays down the failure is
610
+ * reported and the execution is left to lease expiry, which recovers it (E8, then retry or failure) once the
611
+ * store is back; the pool and its other executions carry on (FEAT-037.2).
612
+ */
613
+ async settle(exec, d, codecVersion) {
614
+ // Handed over at shutdown: the execution now belongs to whichever worker recovers its lease.
615
+ if (this.abandoned.delete(exec.id))
616
+ return;
617
+ const attempts = 3;
618
+ for (let attempt = 1;; attempt++) {
619
+ try {
620
+ await this.applyDisposition(exec, d, codecVersion);
621
+ return;
622
+ }
623
+ catch (err) {
624
+ if (isAgentropyError(err, 'StaleRevision'))
625
+ return;
626
+ if (attempt >= attempts)
627
+ return this.report(err);
628
+ await new Promise((r) => setTimeout(r, 50 * attempt));
629
+ }
630
+ }
631
+ }
632
+ async resumeState(taskId, trigger) {
633
+ return this.store.transaction(async (tx) => {
634
+ const cp = await tx.get('checkpoints', taskId);
635
+ const stored = cp
636
+ ? {
637
+ checkpoint: cp.value.data,
638
+ checkpointVersion: cp.value.version ?? 1,
639
+ }
640
+ : {};
641
+ if (trigger !== 'resume')
642
+ return stored;
643
+ const fired = (await tx.find('wakeups', {
644
+ where: { taskId, status: 'fired' },
645
+ })).at(-1);
646
+ return {
647
+ ...stored,
648
+ ...(fired?.value.reason ? { wakeReason: fired.value.reason } : {}),
649
+ ...(fired?.value.causeTraceparent
650
+ ? { causeTraceparent: fired.value.causeTraceparent }
651
+ : {}),
652
+ };
653
+ });
654
+ }
655
+ /** Applies a disposition only if this execution still holds the lease (same epoch, still running). */
656
+ async applyDisposition(exec, d, codecVersion = 1) {
657
+ await this.store.transaction(async (tx) => {
658
+ const e = await tx.get('executions', exec.id);
659
+ const cur = (await tx.get('tasks', exec.value.taskId));
660
+ if (!e ||
661
+ e.value.state !== 'running' ||
662
+ e.value.leaseEpoch !== exec.value.leaseEpoch ||
663
+ cur.value.leaseEpoch !== exec.value.leaseEpoch) {
664
+ throw new AgentropyError('StaleRevision', 'Execution no longer holds the lease', { details: { reason: 'fenced' } });
665
+ }
666
+ const end = (state, edge) => {
667
+ assertTransition(EXECUTION_MACHINE, 'running', state, edge);
668
+ return tx.update('executions', e.id, e.revision, {
669
+ ...e.value,
670
+ state,
671
+ endedAt: this.now(),
672
+ });
673
+ };
674
+ const t = cur.value;
675
+ if (t.cancelRequestedAt) {
676
+ await end('aborted', 'E7b');
677
+ await this.o.tasks.terminate(tx, cur, 'cancelled', 'T11', {
678
+ code: 'Cancelled',
679
+ message: 'cancelled',
680
+ });
681
+ return this.prune(tx, t.taskId);
682
+ }
683
+ if (d.kind === 'completed') {
684
+ const def = this.o.tasks.o.definitions.require(t.definition);
685
+ // An output JSON cannot represent (a BigInt, a cycle) is the handler's mistake like any other bad output: fail
686
+ // once (T8). Left to throw here, the transaction would fail on every try and the handler would run again.
687
+ let outputBytes;
688
+ try {
689
+ outputBytes = Buffer.byteLength(JSON.stringify(d.output ?? null));
690
+ }
691
+ catch {
692
+ await end('failed', 'E6');
693
+ await this.o.tasks.terminate(tx, cur, 'failed', 'T8', {
694
+ code: 'SchemaViolation',
695
+ message: 'Output cannot be serialized as JSON',
696
+ });
697
+ return this.prune(tx, t.taskId);
698
+ }
699
+ try {
700
+ if (def.outputSchema !== undefined)
701
+ validateAgainst(def.outputSchema, d.output, `${def.id} output`);
702
+ }
703
+ catch {
704
+ await end('failed', 'E6');
705
+ await this.o.tasks.terminate(tx, cur, 'failed', 'T8', {
706
+ code: 'SchemaViolation',
707
+ message: 'Output does not match outputSchema',
708
+ });
709
+ return this.prune(tx, t.taskId);
710
+ }
711
+ if (outputBytes > this.o.maxOutputBytes) {
712
+ await end('failed', 'E6');
713
+ await this.o.tasks.terminate(tx, cur, 'failed', 'T8', {
714
+ code: 'SchemaViolation',
715
+ message: `Output exceeds the ${this.o.maxOutputBytes}-byte limit`,
716
+ });
717
+ return this.prune(tx, t.taskId);
718
+ }
719
+ await end('succeeded', 'E4');
720
+ await this.o.tasks.terminate(tx, cur, 'completed', 'T7', undefined, d.output);
721
+ return this.prune(tx, t.taskId);
722
+ }
723
+ if (d.kind === 'waiting') {
724
+ await end('yielded', 'E5');
725
+ // T4: checkpoint and wake-up registration commit together, before the lease is released.
726
+ const cp = await tx.get('checkpoints', t.taskId);
727
+ if (cp)
728
+ await tx.update('checkpoints', t.taskId, cp.revision, {
729
+ taskId: t.taskId,
730
+ data: d.checkpoint,
731
+ version: codecVersion,
732
+ });
733
+ else
734
+ await tx.insert('checkpoints', t.taskId, {
735
+ taskId: t.taskId,
736
+ data: d.checkpoint,
737
+ version: codecVersion,
738
+ });
739
+ for (const old of await tx.find('wakeups', {
740
+ where: { taskId: t.taskId, status: 'fired' },
741
+ })) {
742
+ await tx.update('wakeups', old.id, old.revision, {
743
+ ...old.value,
744
+ status: 'revoked',
745
+ });
746
+ }
747
+ // Per-condition due times: timers fire at `at`, schedules at their next occurrence (re-registered each activation).
748
+ const conditionDue = d.wakeup.anyOf.map((c) => c.kind === 'timer'
749
+ ? c.at
750
+ : c.kind === 'schedule'
751
+ ? nextOccurrence(c.cron, c.timezone, this.now())
752
+ : null);
753
+ // The task's own deadline is a due time too: a waiting task past it fails with T9 (FEAT-038.1).
754
+ const times = [
755
+ ...conditionDue.filter((x) => x !== null),
756
+ ...(d.wakeup.timeoutAt ? [d.wakeup.timeoutAt] : []),
757
+ ...(t.deadline ? [t.deadline] : []),
758
+ ].sort();
759
+ const id = this.o.tasks.newId('wakeup');
760
+ await tx.insert('wakeups', id, {
761
+ id,
762
+ taskId: t.taskId,
763
+ conditions: d.wakeup.anyOf,
764
+ conditionDue,
765
+ ...(d.wakeup.timeoutAt ? { timeoutAt: d.wakeup.timeoutAt } : {}),
766
+ onTimeout: d.wakeup.onTimeout ?? 'resume',
767
+ status: 'armed',
768
+ dueAt: times[0] ?? null,
769
+ // Non-time conditions may already hold (an event in the mailbox, a finished child): check once now.
770
+ checkAt: conditionDue.includes(null)
771
+ ? this.now()
772
+ : (times[0] ?? null),
773
+ });
774
+ await this.o.tasks.transition(tx, cur, 'waiting', 'T4', {
775
+ waitingOn: d.wakeup,
776
+ });
777
+ return this.prune(tx, t.taskId);
778
+ }
779
+ // Lost authority or an unavailable policy decision at a protected effect is not a handler failure:
780
+ // the task goes back to `assigned` behind the dispatch gate (T6), keeping its checkpoint and journal.
781
+ if (d.kind === 'threw' &&
782
+ (d.error.code === 'AuthorityExpired' ||
783
+ d.error.code === 'PolicyDecisionUnavailable')) {
784
+ await end('failed', 'E6');
785
+ const next = await this.o.tasks.transition(tx, cur, 'assigned', 'T6');
786
+ await this.o.tasks.queueExecution(tx, t.taskId, t.activation, t.attempt, 'retry', this.now());
787
+ const status = d.error.details?.['status'];
788
+ await this.writeGate(tx, next, await tx.get('gates', t.taskId), d.error.code === 'PolicyDecisionUnavailable'
789
+ ? 'policy-indeterminate'
790
+ : status === 'revoked'
791
+ ? 'authority-revoked'
792
+ : 'authority-expired', t.grantRef);
793
+ return this.prune(tx, t.taskId);
794
+ }
795
+ const failure = d.kind === 'threw'
796
+ ? {
797
+ code: d.error.code,
798
+ message: d.error.message,
799
+ retryable: d.error.code === 'Internal' ? true : d.error.retryable,
800
+ }
801
+ : { code: d.code, message: d.message, retryable: d.retryable };
802
+ await end('failed', 'E6');
803
+ const policy = t.retryPolicy ?? DEFAULT_RETRY;
804
+ if (failure.retryable && t.attempt < policy.maxAttempts) {
805
+ const delay = Math.min(policy.backoff.maxMs, policy.backoff.initialMs *
806
+ policy.backoff.multiplier ** (t.attempt - 1));
807
+ const next = await this.o.tasks.transition(tx, cur, 'assigned', 'T6', {
808
+ attempt: t.attempt + 1,
809
+ });
810
+ await this.o.tasks.queueExecution(tx, t.taskId, t.activation, next.value.attempt, 'retry', addMs(this.now(), delay));
811
+ }
812
+ else {
813
+ await this.o.tasks.terminate(tx, cur, 'failed', 'T8', {
814
+ code: failure.code,
815
+ message: failure.message,
816
+ });
817
+ }
818
+ return this.prune(tx, t.taskId);
819
+ });
820
+ }
821
+ /** E8 for executions whose lease expired (crashed worker); the task retries (T6) or fails (T8). */
822
+ async recoverExpiredLeases() {
823
+ const now = this.now();
824
+ return this.store.transaction(async (tx) => {
825
+ let recovered = 0;
826
+ for (const state of ['leased', 'running']) {
827
+ for (const e of await tx.find('executions', {
828
+ where: { state },
829
+ })) {
830
+ if (!e.value.leaseExpiresAt ||
831
+ e.value.leaseExpiresAt > now ||
832
+ this.running.has(e.id))
833
+ continue;
834
+ assertTransition(EXECUTION_MACHINE, state, 'lost', 'E8');
835
+ await tx.update('executions', e.id, e.revision, {
836
+ ...e.value,
837
+ state: 'lost',
838
+ endedAt: now,
839
+ });
840
+ const cur = (await tx.get('tasks', e.value.taskId));
841
+ if (cur.value.status !== 'running')
842
+ continue;
843
+ recovered++;
844
+ if (cur.value.cancelRequestedAt) {
845
+ await this.o.tasks.terminate(tx, cur, 'cancelled', 'T11', {
846
+ code: 'Cancelled',
847
+ message: 'cancelled',
848
+ });
849
+ }
850
+ else if (cur.value.attempt <
851
+ (cur.value.retryPolicy ?? DEFAULT_RETRY).maxAttempts) {
852
+ const next = await this.o.tasks.transition(tx, cur, 'assigned', 'T6', { attempt: cur.value.attempt + 1 });
853
+ await this.o.tasks.queueExecution(tx, cur.id, cur.value.activation, next.value.attempt, 'retry', now);
854
+ }
855
+ else {
856
+ await this.o.tasks.terminate(tx, cur, 'failed', 'T8', {
857
+ code: 'Internal',
858
+ message: 'Lease lost and attempts exhausted',
859
+ });
860
+ }
861
+ }
862
+ }
863
+ return recovered;
864
+ });
865
+ }
866
+ /**
867
+ * maxActivationMs elapsed (FEAT-037.2): abort the handler with `Timeout`; if it has not returned after the grace
868
+ * period, fence it as a lost lease — its lease is set to expire now and the next recovery applies E8 and the
869
+ * task's retry policy (T6, or T8 when attempts are exhausted). Its late result is discarded by the fence.
870
+ */
871
+ async timeoutRunning(executionId, controller) {
872
+ if (controller.signal.aborted)
873
+ return;
874
+ controller.abort(new AgentropyError('Timeout', 'Activation exceeded maxActivationMs'));
875
+ await sleepUnref(this.o.cancelGraceMs);
876
+ if (!this.running.has(executionId))
877
+ return;
878
+ await this.store.transaction(async (tx) => {
879
+ const e = await tx.get('executions', executionId);
880
+ if (e?.value.state === 'running')
881
+ await tx.update('executions', e.id, e.revision, {
882
+ ...e.value,
883
+ leaseExpiresAt: this.now(),
884
+ });
885
+ });
886
+ this.forget(executionId);
887
+ await this.recoverExpiredLeases();
888
+ }
889
+ /** Cooperative cancel: fire AbortSignal; if the handler has not returned after the grace period, fence it (E8 + T11). */
890
+ async cancelRunning(executionId, controller) {
891
+ controller.abort(new AgentropyError('TaskCancelled', 'Task cancellation requested'));
892
+ await sleepUnref(this.o.cancelGraceMs);
893
+ if (!this.running.has(executionId))
894
+ return;
895
+ await this.store.transaction(async (tx) => {
896
+ const e = await tx.get('executions', executionId);
897
+ if (!e || e.value.state !== 'running')
898
+ return;
899
+ assertTransition(EXECUTION_MACHINE, 'running', 'lost', 'E8');
900
+ await tx.update('executions', e.id, e.revision, {
901
+ ...e.value,
902
+ state: 'lost',
903
+ endedAt: this.now(),
904
+ });
905
+ const cur = (await tx.get('tasks', e.value.taskId));
906
+ if (cur.value.status === 'running')
907
+ await this.o.tasks.terminate(tx, cur, 'cancelled', 'T11', {
908
+ code: 'Cancelled',
909
+ message: 'cancel grace period expired',
910
+ });
911
+ });
912
+ this.forget(executionId); // the late result, if any, is fenced by applyDisposition
913
+ }
914
+ /** Keep only the last N terminal executions of a task (R-37). */
915
+ async prune(tx, taskId) {
916
+ const terminal = (await tx.find('executions', { where: { taskId } })).filter((e) => !['queued', 'leased', 'running'].includes(e.value.state));
917
+ for (const e of terminal.slice(0, Math.max(0, terminal.length - this.o.keepExecutions)))
918
+ await tx.remove('executions', e.id, e.revision);
919
+ }
920
+ context(t, exec, controller, traceparent) {
921
+ const principal = {
922
+ id: t.instanceId,
923
+ type: 'agent',
924
+ tenantId: t.tenantId,
925
+ ...(t.grantRef ? { delegatedAuthorityRef: t.grantRef } : {}),
926
+ };
927
+ return {
928
+ tenantId: t.tenantId,
929
+ agentInstanceId: t.instanceId,
930
+ taskId: t.taskId,
931
+ executionId: exec.id,
932
+ principal,
933
+ correlationId: t.correlationId,
934
+ ...(t.deadline ? { deadline: t.deadline } : {}),
935
+ signal: controller.signal,
936
+ capabilities: this.capabilityAccess(t, exec.id, principal, controller.signal, traceparent),
937
+ progress: {
938
+ report: async (p) => {
939
+ await this.store.transaction(async (tx) => {
940
+ const cur = (await tx.get('tasks', t.taskId));
941
+ await this.o.tasks.emit(tx, cur.value, cur.revision, 'agentProgressUpdated', p);
942
+ });
943
+ },
944
+ },
945
+ skills: this.o.skills?.(t) ?? EMPTY_SKILLS,
946
+ };
947
+ }
948
+ /** The only handler effect surface: pinned bindings, declared operations, step keys, fresh authorization. */
949
+ capabilityAccess(t, executionId, principal, signal, traceparent) {
950
+ const telemetry = this.o.tasks.telemetry;
951
+ const traced = async (capabilityId, operation, run) => {
952
+ const span = telemetry.startSpan(SPANS.capability, {
953
+ kind: 'client',
954
+ ...(traceparent ? { parent: traceparent } : {}),
955
+ attributes: {
956
+ 'agentropy.task.id': t.taskId,
957
+ 'agentropy.capability.id': capabilityId,
958
+ 'agentropy.capability.operation': operation,
959
+ },
960
+ });
961
+ let result = 'ok';
962
+ try {
963
+ return await run(span);
964
+ }
965
+ catch (err) {
966
+ result = err.code ?? 'Internal';
967
+ span.fail(result);
968
+ throw err;
969
+ }
970
+ finally {
971
+ span.end();
972
+ telemetry.count(METRICS.capabilityCalls, 1, {
973
+ 'agentropy.capability.id': capabilityId,
974
+ 'agentropy.capability.operation': operation,
975
+ 'agentropy.result': result,
976
+ });
977
+ }
978
+ };
979
+ return {
980
+ invoke: (capabilityId, operation, input, options = {}) => traced(capabilityId, operation, async (span) => {
981
+ const binding = t.snapshot.bindings.find((b) => b.id === capabilityId);
982
+ if (!binding)
983
+ throw new AgentropyError('CapabilityNotDeclared', `Capability ${capabilityId} is not in this task's snapshot`, { details: { id: capabilityId } });
984
+ const contract = this.o.tasks.o.acceptance.contracts.find((c) => c.id === binding.id && c.version === binding.version);
985
+ const op = contract?.operations.find((x) => x.name === operation);
986
+ if (!op)
987
+ throw new AgentropyError('UnsupportedOperation', `${capabilityId}.${operation} is not declared`, { details: { id: capabilityId, operation } });
988
+ if (op.effect === 'external' && !options.stepKey)
989
+ throw new AgentropyError('SchemaViolation', `${capabilityId}.${operation} requires a stepKey`, { details: { reason: 'missingStepKey' } });
990
+ // SEC-02: every protected (non-read) effect re-validates the delegated grant; no stale Allow.
991
+ if (op.effect !== 'read' && t.grantRef && this.o.tasks.o.grants) {
992
+ const status = await this.o.tasks.o.grants
993
+ .check(t.grantRef, t.tenantId)
994
+ .catch(() => {
995
+ throw new AgentropyError('PolicyDecisionUnavailable', 'Grant status unavailable');
996
+ });
997
+ if (status !== 'valid')
998
+ throw new AgentropyError('AuthorityExpired', `Delegated authority ${status}`, { details: { status } });
999
+ }
1000
+ await enforcePolicy(this.o.tasks.o.pdp, {
1001
+ principal,
1002
+ action: op.permission,
1003
+ resource: {
1004
+ type: 'capability',
1005
+ id: capabilityId,
1006
+ tenantId: t.tenantId,
1007
+ },
1008
+ }, signal);
1009
+ // The operation's declared input, before the provider sees it (FEAT-071): a malformed input fails the call
1010
+ // with a SchemaViolation, which is not retried.
1011
+ validateAgainst(op.inputSchema, input, `${capabilityId}.${operation} input`);
1012
+ const provider = this.o.capabilityProviders.get(binding.providerId);
1013
+ if (!provider)
1014
+ throw new AgentropyError('ProviderUnavailable', `Capability provider ${binding.providerId} is not available`, { details: { id: capabilityId } });
1015
+ return provider.invoke(operation, input, {
1016
+ tenantId: t.tenantId,
1017
+ taskId: t.taskId,
1018
+ executionId,
1019
+ principalId: principal.id,
1020
+ ...(principal.delegatedAuthorityRef
1021
+ ? { delegatedAuthorityRef: principal.delegatedAuthorityRef }
1022
+ : {}),
1023
+ ...(options.stepKey
1024
+ ? {
1025
+ stepKey: options.stepKey,
1026
+ idempotencyKey: hashKey(t.tenantId, t.taskId, capabilityId, operation, options.stepKey),
1027
+ }
1028
+ : {}),
1029
+ ...(span.traceparent ? { traceparent: span.traceparent } : {}),
1030
+ signal,
1031
+ });
1032
+ }),
1033
+ };
1034
+ }
1035
+ }