@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
package/dist/remote.js ADDED
@@ -0,0 +1,473 @@
1
+ /**
2
+ * Remote delegation (FEAT-027.9, Communication v1 "Only for remote targets … call the router"): a delegation whose
3
+ * target is `{ remote: { endpoint, definitionId } }` goes through the CommunicationRouter to the selected provider
4
+ * (A2A, a custom broker provider, …). Locally the runtime keeps a *projection* of the remote task — the remote side
5
+ * stays authoritative — and refreshes it on every scheduler poll, so a parent waiting on `child-tasks` wakes when
6
+ * the remote task finishes.
7
+ *
8
+ * Checks before anything leaves the process: authentication, delegated-authority status, the same
9
+ * `delegation:delegate` policy action as local delegation (resource type `remote-agent`), and route selection
10
+ * (tenant boundary, required guarantees). The remote call is idempotent by the delegation's idempotency key, so a
11
+ * crash between the remote acceptance and the local projection write is repaired by retrying the same step.
12
+ *
13
+ * Every call to the peer (delegate, getTask, cancel) is bounded by `timeoutMs` (FIX-053): the provider gets an
14
+ * AbortSignal that fires at the limit, and a provider that ignores it is given up on all the same, so a peer that
15
+ * accepts the connection and never answers costs one `RemoteUnavailable` and never holds the caller.
16
+ */
17
+ import { AgentropyError, enforcePolicy, isTerminal, TASK_MACHINE, } from '@agentropy/core';
18
+ import { DEFAULT_LIMITS } from './limits.js';
19
+ import { hashKey } from './task-service.js';
20
+ import { pokeWakeups } from './wake-index.js';
21
+ /** How long a peer may keep answering `NotFound` to the status poll of a remote task before it fails (FIX-087). */
22
+ export const DEFAULT_REMOTE_NOT_FOUND_MS = 24 * 3_600_000;
23
+ /** Longest one call to a peer may take unless configured otherwise. */
24
+ export const DEFAULT_REMOTE_TIMEOUT_MS = 30_000;
25
+ /** Projections refreshed at once by one `sync`. */
26
+ const SYNC_CONCURRENCY = 8;
27
+ /** Statuses of a projection that still needs refreshing. */
28
+ const OPEN = ['created', 'assigned', 'running', 'waiting'];
29
+ export class RemoteDelegationService {
30
+ o;
31
+ constructor(o) {
32
+ this.o = o;
33
+ const ms = o.timeoutMs;
34
+ if (ms !== undefined && (!Number.isInteger(ms) || ms < 1))
35
+ throw new AgentropyError('InvalidConfiguration', 'communication.timeoutMs must be a positive integer', { details: { field: 'timeoutMs', value: String(ms) } });
36
+ const nf = o.sync?.notFoundMs;
37
+ if (nf !== undefined && (!Number.isSafeInteger(nf) || nf < 0))
38
+ throw new AgentropyError('InvalidConfiguration', 'communication.sync.notFoundMs must be a non-negative integer', { details: { field: 'sync.notFoundMs', value: String(nf) } });
39
+ }
40
+ /**
41
+ * Runs one call to a peer within `timeoutMs`. The provider's context carries a signal that fires at the limit (and
42
+ * when the caller's own signal fires); the call is also raced against the limit, so a provider that ignores the
43
+ * signal cannot hold the caller. What the abandoned call does later is contained.
44
+ */
45
+ async bounded(ctx, call) {
46
+ const abort = new AbortController();
47
+ const onCallerAbort = () => abort.abort(ctx.signal?.reason);
48
+ if (ctx.signal?.aborted)
49
+ onCallerAbort();
50
+ else
51
+ ctx.signal?.addEventListener('abort', onCallerAbort, { once: true });
52
+ let timer;
53
+ const limit = new Promise((_, reject) => {
54
+ timer = setTimeout(() => {
55
+ const timedOut = new AgentropyError('RemoteUnavailable', 'The remote peer did not answer in time', { details: { reason: 'timeout' } });
56
+ abort.abort(timedOut);
57
+ reject(timedOut);
58
+ }, this.o.timeoutMs ?? DEFAULT_REMOTE_TIMEOUT_MS);
59
+ });
60
+ const running = call({ ...ctx, signal: abort.signal });
61
+ running.catch(() => undefined); // a call given up on may still fail later: nobody is waiting for it
62
+ try {
63
+ return await Promise.race([running, limit]);
64
+ }
65
+ finally {
66
+ clearTimeout(timer);
67
+ ctx.signal?.removeEventListener('abort', onCallerAbort);
68
+ }
69
+ }
70
+ /** Next refresh time after a poll that saw `quiet` quiet polls in a row (FEAT-039.2). */
71
+ due(quiet) {
72
+ const min = this.o.sync?.minMs ?? 1_000;
73
+ const max = this.o.sync?.maxMs ?? 30_000;
74
+ if (max <= 0)
75
+ return undefined; // backoff off: refreshed on every poll
76
+ const wait = Math.min(max, min * 2 ** Math.min(quiet, 20));
77
+ return new Date(Date.parse(this.now()) + wait).toISOString();
78
+ }
79
+ get store() {
80
+ return this.o.tasks.o.store;
81
+ }
82
+ now() {
83
+ return this.o.tasks.o.now();
84
+ }
85
+ async delegate(request, caller) {
86
+ if (!caller?.id || !caller.tenantId)
87
+ throw new AgentropyError('Unauthenticated', 'No trusted principal');
88
+ const remote = request.target.remote;
89
+ if (!remote ||
90
+ typeof remote.endpoint !== 'string' ||
91
+ !remote.endpoint ||
92
+ typeof remote.definitionId !== 'string')
93
+ throw new AgentropyError('SchemaViolation', 'target.remote needs endpoint and definitionId');
94
+ if (!request.idempotencyKey)
95
+ throw new AgentropyError('SchemaViolation', 'idempotencyKey required');
96
+ await this.o.tasks.checkGrant(caller);
97
+ const docId = `remote:${hashKey(caller.tenantId, caller.id, request.idempotencyKey)}`;
98
+ const fingerprint = hashKey(JSON.stringify([remote, request.input ?? null]));
99
+ const existing = await this.store.transaction((tx) => tx.get('remoteTasks', docId));
100
+ if (existing)
101
+ return this.replay(existing.value, fingerprint);
102
+ await enforcePolicy(this.o.tasks.o.pdp, {
103
+ principal: caller,
104
+ action: 'delegation:delegate',
105
+ resource: {
106
+ type: 'remote-agent',
107
+ id: remote.endpoint,
108
+ tenantId: caller.tenantId,
109
+ },
110
+ });
111
+ const ctx = {
112
+ caller,
113
+ correlationId: request.correlationId,
114
+ ...(request.deadline ? { deadline: request.deadline } : {}),
115
+ };
116
+ const route = await this.o.router.selectRoute({
117
+ definitionId: remote.definitionId,
118
+ ...(remote.version ? { version: remote.version } : {}),
119
+ tenantId: caller.tenantId,
120
+ endpoint: remote.endpoint,
121
+ }, 'delegate', ctx);
122
+ // Never forward local authority: the provider authenticates as this runtime.
123
+ const { delegatedAuthorityRef: _g, ...withoutGrant } = caller;
124
+ void _g;
125
+ const ref = await this.bounded({ ...ctx, caller: withoutGrant }, (c) => this.o.router.provider(route).delegate(route, {
126
+ target: {},
127
+ input: request.input,
128
+ idempotencyKey: request.idempotencyKey,
129
+ correlationId: request.correlationId,
130
+ ...(request.deadline ? { deadline: request.deadline } : {}),
131
+ }, c));
132
+ const now = this.now();
133
+ const record = {
134
+ taskId: ref.localTaskId,
135
+ tenantId: caller.tenantId,
136
+ callerId: caller.id,
137
+ callerType: caller.type,
138
+ ...(request.parentTaskId ? { parentTaskId: request.parentTaskId } : {}),
139
+ correlationId: request.correlationId,
140
+ idempotencyKey: request.idempotencyKey,
141
+ fingerprint,
142
+ definition: {
143
+ id: remote.definitionId,
144
+ version: remote.version ?? 'remote',
145
+ },
146
+ route,
147
+ remoteTaskId: ref.remoteTaskId,
148
+ status: 'created',
149
+ remoteState: 'accepted',
150
+ revision: 1,
151
+ observedAt: now,
152
+ createdAt: now,
153
+ };
154
+ const stored = await this.store.transaction(async (tx) => {
155
+ const raced = await tx.get('remoteTasks', docId);
156
+ if (raced)
157
+ return raced.value;
158
+ // The peer has accepted the task by now, so it cannot be refused: a parent that ended while the peer was being
159
+ // called (FEAT-070 never saw this child) gets it stored already marked for cancellation, and the next sync
160
+ // cancels it at the peer (FIX-081).
161
+ if (request.parentTaskId) {
162
+ const parent = await tx.get('tasks', request.parentTaskId);
163
+ if (parent && isTerminal(TASK_MACHINE, parent.value.status)) {
164
+ record.cancelRequestedAt = now;
165
+ record.nextSyncAt = now;
166
+ }
167
+ }
168
+ await tx.insert('remoteTasks', docId, record);
169
+ await this.o.tasks.audit(tx, caller, {
170
+ type: 'task.delegate.remote',
171
+ action: 'delegation:delegate',
172
+ resource: { type: 'remote-agent', id: remote.endpoint },
173
+ decision: 'allow',
174
+ correlationId: request.correlationId,
175
+ taskId: record.taskId,
176
+ details: {
177
+ provider: route.providerId,
178
+ protocol: route.protocol,
179
+ ...(request.parentTaskId
180
+ ? { parentTaskId: request.parentTaskId }
181
+ : {}),
182
+ },
183
+ });
184
+ return record;
185
+ });
186
+ return this.handle(stored);
187
+ }
188
+ replay(r, fingerprint) {
189
+ if (r.fingerprint !== fingerprint)
190
+ throw new AgentropyError('IdempotencyConflict', 'Idempotency key reused with a different request');
191
+ return this.handle(r);
192
+ }
193
+ handle(r) {
194
+ return {
195
+ taskId: r.taskId,
196
+ agentInstanceId: r.route.target.endpoint ?? r.definition.id,
197
+ status: 'created',
198
+ definition: r.definition,
199
+ // The remote side decides durability; Agentropy promises nothing beyond its own projection.
200
+ durability: 'none',
201
+ };
202
+ }
203
+ async find(taskId) {
204
+ const rows = await this.store.transaction((tx) => tx.find('remoteTasks', { where: { taskId } }));
205
+ return rows[0];
206
+ }
207
+ /**
208
+ * The projection, visible to its delegator, to whoever can see the parent task (owner or delegator of the
209
+ * parent), and to trusted services of the tenant — the same visibility a local child task has.
210
+ */
211
+ async get(taskId, caller) {
212
+ const doc = await this.find(taskId);
213
+ const r = doc?.value;
214
+ if (!r || r.tenantId !== caller?.tenantId)
215
+ throw new AgentropyError('NotFound', 'Task not found');
216
+ if (r.callerId === caller.id || caller.type === 'service')
217
+ return r;
218
+ if (r.parentTaskId) {
219
+ const parent = await this.store.transaction((tx) => tx.get('tasks', r.parentTaskId));
220
+ if (parent &&
221
+ (parent.value.ownerId === caller.id ||
222
+ parent.value.callerId === caller.id))
223
+ return r;
224
+ }
225
+ throw new AgentropyError('NotFound', 'Task not found');
226
+ }
227
+ snapshot(r) {
228
+ return {
229
+ taskId: r.taskId,
230
+ status: r.status,
231
+ revision: r.revision,
232
+ authority: 'remote',
233
+ ...(r.outcome ? { outcome: r.outcome } : {}),
234
+ };
235
+ }
236
+ async cancel(taskId, caller) {
237
+ const r = await this.get(taskId, caller);
238
+ if (isTerminal(TASK_MACHINE, r.status))
239
+ throw new AgentropyError('InvalidState', `Task is ${r.status}`);
240
+ const state = await this.bounded({ caller, correlationId: r.correlationId }, (c) => this.o.router.provider(r.route).cancel(this.ref(r), c));
241
+ return this.snapshot(await this.apply(r.taskId, state.normalized, state.remoteState, state.output));
242
+ }
243
+ /**
244
+ * Refresh the non-terminal projections that are due from their providers (called on each scheduler poll). A
245
+ * projection that keeps showing nothing new, or whose peer is down, is asked less and less often (doubling from
246
+ * `sync.minMs` up to `sync.maxMs`), so open remote tasks do not become a request every poll (FEAT-039.2).
247
+ */
248
+ async sync() {
249
+ const now = this.now();
250
+ const open = (await this.store.transaction(async (tx) => {
251
+ const rows = [];
252
+ for (const status of OPEN)
253
+ rows.push(...(await tx.find('remoteTasks', {
254
+ where: { status },
255
+ })));
256
+ return rows;
257
+ })).filter((d) => !d.value.nextSyncAt || d.value.nextSyncAt <= now);
258
+ // A few at a time: peers that hang each cost their own timeout, not one after the other (FIX-053).
259
+ let changed = 0;
260
+ let next = 0;
261
+ await Promise.all(Array.from({ length: Math.min(SYNC_CONCURRENCY, open.length) }, async () => {
262
+ for (let doc = open[next++]; doc; doc = open[next++])
263
+ if (await this.poll(doc))
264
+ changed++;
265
+ }));
266
+ return changed;
267
+ }
268
+ /** One poll of a projection: true when the peer's answer changed it; otherwise its next poll is pushed back. */
269
+ async poll(doc) {
270
+ const r = doc.value;
271
+ const ctx = {
272
+ caller: {
273
+ id: r.callerId,
274
+ type: r.callerType,
275
+ tenantId: r.tenantId,
276
+ },
277
+ correlationId: r.correlationId,
278
+ };
279
+ // Looked up inside each call: a pinned route that is no longer available fails this poll, not the whole sync.
280
+ const provider = () => this.o.router.provider(r.route);
281
+ const getTask = () => this.bounded(ctx, (c) => provider().getTask(this.ref(r), c));
282
+ try {
283
+ let state;
284
+ try {
285
+ state = r.cancelRequestedAt
286
+ ? await this.bounded(ctx, (c) => provider().cancel(this.ref(r), c))
287
+ : await getTask();
288
+ }
289
+ catch (err) {
290
+ // A cancel the peer refuses is an answer, not an outage (FIX-080): the task already ended there (A2A
291
+ // TaskNotCancelable is `InvalidState`) or the peer cannot cancel (`UnsupportedOperation`), so its state is
292
+ // read in the same poll and applied.
293
+ const code = err.code;
294
+ if (!r.cancelRequestedAt ||
295
+ (code !== 'InvalidState' && code !== 'UnsupportedOperation'))
296
+ throw err;
297
+ state = await getTask();
298
+ }
299
+ // Any answer but NotFound ends a run of NotFound answers (FIX-087).
300
+ if (r.notFoundSince)
301
+ await this.forgetNotFound(doc.id);
302
+ const before = r.revision;
303
+ const after = await this.apply(r.taskId, state.normalized, state.remoteState, state.output);
304
+ if (after.revision !== before)
305
+ return true;
306
+ await this.schedule(doc.id, (r.quiet ?? 0) + 1);
307
+ return false;
308
+ }
309
+ catch (err) {
310
+ const code = err.code ?? 'Internal';
311
+ // A peer that keeps answering NotFound to the status poll (FIX-087): it may be brief (a restore, a misrouted
312
+ // request), so the projection fails only once the answers have lasted `sync.notFoundMs` (default 24 h), counted
313
+ // from the first of them.
314
+ if (!r.cancelRequestedAt && code === 'NotFound') {
315
+ const now = this.now();
316
+ const since = r.notFoundSince ?? now;
317
+ const window = this.o.sync?.notFoundMs ?? DEFAULT_REMOTE_NOT_FOUND_MS;
318
+ if (Date.parse(now) - Date.parse(since) >= window) {
319
+ await this.apply(r.taskId, 'failed', 'not-found', undefined, {
320
+ code: 'NotFound',
321
+ message: 'Remote task not found at the peer',
322
+ });
323
+ return true;
324
+ }
325
+ await this.schedule(doc.id, (r.quiet ?? 0) + 1, code, since);
326
+ return false;
327
+ }
328
+ // A projection whose cancel was requested and whose peer no longer knows the task (`NotFound`, on the cancel or
329
+ // on the read after a refused cancel) can never settle from the peer: it fails with `NotFound` (FIX-080).
330
+ if (r.cancelRequestedAt && code === 'NotFound') {
331
+ await this.apply(r.taskId, 'failed', 'not-found', undefined, {
332
+ code: 'NotFound',
333
+ message: 'Remote task not found at the peer',
334
+ });
335
+ return true;
336
+ }
337
+ // The remote task stays authoritative: an unreachable peer leaves the projection as last observed.
338
+ await this.schedule(doc.id, (r.quiet ?? 0) + 1, code);
339
+ return false;
340
+ }
341
+ }
342
+ refreshing = new Map();
343
+ /**
344
+ * Asks the peer for one open projection now, outside the poll schedule (FEAT-048.2: the A2A push notification
345
+ * receiver calls this). True when the projection changed; false when it did not, is terminal, does not exist or the
346
+ * peer could not be reached (recorded like a failed poll). Concurrent refreshes of one projection share one call.
347
+ * Trusted host code only: it takes no principal, and what it applies is whatever the peer, the authority for the
348
+ * task, answers.
349
+ */
350
+ refresh(taskId) {
351
+ const running = this.refreshing.get(taskId);
352
+ if (running)
353
+ return running;
354
+ const p = (async () => {
355
+ const doc = await this.find(taskId);
356
+ if (!doc || isTerminal(TASK_MACHINE, doc.value.status))
357
+ return false;
358
+ return this.poll(doc);
359
+ })().finally(() => this.refreshing.delete(taskId));
360
+ this.refreshing.set(taskId, p);
361
+ return p;
362
+ }
363
+ /** Records when the projection is asked next, and the error of a failed poll (cleared by a good one). */
364
+ async schedule(docId, quiet, error, notFoundSince) {
365
+ const next = this.due(quiet);
366
+ await this.store.transaction(async (tx) => {
367
+ const cur = await tx.get('remoteTasks', docId);
368
+ if (!cur || isTerminal(TASK_MACHINE, cur.value.status))
369
+ return;
370
+ const value = { ...cur.value, quiet };
371
+ if (next)
372
+ value.nextSyncAt = next;
373
+ else
374
+ delete value.nextSyncAt;
375
+ if (error)
376
+ value.lastError = error;
377
+ if (notFoundSince)
378
+ value.notFoundSince = notFoundSince;
379
+ if (error === undefined &&
380
+ value.quiet === cur.value.quiet &&
381
+ value.nextSyncAt === cur.value.nextSyncAt)
382
+ return;
383
+ await tx.update('remoteTasks', cur.id, cur.revision, value);
384
+ });
385
+ }
386
+ /** Ends a run of NotFound answers: the peer answered something else (FIX-087). */
387
+ async forgetNotFound(docId) {
388
+ await this.store.transaction(async (tx) => {
389
+ const cur = await tx.get('remoteTasks', docId);
390
+ if (!cur?.value.notFoundSince)
391
+ return;
392
+ const value = { ...cur.value };
393
+ delete value.notFoundSince;
394
+ await tx.update('remoteTasks', cur.id, cur.revision, value);
395
+ });
396
+ }
397
+ ref(r) {
398
+ return {
399
+ localTaskId: r.taskId,
400
+ route: r.route,
401
+ remoteTaskId: r.remoteTaskId,
402
+ };
403
+ }
404
+ async apply(taskId, normalized, remoteState, output,
405
+ /** The outcome of a `failed` projection, when the runtime rather than the peer's state decides it (FIX-080). */
406
+ failure) {
407
+ return this.store.transaction(async (tx) => {
408
+ const doc = (await tx.find('remoteTasks', { where: { taskId } }))[0];
409
+ const r = doc.value;
410
+ if (normalized === 'unknown' ||
411
+ (failure && isTerminal(TASK_MACHINE, r.status)) ||
412
+ (normalized === r.status && remoteState === r.remoteState))
413
+ return r;
414
+ // A peer's output is bound like a local handler's: one over `maxOutputBytes` (or not JSON at all) fails the
415
+ // projection with `SchemaViolation` instead of being stored whole (TASK-068).
416
+ const maxOutputBytes = this.o.maxOutputBytes ?? DEFAULT_LIMITS.maxOutputBytes;
417
+ let oversize = false;
418
+ if (normalized === 'completed' && output !== undefined) {
419
+ try {
420
+ oversize = Buffer.byteLength(JSON.stringify(output)) > maxOutputBytes;
421
+ }
422
+ catch {
423
+ oversize = true;
424
+ }
425
+ }
426
+ if (oversize) {
427
+ normalized = 'failed';
428
+ output = undefined;
429
+ }
430
+ const next = {
431
+ ...r,
432
+ status: normalized,
433
+ remoteState,
434
+ revision: r.revision + 1,
435
+ observedAt: this.now(),
436
+ ...(normalized === 'completed' && output !== undefined
437
+ ? { output }
438
+ : {}),
439
+ ...(normalized === 'failed'
440
+ ? {
441
+ outcome: oversize
442
+ ? {
443
+ code: 'SchemaViolation',
444
+ message: `Remote output exceeds the ${maxOutputBytes}-byte limit`,
445
+ }
446
+ : (failure ?? {
447
+ code: 'TaskFailed',
448
+ message: `Remote task ${remoteState}`,
449
+ }),
450
+ }
451
+ : normalized === 'cancelled'
452
+ ? {
453
+ outcome: {
454
+ code: 'TaskCancelled',
455
+ message: 'Remote task cancelled',
456
+ },
457
+ }
458
+ : {}),
459
+ };
460
+ delete next.lastError;
461
+ next.quiet = 0;
462
+ const due = this.due(0);
463
+ if (due)
464
+ next.nextSyncAt = due;
465
+ else
466
+ delete next.nextSyncAt;
467
+ await tx.update('remoteTasks', doc.id, doc.revision, next);
468
+ if (r.parentTaskId)
469
+ await pokeWakeups(tx, r.parentTaskId, this.now());
470
+ return next;
471
+ });
472
+ }
473
+ }
@@ -0,0 +1,167 @@
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, type CheckpointCodec, type CapabilityProvider, type SkillAccess, type WakeReason, type WakeupRequest } from '@agentropy/core';
7
+ import type { InMemoryImplementationProviderRegistry } from './implementation.js';
8
+ import { type TaskRecord, type TaskService } from './task-service.js';
9
+ export interface WakeupRecord {
10
+ id: string;
11
+ taskId: string;
12
+ conditions: WakeupRequest['anyOf'];
13
+ timeoutAt?: string;
14
+ onTimeout: 'resume' | 'fail';
15
+ status: 'armed' | 'fired' | 'revoked';
16
+ /** Due time per condition (timer/schedule), aligned with `conditions`; null for non-time conditions. */
17
+ conditionDue: (string | null)[];
18
+ /** Earliest time-based trigger (timer, schedule or timeout), for the polling scheduler. */
19
+ dueAt: string | null;
20
+ /**
21
+ * When the scheduler next evaluates it (FEAT-033.2): `dueAt`, or the time something it waits for happened
22
+ * (`pokeWakeups`); null when only a poke can make it fire. Absent on registrations armed before the index.
23
+ */
24
+ checkAt?: string | null;
25
+ /** Set by whoever fires it; delivered to the next activation. */
26
+ reason?: WakeReason;
27
+ /** Sanitized traceparent of the inbound event that fired it; linked from the next execution span. */
28
+ causeTraceparent?: string;
29
+ }
30
+ export interface RuntimeOptions {
31
+ tasks: TaskService;
32
+ implementations: InMemoryImplementationProviderRegistry;
33
+ /** Capability providers by provider ID (bindings in the snapshot name them). */
34
+ capabilityProviders: ReadonlyMap<string, CapabilityProvider>;
35
+ poolSize?: number;
36
+ leaseMs?: number;
37
+ cancelGraceMs?: number;
38
+ /** Largest serialized task output; a larger one fails the task with `SchemaViolation` (default 1 MiB, FEAT-040.2). */
39
+ maxOutputBytes?: number;
40
+ /** Longest one activation may run before it is aborted and fenced (default 10 min, FEAT-037.2). */
41
+ maxActivationMs?: number;
42
+ /**
43
+ * Called with every failure the pool contains instead of letting it escape as an unhandled rejection: a
44
+ * disposition that could not be written, a cancel or timeout fence that failed. Counted as
45
+ * `agentropy.scheduler.errors` either way.
46
+ */
47
+ onError?: (error: AgentropyError) => void;
48
+ /** Bounded execution history kept per task (R-37); older terminal executions are pruned. */
49
+ keepExecutions?: number;
50
+ skills?: (task: TaskRecord) => SkillAccess;
51
+ /** Outbox relay drained on every tick and when the pool goes idle (R-29). */
52
+ relay?: {
53
+ drain(): Promise<number>;
54
+ };
55
+ /** ADR-0024 gate: bounded re-checks after a policy outage (default 1 s doubling to 5 min, 8 evaluations). */
56
+ gateRetry?: {
57
+ initialMs: number;
58
+ maxMs: number;
59
+ maxAttempts: number;
60
+ };
61
+ /** A policy decision slower than this is treated as unavailable (default 5 s). */
62
+ pdpTimeoutMs?: number;
63
+ /** Largest serialized checkpoint a waiting disposition may store (R-37; default 64 KiB). */
64
+ maxCheckpointBytes?: number;
65
+ /** Identity of this worker among those sharing the store (M3-02); recorded on every lease. */
66
+ workerId?: string;
67
+ }
68
+ /**
69
+ * Fair dispatch order (M3-02): round-robin across tenants, oldest first within each tenant, so one tenant's backlog
70
+ * cannot starve another's on a shared pool.
71
+ */
72
+ export declare function fairOrder<T extends {
73
+ value: {
74
+ tenantId?: string;
75
+ };
76
+ }>(due: T[]): T[];
77
+ /** Applies the handler's checkpoint codec to a stored checkpoint (FEAT-028.3); never reinterprets silently. */
78
+ export declare function decodeCheckpoint(codec: CheckpointCodec | undefined, data: unknown, storedVersion: number | undefined): unknown;
79
+ export declare class AgentRuntime {
80
+ /** Executions handed over by `handOver`, whose late disposition is dropped. */
81
+ private readonly abandoned;
82
+ private readonly running;
83
+ private readonly o;
84
+ constructor(options: RuntimeOptions);
85
+ /**
86
+ * Contains a background promise (cancel or timeout fence): its failure is counted and reported, never an
87
+ * unhandled rejection that would end the process and every other execution with it (FEAT-037.2).
88
+ */
89
+ private guard;
90
+ /** Counts and reports a failure the host contains (see `onError`). */
91
+ report(err: unknown): void;
92
+ private get store();
93
+ private now;
94
+ /** Recover expired leases, then lease due executions up to the free pool capacity. Returns how many started. */
95
+ tick(): Promise<number>;
96
+ /**
97
+ * Lease heartbeat (M2-01): extend the lease of every execution this pool is still running, so another worker
98
+ * sharing the store does not recover it as lost while it makes progress. Fenced by state and epoch. Called by
99
+ * every tick and, independently of ticks, by the heartbeat timer of a started app (FIX-051).
100
+ */
101
+ renewLeases(): Promise<number>;
102
+ /** This worker's identity (M3-02). */
103
+ get workerId(): string;
104
+ /**
105
+ * Revocation checkpoint (D-20): signal every execution this pool is running under `grantRef` to stop. The
106
+ * handler sees its AbortSignal fire with `AuthorityExpired` (status revoked); its next protected effect is refused
107
+ * anyway (grants are checked per operation), and the task waits behind the dispatch gate. Committed effects are
108
+ * not rolled back: they stay in the effect journal for authorized compensation. Returns the affected task IDs.
109
+ */
110
+ revokeAuthority(grantRef: string, tenantId: string): Promise<string[]>;
111
+ /** Wait for every in-flight execution to settle. */
112
+ idle(): Promise<void>;
113
+ /**
114
+ * Hands this worker's running executions over (FEAT-072): signal every handler to stop, expire the leases now so any
115
+ * other worker recovers them at its next tick (E8, then the task's retry policy) instead of after `leaseMs`, and
116
+ * drop them from the pool. What a handler returns after this is discarded. For a worker that is about to exit, once
117
+ * its heartbeat has stopped; returns how many executions were handed over.
118
+ */
119
+ handOver(): Promise<number>;
120
+ /** Drop an execution from the pool (settled, or fenced after a cancel grace period). */
121
+ private forget;
122
+ /** Tick and settle until no due work remains (bounded). */
123
+ runUntilIdle(maxRounds?: number): Promise<void>;
124
+ get activeCount(): number;
125
+ /**
126
+ * ADR-0024 activation eligibility gate, evaluated before every lease with a fresh grant check and policy
127
+ * decision. A blocked task keeps its status (`assigned`) and its queued execution; the gate row records why,
128
+ * and when (if ever) to look again. Deadlines are enforced while gated (T9). Returns undefined when not admitted.
129
+ */
130
+ private admit;
131
+ private writeGate;
132
+ /** Fresh grant check and policy decision for dispatching a task; never reuses an earlier Allow. */
133
+ private dispatchDecision;
134
+ /**
135
+ * Store-wide per-tenant concurrency (M3-02, `maxConcurrentExecutions`): counted inside the lease transaction over
136
+ * every worker's running executions, so workers sharing the store cannot overshoot together.
137
+ */
138
+ private tenantAtCapacity;
139
+ /** E2+E3 with T3 in one transaction; the lease epoch fences every later write of this execution. */
140
+ private lease;
141
+ private execute;
142
+ /**
143
+ * Writes the disposition, retrying a store failure a few times. A fenced (stale-epoch) write is expected after lease
144
+ * loss, cancel grace expiry or a timeout fence: the result is discarded. If the store stays down the failure is
145
+ * reported and the execution is left to lease expiry, which recovers it (E8, then retry or failure) once the
146
+ * store is back; the pool and its other executions carry on (FEAT-037.2).
147
+ */
148
+ private settle;
149
+ private resumeState;
150
+ /** Applies a disposition only if this execution still holds the lease (same epoch, still running). */
151
+ private applyDisposition;
152
+ /** E8 for executions whose lease expired (crashed worker); the task retries (T6) or fails (T8). */
153
+ recoverExpiredLeases(): Promise<number>;
154
+ /**
155
+ * maxActivationMs elapsed (FEAT-037.2): abort the handler with `Timeout`; if it has not returned after the grace
156
+ * period, fence it as a lost lease — its lease is set to expire now and the next recovery applies E8 and the
157
+ * task's retry policy (T6, or T8 when attempts are exhausted). Its late result is discarded by the fence.
158
+ */
159
+ private timeoutRunning;
160
+ /** Cooperative cancel: fire AbortSignal; if the handler has not returned after the grace period, fence it (E8 + T11). */
161
+ private cancelRunning;
162
+ /** Keep only the last N terminal executions of a task (R-37). */
163
+ private prune;
164
+ private context;
165
+ /** The only handler effect surface: pinned bindings, declared operations, step keys, fresh authorization. */
166
+ private capabilityAccess;
167
+ }