@agentropy/runtime 0.0.0-stage → 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 +39 -2
  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 +48 -3
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Wake-ups (M1-08, ADR-0017): polling scheduler over armed registrations, in-process event bus with durable
3
+ * per-task subscriptions and mailboxes, child-task and human-action wake-ups. Firing consumes a registration
4
+ * with a CAS (exactly-once consumption, at-least-once delivery) and applies T5 (or T9 on fail-timeout).
5
+ */
6
+ import { AgentropyError, type CapabilityInvocationContext, type CapabilityProvider } from '@agentropy/core';
7
+ import { type CompactionResult } from './compaction.js';
8
+ import type { InstanceDirectory } from './registry.js';
9
+ import type { RemoteDelegationService } from './remote.js';
10
+ import { type TaskService } from './task-service.js';
11
+ export interface Subscription {
12
+ id: string;
13
+ taskId: string;
14
+ tenantId: string;
15
+ source: string;
16
+ filter?: Record<string, unknown>;
17
+ status: 'active' | 'revoked';
18
+ /** Events not appended because the mailbox was full (back-pressure). */
19
+ dropped?: number;
20
+ lastDroppedEventId?: string;
21
+ }
22
+ export interface MailboxEntry {
23
+ taskId: string;
24
+ subscriptionId: string;
25
+ eventId: string;
26
+ payload: unknown;
27
+ consumed: 0 | 1;
28
+ /** Sanitized W3C traceparent the producer sent with the event (correlation only). */
29
+ traceparent?: string;
30
+ }
31
+ export interface WakeupServiceOptions {
32
+ /** Unconsumed events kept per subscription; further events are dropped and counted (default 1000). */
33
+ mailboxLimit?: number;
34
+ /** Largest inbound event payload (default `DEFAULT_LIMITS.maxEventBytes`); larger is `SchemaViolation`. */
35
+ maxEventBytes?: number;
36
+ /**
37
+ * A poll evaluates only registrations due by `checkAt` (FEAT-033.2); every `fullScanMs` (default 60 s, and on
38
+ * the first poll) it evaluates every armed registration instead, as a backstop.
39
+ */
40
+ fullScanMs?: number;
41
+ /**
42
+ * Called with the failure of a sweep (FIX-052). A sweep that throws is counted as `agentropy.scheduler.errors`
43
+ * (code only, never the message) and handed here; the poll goes on with the remaining sweeps and then evaluates
44
+ * the wake-ups. A throwing hook is ignored.
45
+ */
46
+ onError?: (error: AgentropyError) => void;
47
+ }
48
+ export interface OfferResult {
49
+ /** False for a duplicate inbound event ID (already recorded). */
50
+ accepted: boolean;
51
+ /** Subscriptions the event was appended to. */
52
+ appended: number;
53
+ /** Subscriptions whose mailbox was full (back-pressure: the event was not appended there). */
54
+ dropped: number;
55
+ }
56
+ export declare class WakeupService {
57
+ private readonly tasks;
58
+ private readonly instances;
59
+ private readonly options;
60
+ private readonly sweeps;
61
+ private lastFullScan;
62
+ constructor(tasks: TaskService, instances: InstanceDirectory, options?: WakeupServiceOptions);
63
+ /**
64
+ * Work run at the start of every poll, e.g. human-action expiry, so due state changes are seen by this poll. A
65
+ * sweep that throws is reported (`options.onError`, `agentropy.scheduler.errors`) and does not stop the poll:
66
+ * an unreachable workflow engine or remote peer must not keep due timers from firing (FIX-052).
67
+ *
68
+ * A `background` sweep is one that waits on the network (the remote projection sync, a workflow engine's poll).
69
+ * A poll started with `detach` (the scheduler loop) starts it without waiting for it and never runs two of the
70
+ * same sweep at once, so a slow peer cannot hold the tick or local dispatch; any other poll waits for it, which
71
+ * keeps `runUntilIdle` and direct polls deterministic (FIX-053). `settle` waits for those in flight.
72
+ */
73
+ addSweep(sweep: () => Promise<unknown>, options?: {
74
+ background?: boolean;
75
+ }): void;
76
+ /** Waits for the background sweeps a detached poll left running (the loop's stop calls it). */
77
+ settle(): Promise<void>;
78
+ private runSweep;
79
+ private reportSweepFailure;
80
+ private get store();
81
+ private now;
82
+ /**
83
+ * Evaluate every armed registration once; returns how many fired. Safe to call repeatedly and concurrently. With
84
+ * `detach`, background sweeps are started but not waited for (see `addSweep`).
85
+ */
86
+ poll(options?: {
87
+ sweeps?: boolean;
88
+ detach?: boolean;
89
+ }): Promise<number>;
90
+ /** Durable subscription for a task; deterministic ID makes replays idempotent. */
91
+ subscribe(taskId: string, tenantId: string, source: string, filter?: Record<string, unknown>): Promise<string>;
92
+ unsubscribe(subscriptionId: string, taskId: string): Promise<void>;
93
+ /**
94
+ * Record an inbound event and append it to every matching active subscription's mailbox in one transaction.
95
+ * A duplicate event ID is dropped at append time. Returns false for a duplicate.
96
+ */
97
+ publish(event: {
98
+ eventId: string;
99
+ source: string;
100
+ tenantId: string;
101
+ payload: unknown;
102
+ traceparent?: string;
103
+ }): Promise<boolean>;
104
+ /**
105
+ * `publish` with back-pressure detail (M2-01): a subscription whose mailbox already holds `mailboxLimit`
106
+ * unconsumed events does not receive the event; the drop is counted on the subscription.
107
+ */
108
+ offer(event: {
109
+ eventId: string;
110
+ source: string;
111
+ tenantId: string;
112
+ payload: unknown;
113
+ traceparent?: string;
114
+ }): Promise<OfferResult>;
115
+ /**
116
+ * Compaction (M2-01, R-37; every collection since FEAT-040.1): see `compactStore`. Duplicate inbound events are
117
+ * only detected inside the retention window.
118
+ */
119
+ compact(retainMs: number): Promise<CompactionResult>;
120
+ private tryFire;
121
+ /** First condition that is satisfied, in declaration order; the timeout is checked last. */
122
+ private evaluate;
123
+ }
124
+ export type OperationHandler = (input: unknown, ctx: CapabilityInvocationContext) => Promise<unknown>;
125
+ /**
126
+ * Built-in capability provider: routes `operation` to the handler of the capability that declares it.
127
+ * Capability v1 operation names are unique across the catalog, which this constructor asserts.
128
+ */
129
+ export declare class BuiltinCapabilityProvider implements CapabilityProvider {
130
+ readonly id = "builtin";
131
+ readonly version = "1.0.0";
132
+ readonly contracts: {
133
+ level?: string | undefined;
134
+ id: string;
135
+ version: string;
136
+ }[];
137
+ private readonly handlers;
138
+ constructor(handlers: Partial<Record<string, OperationHandler>>);
139
+ invoke<I, O>(operation: string, input: I, ctx: CapabilityInvocationContext): Promise<O>;
140
+ }
141
+ /** Handlers for delegation, event-handling and scheduling operations (Capability v1 operation I/O). */
142
+ export declare function coreOperationHandlers(tasks: TaskService, wakeups: WakeupService, remote?: RemoteDelegationService): Record<string, OperationHandler>;
@@ -0,0 +1,501 @@
1
+ /**
2
+ * Wake-ups (M1-08, ADR-0017): polling scheduler over armed registrations, in-process event bus with durable
3
+ * per-task subscriptions and mailboxes, child-task and human-action wake-ups. Firing consumes a registration
4
+ * with a CAS (exactly-once consumption, at-least-once delivery) and applies T5 (or T9 on fail-timeout).
5
+ */
6
+ import { AgentropyError, CAPABILITY_CATALOG, digestOf, isTerminal, nextOccurrence, TASK_MACHINE, METRICS, sanitizeTraceparent, toAgentropyError, } from '@agentropy/core';
7
+ import { compactStore } from './compaction.js';
8
+ import { DEFAULT_LIMITS, assertMaxBytes } from './limits.js';
9
+ import { pokeWakeups } from './wake-index.js';
10
+ import { toSnapshot, } from './task-service.js';
11
+ const matches = (filter, payload) => !filter ||
12
+ Object.entries(filter).every(([k, v]) => payload?.[k] === v);
13
+ export class WakeupService {
14
+ tasks;
15
+ instances;
16
+ options;
17
+ sweeps = [];
18
+ lastFullScan = -Infinity;
19
+ constructor(tasks, instances, options = {}) {
20
+ this.tasks = tasks;
21
+ this.instances = instances;
22
+ this.options = options;
23
+ }
24
+ /**
25
+ * Work run at the start of every poll, e.g. human-action expiry, so due state changes are seen by this poll. A
26
+ * sweep that throws is reported (`options.onError`, `agentropy.scheduler.errors`) and does not stop the poll:
27
+ * an unreachable workflow engine or remote peer must not keep due timers from firing (FIX-052).
28
+ *
29
+ * A `background` sweep is one that waits on the network (the remote projection sync, a workflow engine's poll).
30
+ * A poll started with `detach` (the scheduler loop) starts it without waiting for it and never runs two of the
31
+ * same sweep at once, so a slow peer cannot hold the tick or local dispatch; any other poll waits for it, which
32
+ * keeps `runUntilIdle` and direct polls deterministic (FIX-053). `settle` waits for those in flight.
33
+ */
34
+ addSweep(sweep, options = {}) {
35
+ this.sweeps.push({ run: sweep, background: options.background === true });
36
+ }
37
+ /** Waits for the background sweeps a detached poll left running (the loop's stop calls it). */
38
+ async settle() {
39
+ await Promise.all(this.sweeps.map((s) => s.running));
40
+ }
41
+ async runSweep(s) {
42
+ try {
43
+ await s.run();
44
+ }
45
+ catch (err) {
46
+ this.reportSweepFailure(err);
47
+ }
48
+ }
49
+ reportSweepFailure(err) {
50
+ const error = toAgentropyError(err);
51
+ this.tasks.telemetry.count(METRICS.schedulerErrors, 1, {
52
+ 'agentropy.error.code': error.code,
53
+ });
54
+ try {
55
+ this.options.onError?.(error);
56
+ }
57
+ catch {
58
+ // A failing error hook must not stop the poll either.
59
+ }
60
+ }
61
+ get store() {
62
+ return this.tasks.o.store;
63
+ }
64
+ now() {
65
+ return this.tasks.o.now();
66
+ }
67
+ /**
68
+ * Evaluate every armed registration once; returns how many fired. Safe to call repeatedly and concurrently. With
69
+ * `detach`, background sweeps are started but not waited for (see `addSweep`).
70
+ */
71
+ async poll(options = {}) {
72
+ if (options.sweeps !== false)
73
+ for (const s of this.sweeps) {
74
+ if (!s.background) {
75
+ await this.runSweep(s);
76
+ continue;
77
+ }
78
+ s.running ??= this.runSweep(s).finally(() => {
79
+ s.running = undefined;
80
+ });
81
+ if (!options.detach)
82
+ await s.running;
83
+ }
84
+ const now = this.now();
85
+ const at = Date.parse(now);
86
+ const full = at - this.lastFullScan >= (this.options.fullScanMs ?? 60_000);
87
+ if (full)
88
+ this.lastFullScan = at;
89
+ const armed = await this.store.transaction((tx) => tx.find('wakeups', {
90
+ where: { status: 'armed' },
91
+ ...(full ? {} : { range: { field: 'checkAt', lte: now } }),
92
+ }));
93
+ let fired = 0;
94
+ for (const w of armed)
95
+ if (await this.tryFire(w.id))
96
+ fired++;
97
+ return fired;
98
+ }
99
+ /** Durable subscription for a task; deterministic ID makes replays idempotent. */
100
+ async subscribe(taskId, tenantId, source, filter) {
101
+ const id = `sub:${digestOf({ taskId, source, filter: filter ?? null })}`;
102
+ await this.store.transaction(async (tx) => {
103
+ const existing = await tx.get('subscriptions', id);
104
+ // One that `unsubscribe` revoked is active again: the deterministic ID must not leave it dead (FEAT-038.2).
105
+ if (existing?.value.status === 'revoked')
106
+ await tx.update('subscriptions', id, existing.revision, {
107
+ ...existing.value,
108
+ status: 'active',
109
+ });
110
+ else if (!existing)
111
+ await tx.insert('subscriptions', id, {
112
+ id,
113
+ taskId,
114
+ tenantId,
115
+ source,
116
+ ...(filter ? { filter } : {}),
117
+ status: 'active',
118
+ });
119
+ });
120
+ return id;
121
+ }
122
+ async unsubscribe(subscriptionId, taskId) {
123
+ await this.store.transaction(async (tx) => {
124
+ const s = await tx.get('subscriptions', subscriptionId);
125
+ if (s && s.value.taskId === taskId && s.value.status === 'active')
126
+ await tx.update('subscriptions', s.id, s.revision, {
127
+ ...s.value,
128
+ status: 'revoked',
129
+ });
130
+ });
131
+ }
132
+ /**
133
+ * Record an inbound event and append it to every matching active subscription's mailbox in one transaction.
134
+ * A duplicate event ID is dropped at append time. Returns false for a duplicate.
135
+ */
136
+ async publish(event) {
137
+ return (await this.offer(event)).accepted;
138
+ }
139
+ /**
140
+ * `publish` with back-pressure detail (M2-01): a subscription whose mailbox already holds `mailboxLimit`
141
+ * unconsumed events does not receive the event; the drop is counted on the subscription.
142
+ */
143
+ async offer(event) {
144
+ const limit = this.options.mailboxLimit ?? 1000;
145
+ assertMaxBytes(event.payload, this.options.maxEventBytes ?? DEFAULT_LIMITS.maxEventBytes, 'event');
146
+ const telemetry = this.tasks.telemetry;
147
+ const traceparent = sanitizeTraceparent(event.traceparent);
148
+ if (event.traceparent !== undefined && !traceparent)
149
+ telemetry.count(METRICS.traceRejected, 1, { carrier: 'event' });
150
+ const result = await this.store.transaction(async (tx) => {
151
+ const r = { accepted: false, appended: 0, dropped: 0 };
152
+ if (await tx.get('inboundEvents', event.eventId))
153
+ return r;
154
+ r.accepted = true;
155
+ await tx.insert('inboundEvents', event.eventId, {
156
+ source: event.source,
157
+ tenantId: event.tenantId,
158
+ at: this.now(),
159
+ });
160
+ for (const s of await tx.find('subscriptions', {
161
+ where: { source: event.source, status: 'active' },
162
+ })) {
163
+ if (s.value.tenantId !== event.tenantId ||
164
+ !matches(s.value.filter, event.payload))
165
+ continue;
166
+ // Only whether the mailbox is full matters: read at most `limit` rows.
167
+ const pending = await tx.find('mailbox', {
168
+ where: { subscriptionId: s.id, consumed: 0 },
169
+ limit,
170
+ });
171
+ if (pending.length >= limit) {
172
+ await tx.update('subscriptions', s.id, s.revision, {
173
+ ...s.value,
174
+ dropped: (s.value.dropped ?? 0) + 1,
175
+ lastDroppedEventId: event.eventId,
176
+ });
177
+ r.dropped++;
178
+ telemetry.count(METRICS.mailboxDropped, 1, {
179
+ 'agentropy.event.source': event.source,
180
+ });
181
+ continue;
182
+ }
183
+ await tx.insert('mailbox', `${s.id}:${event.eventId}`, {
184
+ taskId: s.value.taskId,
185
+ subscriptionId: s.id,
186
+ eventId: event.eventId,
187
+ payload: event.payload,
188
+ consumed: 0,
189
+ ...(traceparent ? { traceparent } : {}),
190
+ });
191
+ await pokeWakeups(tx, s.value.taskId, this.now());
192
+ r.appended++;
193
+ }
194
+ return r;
195
+ });
196
+ // The event poked the registrations it concerns: evaluate those (the due-time index), not every sweep again.
197
+ if (result.accepted)
198
+ await this.poll({ sweeps: false });
199
+ return result;
200
+ }
201
+ /**
202
+ * Compaction (M2-01, R-37; every collection since FEAT-040.1): see `compactStore`. Duplicate inbound events are
203
+ * only detected inside the retention window.
204
+ */
205
+ compact(retainMs) {
206
+ return compactStore(this.tasks, retainMs);
207
+ }
208
+ async tryFire(wakeupId) {
209
+ return this.store.transaction(async (tx) => {
210
+ const w = await tx.get('wakeups', wakeupId);
211
+ if (!w || w.value.status !== 'armed')
212
+ return false;
213
+ const task = await tx.get('tasks', w.value.taskId);
214
+ if (!task || task.value.status !== 'waiting')
215
+ return false;
216
+ // A suspended instance defers its wake-ups (they fire after resume), never drops them.
217
+ if ((await tx.get('instances', task.value.instanceId))
218
+ ?.value.state === 'suspended')
219
+ return false;
220
+ const now = this.now();
221
+ // T9: a waiting task past its deadline fails, whatever it waits for (FEAT-038.1).
222
+ if (task.value.deadline && task.value.deadline <= now) {
223
+ await this.tasks.terminate(tx, task, 'failed', 'T9', {
224
+ code: 'Timeout',
225
+ message: 'Task deadline passed',
226
+ });
227
+ return true;
228
+ }
229
+ const hit = await this.evaluate(tx, w.value, now);
230
+ if (!hit) {
231
+ // Nothing holds yet: wait for the next due time or a poke.
232
+ if (w.value.checkAt !== w.value.dueAt)
233
+ await tx.update('wakeups', w.id, w.revision, {
234
+ ...w.value,
235
+ checkAt: w.value.dueAt,
236
+ });
237
+ return false;
238
+ }
239
+ // The activation budget (`budget.maxActivations`) is spent: no further activation, T9 (FEAT-038.1).
240
+ const maxActivations = task.value.budget?.maxActivations;
241
+ if (maxActivations !== undefined &&
242
+ task.value.activation >= maxActivations) {
243
+ await tx.update('wakeups', w.id, w.revision, {
244
+ ...w.value,
245
+ status: 'fired',
246
+ reason: hit.reason,
247
+ });
248
+ await this.tasks.terminate(tx, task, 'failed', 'T9', {
249
+ code: 'BudgetExceeded',
250
+ message: 'Activation budget spent',
251
+ });
252
+ return true;
253
+ }
254
+ // An expired human action whose request says fail-task fails the task (T9) instead of resuming it.
255
+ if (hit.reason.kind === 'human-action' &&
256
+ hit.reason.outcome === 'expired' &&
257
+ (await tx.get('humanActions', hit.reason.requestId))
258
+ ?.value.onExpiry === 'fail-task') {
259
+ await tx.update('wakeups', w.id, w.revision, {
260
+ ...w.value,
261
+ status: 'fired',
262
+ reason: hit.reason,
263
+ });
264
+ await this.tasks.terminate(tx, task, 'failed', 'T9', {
265
+ code: 'ActionExpired',
266
+ message: 'Human action expired',
267
+ });
268
+ return true;
269
+ }
270
+ if (hit.reason.kind === 'timeout' && w.value.onTimeout === 'fail') {
271
+ await tx.update('wakeups', w.id, w.revision, {
272
+ ...w.value,
273
+ status: 'fired',
274
+ reason: hit.reason,
275
+ });
276
+ await this.tasks.terminate(tx, task, 'failed', 'T9', {
277
+ code: 'Timeout',
278
+ message: 'Wake-up timeout elapsed',
279
+ });
280
+ return true;
281
+ }
282
+ await tx.update('wakeups', w.id, w.revision, {
283
+ ...w.value,
284
+ status: 'fired',
285
+ reason: hit.reason,
286
+ ...(hit.consume?.value.traceparent
287
+ ? { causeTraceparent: hit.consume.value.traceparent }
288
+ : {}),
289
+ });
290
+ if (hit.consume)
291
+ await tx.update('mailbox', hit.consume.id, hit.consume.revision, { ...hit.consume.value, consumed: 1 });
292
+ const { waitingOn: _w, ...rest } = task.value;
293
+ void _w;
294
+ const next = await this.tasks.transition(tx, { ...task, value: rest }, 'assigned', 'T5', { activation: task.value.activation + 1, attempt: 1 });
295
+ await this.tasks.queueExecution(tx, task.id, next.value.activation, 1, 'resume', now);
296
+ return true;
297
+ });
298
+ }
299
+ /** First condition that is satisfied, in declaration order; the timeout is checked last. */
300
+ async evaluate(tx, w, now) {
301
+ for (const [i, c] of w.conditions.entries()) {
302
+ if (c.kind === 'timer' || c.kind === 'schedule') {
303
+ const due = w.conditionDue?.[i];
304
+ if (due && due <= now)
305
+ return { reason: { kind: c.kind, firedAt: now } };
306
+ }
307
+ else if (c.kind === 'event') {
308
+ const pending = await tx.find('mailbox', {
309
+ where: { subscriptionId: c.subscription, consumed: 0 },
310
+ limit: 1,
311
+ });
312
+ const oldest = pending[0];
313
+ if (oldest)
314
+ return {
315
+ reason: {
316
+ kind: 'event',
317
+ subscription: c.subscription,
318
+ eventId: oldest.value.eventId,
319
+ payload: oldest.value.payload,
320
+ },
321
+ consume: oldest,
322
+ };
323
+ }
324
+ else if (c.kind === 'human-action') {
325
+ const req = await tx.get('humanActions', c.requestId);
326
+ const s = req?.value.status;
327
+ if (s === 'resolved' || s === 'expired' || s === 'revoked') {
328
+ return {
329
+ reason: {
330
+ kind: 'human-action',
331
+ requestId: c.requestId,
332
+ outcome: s,
333
+ ...(s === 'resolved' ? { input: req.value.decisionInput } : {}),
334
+ },
335
+ };
336
+ }
337
+ }
338
+ else if (c.kind === 'child-tasks') {
339
+ // Remote children (FEAT-027.9) are tracked by their local projection, found by its indexed task ID.
340
+ const children = await Promise.all(c.taskIds.map(async (id) => {
341
+ const local = await tx.get('tasks', id);
342
+ if (local)
343
+ return local;
344
+ if (!id.includes(':'))
345
+ return undefined;
346
+ const r = (await tx.find('remoteTasks', {
347
+ where: { taskId: id },
348
+ }))[0];
349
+ return r
350
+ ? {
351
+ ...r,
352
+ id,
353
+ value: r.value,
354
+ }
355
+ : undefined;
356
+ }));
357
+ const done = children.filter((d) => !!d && isTerminal(TASK_MACHINE, d.value.status));
358
+ if (c.mode === 'all' ? done.length === c.taskIds.length : done.length > 0) {
359
+ return {
360
+ reason: {
361
+ kind: 'child-tasks',
362
+ children: done.map((d) => ({
363
+ taskId: d.id,
364
+ status: d.value.status,
365
+ ...(d.value.status === 'completed'
366
+ ? { output: d.value.output }
367
+ : { outcome: d.value.outcome }),
368
+ })),
369
+ },
370
+ };
371
+ }
372
+ }
373
+ }
374
+ if (w.timeoutAt && w.timeoutAt <= now)
375
+ return { reason: { kind: 'timeout' } };
376
+ return undefined;
377
+ }
378
+ }
379
+ /**
380
+ * Built-in capability provider: routes `operation` to the handler of the capability that declares it.
381
+ * Capability v1 operation names are unique across the catalog, which this constructor asserts.
382
+ */
383
+ export class BuiltinCapabilityProvider {
384
+ id = 'builtin';
385
+ version = '1.0.0';
386
+ contracts = CAPABILITY_CATALOG.map((c) => ({
387
+ id: c.id,
388
+ version: c.version,
389
+ ...(c.id === 'durability' ? { level: 'durable-execution' } : {}),
390
+ }));
391
+ handlers = new Map();
392
+ constructor(handlers) {
393
+ const owners = new Map();
394
+ for (const c of CAPABILITY_CATALOG)
395
+ for (const op of c.operations) {
396
+ if (owners.has(op.name))
397
+ throw new AgentropyError('Internal', `Operation ${op.name} is declared twice`);
398
+ owners.set(op.name, c.id);
399
+ }
400
+ for (const [op, h] of Object.entries(handlers))
401
+ if (h)
402
+ this.handlers.set(op, h);
403
+ }
404
+ async invoke(operation, input, ctx) {
405
+ const h = this.handlers.get(operation);
406
+ if (!h)
407
+ throw new AgentropyError('UnsupportedOperation', `No built-in implementation for ${operation}`, { details: { operation } });
408
+ return (await h(input, ctx));
409
+ }
410
+ }
411
+ /** Handlers for delegation, event-handling and scheduling operations (Capability v1 operation I/O). */
412
+ export function coreOperationHandlers(tasks, wakeups, remote) {
413
+ const agentPrincipal = async (ctx) => ({
414
+ id: ctx.principalId,
415
+ type: 'agent',
416
+ tenantId: ctx.tenantId,
417
+ ...(ctx.delegatedAuthorityRef
418
+ ? { delegatedAuthorityRef: ctx.delegatedAuthorityRef }
419
+ : {}),
420
+ });
421
+ const ownChild = async (taskId, ctx) => {
422
+ const doc = await tasks.o.store.transaction((tx) => tx.get('tasks', taskId));
423
+ if (!doc ||
424
+ doc.value.parentTaskId !== ctx.taskId ||
425
+ doc.value.tenantId !== ctx.tenantId)
426
+ throw new AgentropyError('NotFound', 'Task not found');
427
+ return doc;
428
+ };
429
+ const remoteChild = async (taskId, ctx) => {
430
+ if (!remote || !taskId.includes(':'))
431
+ return undefined;
432
+ try {
433
+ const r = await remote.get(taskId, await agentPrincipal(ctx));
434
+ return r.parentTaskId === ctx.taskId ? r : undefined;
435
+ }
436
+ catch {
437
+ return undefined;
438
+ }
439
+ };
440
+ return {
441
+ delegate: async (input, ctx) => {
442
+ const d = input;
443
+ const parent = await tasks.o.store.transaction((tx) => tx.get('tasks', ctx.taskId));
444
+ if (d.target?.remote) {
445
+ if (!remote)
446
+ throw new AgentropyError('NoCompatibleRoute', 'No communication router is configured for remote targets');
447
+ if (!ctx.idempotencyKey)
448
+ throw new AgentropyError('SchemaViolation', 'delegate requires a stepKey', {
449
+ details: { reason: 'missingStepKey' },
450
+ });
451
+ return remote.delegate({
452
+ target: d.target,
453
+ input: d.input,
454
+ idempotencyKey: ctx.idempotencyKey,
455
+ correlationId: parent?.value.correlationId ?? ctx.taskId,
456
+ parentTaskId: ctx.taskId,
457
+ ...(d.deadline ? { deadline: d.deadline } : {}),
458
+ }, await agentPrincipal(ctx));
459
+ }
460
+ return tasks.delegate({
461
+ target: d.target,
462
+ input: d.input,
463
+ idempotencyKey: ctx.idempotencyKey,
464
+ correlationId: parent?.value.correlationId ?? ctx.taskId,
465
+ parentTaskId: ctx.taskId,
466
+ ...(d.deadline ? { deadline: d.deadline } : {}),
467
+ ...(d.budget ? { budget: d.budget } : {}),
468
+ }, await agentPrincipal(ctx), ctx.traceparent ? { traceparent: ctx.traceparent } : {});
469
+ },
470
+ getTask: async (input, ctx) => {
471
+ const { taskId } = input;
472
+ const r = remote ? await remoteChild(taskId, ctx) : undefined;
473
+ if (r)
474
+ return remote.snapshot(r);
475
+ const doc = await ownChild(taskId, ctx);
476
+ return toSnapshot(doc.value, doc.revision);
477
+ },
478
+ cancel: async (input, ctx) => {
479
+ const { taskId, reason } = input;
480
+ const r = remote ? await remoteChild(taskId, ctx) : undefined;
481
+ if (r)
482
+ return remote.cancel(taskId, await agentPrincipal(ctx));
483
+ await ownChild(taskId, ctx);
484
+ return tasks.cancel(taskId, await agentPrincipal(ctx), reason);
485
+ },
486
+ subscribe: async (input, ctx) => {
487
+ const { source, filter } = input;
488
+ return {
489
+ subscription: await wakeups.subscribe(ctx.taskId, ctx.tenantId, source, filter),
490
+ };
491
+ },
492
+ unsubscribe: async (input, ctx) => {
493
+ await wakeups.unsubscribe(input.subscription, ctx.taskId);
494
+ return {};
495
+ },
496
+ nextOccurrence: async (input) => {
497
+ const { cron, timezone, after } = input;
498
+ return { at: nextOccurrence(cron, timezone, after ?? tasks.o.now()) };
499
+ },
500
+ };
501
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `workflow.start` / `workflow.status` backed by a WorkflowEngine (ADR-0006, M2-07). The engine owns
3
+ * deterministic execution; Agentropy only starts runs idempotently (the derived step key is the engine's
4
+ * idempotency key) and turns engine completion into an inbound `workflow` event, so the waiting agent task wakes
5
+ * through its ordinary event subscription (filter `{ runId }`). Subscribe before starting so no completion is
6
+ * missed. No workflow semantics (steps, branching, compensation) live in Agentropy.
7
+ */
8
+ import { type CapabilityInvocationContext, type Store, type WorkflowEngine } from '@agentropy/core';
9
+ /** Source of the completion events; subscribe with `{ source: WORKFLOW_SOURCE, filter: { runId } }`. */
10
+ export declare const WORKFLOW_SOURCE = "workflow";
11
+ export declare function workflowOperationHandlers(engine: WorkflowEngine,
12
+ /**
13
+ * With a store, `workflow.start` is journaled by its step key (the `effects` collection, like other external
14
+ * effects): a replayed step returns the run it started instead of asking the engine again, so once-per-key
15
+ * holds even for engines that ignore the idempotency key (Conductor OSS does). A crash between the engine's
16
+ * answer and the journal write can still start a second run; the engine's own idempotency covers that window.
17
+ */
18
+ journal?: {
19
+ store: Store;
20
+ now: () => string;
21
+ }): Record<string, (input: unknown, ctx: CapabilityInvocationContext) => Promise<unknown>>;
22
+ /**
23
+ * Bridges engine completions into the trusted event ingress (deduplicated by run ID). A failed publish (a store
24
+ * blip) is retried with doubling backoff; after `attempts` it is handed to `onError`, because the event ID makes a
25
+ * later manual or polled redelivery safe (FEAT-038.2).
26
+ */
27
+ export declare function bridgeWorkflowCompletions(engine: WorkflowEngine, publish: (event: {
28
+ eventId: string;
29
+ source: string;
30
+ tenantId: string;
31
+ payload: unknown;
32
+ }) => Promise<boolean>, options?: {
33
+ attempts?: number;
34
+ retryMs?: number;
35
+ onError?: (error: unknown) => void;
36
+ }): void;