@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,790 @@
1
+ /**
2
+ * TaskService (Agent v1 AgentService task operations, runtime contract §1): authoritative for local tasks.
3
+ * Guard order: authenticate → authorize (grant, tenant, policy; invisible → NotFound) → schema →
4
+ * idempotency replay → entity state → capability/guarantee → limits. Every transition is a CAS in the
5
+ * Store and emits exactly one outbox event in the same transaction.
6
+ */
7
+ import { createHash, randomUUID } from 'node:crypto';
8
+ import { AgentropyError, isAgentropyError, EXECUTION_MACHINE, HUMAN_ACTION_MACHINE, INSTANCE_MACHINE, TASK_MACHINE, assertTransition, digestOf, enforcePolicy, isTerminal, normalizeInstant, resolveAcceptance, validateAgainst, METRICS, NOOP_TELEMETRY, SPANS, sanitizeTraceparent, TRANSITION_EVENT, } from '@agentropy/core';
9
+ import { recordAuditIntent } from './audit.js';
10
+ import { DEFAULT_LIMITS, assertMaxBytes } from './limits.js';
11
+ import { checkTaskQuota } from './quotas.js';
12
+ import { pokeWakeups } from './wake-index.js';
13
+ /** Users whose inbox shows a human-action request: its named assignees, else the task owner. */
14
+ export const actionUsers = (a, task) => a.assignees.principalIds?.length ? a.assignees.principalIds : [task.ownerId];
15
+ export const DEFAULT_RETRY = {
16
+ maxAttempts: 3,
17
+ backoff: { initialMs: 1000, maxMs: 300_000, multiplier: 2 },
18
+ };
19
+ /** The handle an acceptance answers with. */
20
+ const handleOf = (t) => ({
21
+ taskId: t.taskId,
22
+ agentInstanceId: t.instanceId,
23
+ // The status at acceptance: both T1 and T2 commit in the accepting transaction.
24
+ status: 'assigned',
25
+ definition: t.definition,
26
+ durability: t.snapshot.durability,
27
+ });
28
+ export const hashKey = (...parts) => createHash('sha256').update(JSON.stringify(parts)).digest('hex');
29
+ export function toSnapshot(t, revision) {
30
+ return {
31
+ taskId: t.taskId,
32
+ status: t.status,
33
+ revision,
34
+ agentInstanceId: t.instanceId,
35
+ ...(t.parentTaskId ? { parentTaskId: t.parentTaskId } : {}),
36
+ ...(t.cancelRequestedAt ? { cancelRequestedAt: t.cancelRequestedAt } : {}),
37
+ ...(t.waitingOn ? { waitingOn: t.waitingOn } : {}),
38
+ ...(t.outcome ? { outcome: t.outcome } : {}),
39
+ authority: 'local',
40
+ correlationId: t.correlationId,
41
+ updatedAt: t.updatedAt,
42
+ };
43
+ }
44
+ export class TaskService {
45
+ o;
46
+ cancelHooks = new Set();
47
+ constructor(o) {
48
+ this.o = o;
49
+ }
50
+ newId(kind) {
51
+ // IDs must stay unique across restarts of the same store.
52
+ return this.o.newId ? this.o.newId(kind) : `${kind}-${randomUUID()}`;
53
+ }
54
+ /** The runtime registers to hear cancel requests for running executions. */
55
+ onCancelRequested(hook) {
56
+ this.cancelHooks.add(hook);
57
+ }
58
+ get telemetry() {
59
+ return this.o.telemetry ?? NOOP_TELEMETRY;
60
+ }
61
+ /**
62
+ * Accept a task (see `accept`) inside an `agentropy.task.accept` span. `trace.traceparent` is an untrusted
63
+ * correlation hint from ingress or the parent capability span: it is sanitized and never used for authorization.
64
+ */
65
+ async delegate(request, caller, trace = {}) {
66
+ const parent = sanitizeTraceparent(trace.traceparent);
67
+ if (trace.traceparent !== undefined && !parent)
68
+ this.telemetry.count(METRICS.traceRejected, 1, { carrier: 'delegate' });
69
+ const span = this.telemetry.startSpan(SPANS.accept, {
70
+ kind: 'server',
71
+ ...(parent ? { parent } : {}),
72
+ attributes: {
73
+ 'agentropy.tenant.id': caller?.tenantId ?? '',
74
+ 'agentropy.correlation_id': request?.correlationId ?? '',
75
+ ...(request?.target && 'instanceId' in request.target
76
+ ? { 'agentropy.instance.id': request.target.instanceId }
77
+ : {}),
78
+ },
79
+ });
80
+ try {
81
+ const handle = await this.accept(request, caller, span.traceparent ?? parent);
82
+ span.setAttributes({ 'agentropy.task.id': handle.taskId });
83
+ return handle;
84
+ }
85
+ catch (err) {
86
+ span.fail(err.code ?? 'Internal');
87
+ throw err;
88
+ }
89
+ finally {
90
+ span.end();
91
+ }
92
+ }
93
+ async accept(request, caller, traceparent) {
94
+ // 1. Authenticate.
95
+ if (!caller?.id || !caller.tenantId)
96
+ throw new AgentropyError('Unauthenticated', 'No trusted principal');
97
+ // 2. Authorize: grant, target visibility (tenant), policy.
98
+ await this.checkGrant(caller);
99
+ const idemId = hashKey(caller.tenantId, caller.id, request.idempotencyKey);
100
+ // FEAT-032.2: the target and the idempotency record come from one read; the record is acted on only below.
101
+ const { instance, replay: early, planned, } = await this.resolveTarget(request, caller, idemId);
102
+ await enforcePolicy(this.o.pdp, {
103
+ principal: caller,
104
+ action: 'delegation:delegate',
105
+ resource: {
106
+ type: 'agent-instance',
107
+ id: instance.id,
108
+ tenantId: caller.tenantId,
109
+ },
110
+ });
111
+ const definition = this.o.definitions.require(instance.definition);
112
+ // 3. Schema, and the size bound (a payload cannot grow task rows without limit).
113
+ validateAgainst(definition.inputSchema, request.input, `${definition.id} input`);
114
+ assertMaxBytes(request.input, this.o.limits?.maxInputBytes ?? DEFAULT_LIMITS.maxInputBytes, 'input');
115
+ // The deadline is compared as a string by the scheduler: keep only UTC ISO-8601 (FEAT-038.3).
116
+ const deadline = request.deadline === undefined
117
+ ? undefined
118
+ : normalizeInstant(request.deadline, 'deadline');
119
+ // 4. Idempotency replay (before state: a retry always gets its original answer).
120
+ const fingerprint = digestOf({
121
+ target: { instanceId: instance.id },
122
+ input: request.input,
123
+ parentTaskId: request.parentTaskId ?? null,
124
+ });
125
+ const replay = early === null
126
+ ? await this.o.store.transaction((tx) => tx.get('idempotency', idemId))
127
+ : early;
128
+ if (replay) {
129
+ if (replay.value.fingerprint !== fingerprint)
130
+ throw new AgentropyError('IdempotencyConflict', 'Idempotency key reused with a different request');
131
+ return this.handleFor(replay.value.taskId);
132
+ }
133
+ // 5. Entity state.
134
+ if (instance.state === 'suspended')
135
+ throw new AgentropyError('InstanceUnavailable', 'Target instance is suspended');
136
+ if (instance.state === 'retired')
137
+ throw new AgentropyError('InvalidState', 'Target instance is retired', {
138
+ details: { kind: 'instance' },
139
+ });
140
+ if (instance.draining)
141
+ throw new AgentropyError('InstanceUnavailable', 'Target instance is draining and accepts no new tasks', { details: { reason: 'draining' } });
142
+ // 6. Capability, guarantee and implementation resolution → pinned snapshot.
143
+ const snapshot = await resolveAcceptance({ definition, principal: caller, tenantId: caller.tenantId }, this.o.acceptance);
144
+ // 7. Limits.
145
+ const parent = request.parentTaskId
146
+ ? await this.o.store.transaction((tx) => tx.get('tasks', request.parentTaskId))
147
+ : undefined;
148
+ if (request.parentTaskId &&
149
+ (!parent || parent.value.tenantId !== caller.tenantId))
150
+ throw new AgentropyError('NotFound', 'Parent task not found');
151
+ if (parent)
152
+ assertParentOpen(parent.value);
153
+ const depth = parent ? parent.value.depth + 1 : 0;
154
+ if (depth > (this.o.limits?.maxDepth ?? 5))
155
+ throw new AgentropyError('DelegationDepthExceeded', 'Delegation depth exceeded', { details: { depth } });
156
+ const now = this.o.now();
157
+ const taskId = this.newId('task');
158
+ // D-15: an agent delegating on someone's behalf passes on a grant narrowed to the target, when the grant
159
+ // service supports narrowing; a refused narrowing is a denial, never a silent fallback to the wider grant.
160
+ let grantRef = caller.delegatedAuthorityRef;
161
+ if (grantRef && caller.type === 'agent' && this.o.grants?.narrow) {
162
+ try {
163
+ grantRef = await this.o.grants.narrow(grantRef, {
164
+ tenantId: caller.tenantId,
165
+ agentInstanceId: instance.id,
166
+ ...(request.parentTaskId
167
+ ? { parentTaskId: request.parentTaskId }
168
+ : {}),
169
+ });
170
+ }
171
+ catch (cause) {
172
+ if (isAgentropyError(cause))
173
+ throw cause;
174
+ throw new AgentropyError('PermissionDenied', 'Delegated authority cannot be narrowed to the target', { cause });
175
+ }
176
+ }
177
+ const task = {
178
+ taskId,
179
+ tenantId: caller.tenantId,
180
+ status: 'created',
181
+ instanceId: instance.id,
182
+ ownerId: instance.ownerId,
183
+ callerId: caller.id,
184
+ callerType: caller.type,
185
+ ...(traceparent ? { traceparent } : {}),
186
+ ...(request.parentTaskId ? { parentTaskId: request.parentTaskId } : {}),
187
+ depth,
188
+ definition: instance.definition,
189
+ input: request.input,
190
+ correlationId: request.correlationId,
191
+ snapshot,
192
+ retryPolicy: definition.retryPolicy ?? DEFAULT_RETRY,
193
+ activation: 1,
194
+ attempt: 1,
195
+ ...(deadline ? { deadline } : {}),
196
+ ...(grantRef ? { grantRef } : {}),
197
+ ...(request.budget ? { budget: request.budget } : {}),
198
+ createdAt: now,
199
+ updatedAt: now,
200
+ };
201
+ try {
202
+ await this.o.store.transaction(async (tx) => {
203
+ await checkTaskQuota(tx, caller.tenantId, this.o.quotas?.(caller.tenantId), now);
204
+ // The fan-out is counted here, where the child is inserted: counted before the transaction, concurrent
205
+ // delegations would all see room (FIX-063). Reading one row past the limit is enough to know it is full.
206
+ if (parent) {
207
+ // A parent that ended in the meantime takes no new child (FIX-081): FEAT-070 ends the children it has when
208
+ // it ends, so a child accepted after that would never be cancelled. Re-read in the transaction that inserts
209
+ // the child: the check before it can be overtaken by the parent's cancel or a fenced handler's late call.
210
+ const live = await tx.get('tasks', parent.id);
211
+ if (!live)
212
+ throw new AgentropyError('NotFound', 'Parent task not found');
213
+ assertParentOpen(live.value);
214
+ const maxFanOut = this.o.limits?.maxFanOut ?? 20;
215
+ const children = await tx.find('tasks', {
216
+ where: { parentTaskId: parent.id },
217
+ limit: maxFanOut,
218
+ });
219
+ if (children.length >= maxFanOut)
220
+ throw new AgentropyError('FanOutExceeded', 'Delegation fan-out exceeded', { details: { children: children.length } });
221
+ }
222
+ // An instance made for this delegation (a definition target) is stored with the task, or not at all.
223
+ if (planned && !planned.stored)
224
+ await this.o.instances.insertPlanned(tx, planned.request, caller, instance);
225
+ // Fence against a concurrent suspend, drain or retire between the checks above and this commit.
226
+ const live = await tx.get('instances', instance.id);
227
+ if (!live || live.value.state !== 'available' || live.value.draining)
228
+ throw new AgentropyError('InstanceUnavailable', 'Target instance changed state during acceptance', {
229
+ details: {
230
+ reason: live?.value.draining
231
+ ? 'draining'
232
+ : (live?.value.state ?? 'missing'),
233
+ },
234
+ });
235
+ await tx.insert('idempotency', idemId, {
236
+ tenantId: caller.tenantId,
237
+ taskId,
238
+ fingerprint,
239
+ });
240
+ assertTransition(TASK_MACHINE, null, 'created', 'T1');
241
+ const created = await tx.insert('tasks', taskId, task);
242
+ await this.audit(tx, caller, {
243
+ type: 'task.accept',
244
+ action: 'delegation:delegate',
245
+ resource: { type: 'task', id: taskId },
246
+ decision: 'allow',
247
+ correlationId: task.correlationId,
248
+ taskId,
249
+ // Audit chain (D-15): who delegated, on whose behalf, and whether authority was narrowed.
250
+ details: {
251
+ callerType: caller.type,
252
+ ...(request.parentTaskId
253
+ ? { parentTaskId: request.parentTaskId }
254
+ : {}),
255
+ ...(caller.delegatedAuthorityRef
256
+ ? { narrowed: grantRef !== caller.delegatedAuthorityRef }
257
+ : {}),
258
+ },
259
+ });
260
+ await this.emit(tx, task, created.revision);
261
+ // T2: the instance is available, so bind it and queue the first execution in the same unit of work.
262
+ await this.transition(tx, created, 'assigned', 'T2');
263
+ await this.queueExecution(tx, taskId, 1, 1, 'delegation', now, caller.tenantId);
264
+ });
265
+ }
266
+ catch (err) {
267
+ // A concurrent duplicate won the idempotency insert: answer with its task.
268
+ const winner = await this.o.store.transaction((tx) => tx.get('idempotency', idemId));
269
+ let same = fingerprint;
270
+ if (winner && planned && !planned.stored) {
271
+ // The winner stored its own planned instance for this key: ours is not the one the request was made with.
272
+ const { instance: actual } = await this.o.instances.plan(planned.request, caller);
273
+ same = digestOf({
274
+ target: { instanceId: actual.id },
275
+ input: request.input,
276
+ parentTaskId: request.parentTaskId ?? null,
277
+ });
278
+ }
279
+ if (winner && winner.value.fingerprint === same)
280
+ return this.handleFor(winner.value.taskId);
281
+ throw err;
282
+ }
283
+ this.telemetry.count(METRICS.tasksAccepted, 1, {
284
+ 'agentropy.agent.id': definition.id,
285
+ 'agentropy.profile': definition.profile.id,
286
+ });
287
+ return handleOf(task);
288
+ }
289
+ /**
290
+ * One user message → one turn task on the caller's own conversational instance (Agent v1 "Conversation
291
+ * turn model"). The turn handler reads `conversation.briefing` and replies; it does not wait for children.
292
+ */
293
+ async submitTurn(turn, caller) {
294
+ if (!caller?.id || !caller.tenantId)
295
+ throw new AgentropyError('Unauthenticated', 'No trusted principal');
296
+ const instance = await this.o.instances.get(turn.instanceId, caller);
297
+ if (instance.ownerId !== caller.id)
298
+ throw new AgentropyError('NotFound', 'Conversational instance not found');
299
+ const definition = this.o.definitions.require(instance.definition);
300
+ if (definition.profile.id !== 'conversational')
301
+ throw new AgentropyError('UnsupportedOperation', 'Turns are only accepted by conversational agents', { details: { profile: definition.profile.id } });
302
+ return this.delegate({
303
+ target: { instanceId: instance.id },
304
+ input: { sessionId: turn.sessionId, text: turn.text },
305
+ idempotencyKey: `turn:${turn.idempotencyKey}`,
306
+ correlationId: turn.correlationId ?? randomUUID(),
307
+ }, caller);
308
+ }
309
+ /**
310
+ * Owner visibility (R-13, M2-05): tasks the caller delegated or owns (a trusted service sees its tenant), oldest
311
+ * first, or newest first with `newestFirst` (FIX-062), with an opaque cursor. `cursors[i]` resumes right after
312
+ * `tasks[i]`, so a caller that stops inside the page can continue from the item it stopped at. Other users' and
313
+ * tenants' tasks are never listed.
314
+ */
315
+ async listTasks(query, caller) {
316
+ if (!caller?.id || !caller.tenantId)
317
+ throw new AgentropyError('Unauthenticated', 'No trusted principal');
318
+ const newest = query.newestFirst === true;
319
+ // Oldest first, the cursor is the last `seq` read (0 at the start); newest first, the `seq` to read before.
320
+ const start = query.cursor ? Number(query.cursor) : newest ? undefined : 0;
321
+ if (start !== undefined &&
322
+ (!Number.isSafeInteger(start) || start < (newest ? 1 : 0)))
323
+ throw new AgentropyError('SchemaViolation', 'Invalid task cursor');
324
+ const limit = Math.min(Math.max(query.limit ?? 50, 1), 200);
325
+ // Read through the indexes: a trusted service sees the tenant; anyone else the tasks they delegated (callerId)
326
+ // or own (ownerId). Each source is read in pages of `limit`, so the work follows the page, not the history.
327
+ const base = {
328
+ tenantId: caller.tenantId,
329
+ ...(query.instanceId ? { instanceId: query.instanceId } : {}),
330
+ };
331
+ const sources = caller.type === 'service'
332
+ ? [base]
333
+ : [
334
+ { ...base, callerId: caller.id },
335
+ { ...base, ownerId: caller.id },
336
+ ];
337
+ const page = [];
338
+ const cursors = [];
339
+ let after = start;
340
+ while (page.length < limit) {
341
+ const { rows, exhausted } = await this.o.store.transaction(async (tx) => {
342
+ const merged = new Map();
343
+ let full = false;
344
+ for (const where of sources) {
345
+ const r = await tx.find('tasks', {
346
+ where,
347
+ orderBy: 'seq',
348
+ ...(newest
349
+ ? {
350
+ descending: true,
351
+ ...(after !== undefined ? { beforeSeq: after } : {}),
352
+ }
353
+ : { afterSeq: after ?? 0 }),
354
+ limit,
355
+ });
356
+ if (r.length === limit)
357
+ full = true;
358
+ for (const d of r)
359
+ merged.set(d.id, d);
360
+ }
361
+ const sorted = [...merged.values()].sort((a, b) => newest ? b.seq - a.seq : a.seq - b.seq);
362
+ // When a source filled its page, only the first `limit` rows of the union are known to be complete.
363
+ return {
364
+ rows: full ? sorted.slice(0, limit) : sorted,
365
+ exhausted: !full,
366
+ };
367
+ });
368
+ for (const d of rows) {
369
+ after = d.seq;
370
+ if (!query.status?.length || query.status.includes(d.value.status)) {
371
+ page.push(d);
372
+ cursors.push(String(d.seq));
373
+ }
374
+ if (page.length === limit)
375
+ break;
376
+ }
377
+ if (exhausted)
378
+ break;
379
+ }
380
+ return {
381
+ tasks: page.map((d) => toSnapshot(d.value, d.revision)),
382
+ // Newest first with nothing read, the cursor stays where it was (or empty: the start).
383
+ cursor: after === undefined ? '' : String(after),
384
+ cursors,
385
+ };
386
+ }
387
+ async getTask(taskId, caller) {
388
+ const doc = await this.visible(taskId, caller);
389
+ return toSnapshot(doc.value, doc.revision);
390
+ }
391
+ async getTaskByIdempotencyKey(key, caller) {
392
+ if (!caller?.id || !caller.tenantId)
393
+ throw new AgentropyError('Unauthenticated', 'No trusted principal');
394
+ const rec = await this.o.store.transaction((tx) => tx.get('idempotency', hashKey(caller.tenantId, caller.id, key)));
395
+ if (!rec)
396
+ throw new AgentropyError('NotFound', 'Task not found');
397
+ return this.getTask(rec.value.taskId, caller);
398
+ }
399
+ async getResult(taskId, caller) {
400
+ const { value: t } = await this.visible(taskId, caller);
401
+ if (t.status === 'completed')
402
+ return t.output;
403
+ if (t.status === 'failed')
404
+ throw new AgentropyError('TaskFailed', 'Task failed', {
405
+ details: { ...t.outcome },
406
+ });
407
+ if (t.status === 'cancelled')
408
+ throw new AgentropyError('TaskCancelled', 'Task cancelled', {
409
+ details: { ...t.outcome },
410
+ });
411
+ throw new AgentropyError('NotReady', 'Task has not completed');
412
+ }
413
+ async cancel(taskId, caller, reason = 'cancelled') {
414
+ await this.checkGrant(caller);
415
+ const doc = await this.visible(taskId, caller);
416
+ await enforcePolicy(this.o.pdp, {
417
+ principal: caller,
418
+ action: 'delegation:cancel',
419
+ resource: { type: 'task', id: taskId, tenantId: caller.tenantId },
420
+ });
421
+ const result = await this.o.store.transaction(async (tx) => {
422
+ const cur = (await tx.get('tasks', taskId));
423
+ const t = cur.value;
424
+ if (isTerminal(TASK_MACHINE, t.status))
425
+ throw new AgentropyError('InvalidState', `Task is ${t.status}`);
426
+ await this.audit(tx, caller, {
427
+ type: 'task.cancel',
428
+ action: 'delegation:cancel',
429
+ resource: { type: 'task', id: taskId },
430
+ decision: 'allow',
431
+ correlationId: t.correlationId,
432
+ taskId,
433
+ });
434
+ if (t.status === 'running')
435
+ return this.requestCancel(tx, cur, reason);
436
+ return this.terminate(tx, cur, 'cancelled', 'T10', {
437
+ code: 'Cancelled',
438
+ message: reason,
439
+ });
440
+ });
441
+ if (result.value.status === 'running')
442
+ for (const hook of this.cancelHooks)
443
+ hook(taskId);
444
+ void doc;
445
+ return toSnapshot(result.value, result.revision);
446
+ }
447
+ /**
448
+ * The cancel request of a running task: recorded on the task and announced. The worker running it sees the request
449
+ * through the store (its next heartbeat or tick) and stops the handler, and a result that arrives late is fenced.
450
+ */
451
+ async requestCancel(tx, cur, reason) {
452
+ if (cur.value.cancelRequestedAt)
453
+ return cur;
454
+ const next = {
455
+ ...cur.value,
456
+ cancelRequestedAt: this.o.now(),
457
+ updatedAt: this.o.now(),
458
+ };
459
+ const doc = await tx.update('tasks', cur.id, cur.revision, next);
460
+ await this.emit(tx, next, doc.revision, 'taskCancelRequested', { reason });
461
+ return doc;
462
+ }
463
+ /**
464
+ * A parent that was cancelled or failed takes its open children with it (Agent v1 revision 15): a child that is not
465
+ * running is cancelled at once (T10, its own children follow), a running child is asked to stop (the worker acts on
466
+ * it at its next heartbeat), and an open remote projection is marked so the next sync cancels it at the peer. The
467
+ * parent's own cancel was the audited act; this is the runtime carrying it out, like a deadline.
468
+ */
469
+ async endChildren(tx, parent, to) {
470
+ const reason = `parent task ${to}`;
471
+ for (const c of await tx.find('tasks', {
472
+ where: { parentTaskId: parent.id },
473
+ })) {
474
+ if (isTerminal(TASK_MACHINE, c.value.status))
475
+ continue;
476
+ if (c.value.status === 'running')
477
+ await this.requestCancel(tx, c, reason);
478
+ else
479
+ await this.terminate(tx, c, 'cancelled', 'T10', {
480
+ code: 'Cancelled',
481
+ message: reason,
482
+ });
483
+ }
484
+ const now = this.o.now();
485
+ for (const r of await tx.find('remoteTasks', {
486
+ where: { parentTaskId: parent.id },
487
+ })) {
488
+ if (isTerminal(TASK_MACHINE, r.value.status) || r.value.cancelRequestedAt)
489
+ continue;
490
+ await tx.update('remoteTasks', r.id, r.revision, {
491
+ ...r.value,
492
+ cancelRequestedAt: now,
493
+ nextSyncAt: now,
494
+ });
495
+ }
496
+ }
497
+ // --- internal helpers shared with the runtime -------------------------------------------------
498
+ async visible(taskId, caller) {
499
+ if (!caller?.id)
500
+ throw new AgentropyError('Unauthenticated', 'No trusted principal');
501
+ const doc = await this.o.store.transaction((tx) => tx.get('tasks', taskId));
502
+ // Authorization before state: an invisible task is NotFound, whatever its state (AC-04).
503
+ const t = doc?.value;
504
+ if (!doc ||
505
+ !t ||
506
+ t.tenantId !== caller.tenantId ||
507
+ !(t.callerId === caller.id ||
508
+ t.ownerId === caller.id ||
509
+ caller.type === 'service')) {
510
+ throw new AgentropyError('NotFound', 'Task not found');
511
+ }
512
+ return doc;
513
+ }
514
+ async checkGrant(caller) {
515
+ if (!caller.delegatedAuthorityRef || !this.o.grants)
516
+ return;
517
+ const status = await this.o.grants
518
+ .check(caller.delegatedAuthorityRef, caller.tenantId)
519
+ .catch(() => {
520
+ throw new AgentropyError('PolicyDecisionUnavailable', 'Grant status unavailable');
521
+ });
522
+ if (status !== 'valid')
523
+ throw new AgentropyError('AuthorityExpired', `Delegated authority ${status}`, { details: { status } });
524
+ }
525
+ /**
526
+ * D-08 delegation governance: an instance accepts work from its owner, principals the owner shared it with,
527
+ * agents whose own instance has the same owner (or a shared one), and trusted services. Everyone else in the
528
+ * tenant gets NotFound, so instance IDs do not reveal other users' agents. Policy (PDP) still applies after this.
529
+ */
530
+ async checkInstanceAccess(target, caller) {
531
+ if (caller.type === 'service' || caller.id === target.ownerId)
532
+ return;
533
+ const shared = target.sharedWith ?? [];
534
+ if (shared.includes(caller.id))
535
+ return;
536
+ if (caller.type === 'agent') {
537
+ const own = await this.o.store.transaction((tx) => tx.get('instances', caller.id));
538
+ const owner = own?.value.ownerId;
539
+ if (owner && (owner === target.ownerId || shared.includes(owner)))
540
+ return;
541
+ }
542
+ throw new AgentropyError('NotFound', 'Instance not found', {
543
+ details: { kind: 'instance' },
544
+ });
545
+ }
546
+ /**
547
+ * The visible target instance, and the caller's idempotency record when it could be read in the same
548
+ * transaction (`null` when it was not read).
549
+ */
550
+ async resolveTarget(request, caller, idemId) {
551
+ const instanceId = request.target.instanceId;
552
+ if (instanceId) {
553
+ const [doc, replay] = await this.o.store.transaction(async (tx) => [
554
+ await tx.get('instances', instanceId),
555
+ await tx.get('idempotency', idemId),
556
+ ]);
557
+ // AC-09: a target owned by another tenant is TenantMismatch; an unknown ID stays NotFound.
558
+ if (doc && doc.value.tenantId !== caller.tenantId)
559
+ throw new AgentropyError('TenantMismatch', 'Cross-tenant delegation denied');
560
+ if (!doc)
561
+ throw new AgentropyError('NotFound', 'Instance not found', {
562
+ details: { kind: 'instance' },
563
+ });
564
+ await this.checkInstanceAccess(doc.value, caller);
565
+ return { instance: doc.value, replay };
566
+ }
567
+ if (request.target.definition) {
568
+ const create = {
569
+ definition: request.target.definition,
570
+ ownerId: caller.id,
571
+ idempotencyKey: `auto:${request.idempotencyKey}`,
572
+ };
573
+ const { instance, stored } = await this.o.instances.plan(create, caller);
574
+ return {
575
+ instance,
576
+ replay: null,
577
+ planned: { request: create, stored },
578
+ };
579
+ }
580
+ throw new AgentropyError('SchemaViolation', 'Delegation target needs an instanceId or a definition');
581
+ }
582
+ async handleFor(taskId) {
583
+ const doc = (await this.o.store.transaction((tx) => tx.get('tasks', taskId)));
584
+ return handleOf(doc.value);
585
+ }
586
+ /** Mandatory audit intent in the caller's transaction (SEC-03); failure aborts it with AuditCommitUnavailable. */
587
+ async audit(tx, principal, event) {
588
+ await recordAuditIntent(tx, this.newId('audit'), {
589
+ ...event,
590
+ tenantId: principal.tenantId,
591
+ principalId: principal.id,
592
+ at: this.o.now(),
593
+ }, this.o.faults);
594
+ }
595
+ /**
596
+ * ADR-0024: a trusted principal re-establishes authority for a task held by the dispatch gate. Nothing is
597
+ * dispatched here; the next scheduler pass re-evaluates the gate with a fresh policy decision and the new grant.
598
+ */
599
+ async reauthorize(taskId, caller) {
600
+ await this.visible(taskId, caller);
601
+ await this.checkGrant(caller);
602
+ await enforcePolicy(this.o.pdp, {
603
+ principal: caller,
604
+ action: 'delegation:reauthorize',
605
+ resource: { type: 'task', id: taskId, tenantId: caller.tenantId },
606
+ });
607
+ await this.o.store.transaction(async (tx) => {
608
+ const task = (await tx.get('tasks', taskId));
609
+ const gate = await tx.get('gates', taskId);
610
+ if (!gate || isTerminal(TASK_MACHINE, task.value.status))
611
+ throw new AgentropyError('InvalidState', 'Task is not held by the dispatch gate', {
612
+ details: { kind: 'gate' },
613
+ });
614
+ const grantRef = caller.delegatedAuthorityRef ?? gate.value.grantRef;
615
+ await tx.update('gates', gate.id, gate.revision, {
616
+ ...gate.value,
617
+ nextCheckAt: this.o.now(),
618
+ attempt: 0,
619
+ ...(grantRef ? { grantRef } : {}),
620
+ });
621
+ await this.audit(tx, caller, {
622
+ type: 'task.reauthorize',
623
+ action: 'delegation:reauthorize',
624
+ resource: { type: 'task', id: taskId },
625
+ decision: 'allow',
626
+ correlationId: task.value.correlationId,
627
+ taskId,
628
+ });
629
+ });
630
+ }
631
+ /**
632
+ * Append one TaskEvent to the outbox in the caller's transaction. Without `type` it is the transition
633
+ * event for the status the task just entered (sequence 0); otherwise a non-transition event at the
634
+ * current revision with the next sequence number.
635
+ */
636
+ async emit(tx, t, revision, type, data) {
637
+ let sequence = 0;
638
+ if (type) {
639
+ // The task's newest event: at this revision it carries the highest sequence so far (the transition event is
640
+ // sequence 0), so the next one follows it. One row read, not the task's whole event history (FEAT-039.3).
641
+ const [latest] = await tx.find('outbox', {
642
+ where: { aggregateId: t.taskId },
643
+ orderBy: 'seq',
644
+ descending: true,
645
+ limit: 1,
646
+ });
647
+ sequence =
648
+ latest && latest.value.revision === revision
649
+ ? latest.value.sequence + 1
650
+ : 1;
651
+ }
652
+ const eventId = this.newId('event');
653
+ const record = {
654
+ eventId,
655
+ type: type ?? TRANSITION_EVENT[t.status],
656
+ aggregateId: t.taskId,
657
+ tenantId: t.tenantId,
658
+ revision,
659
+ sequence,
660
+ status: t.status,
661
+ occurredAt: this.o.now(),
662
+ ...(data !== undefined ? { data } : {}),
663
+ payload: {
664
+ status: t.status,
665
+ ...(t.outcome ? { outcome: t.outcome } : {}),
666
+ },
667
+ correlationId: t.correlationId,
668
+ published: 0,
669
+ attempts: 0,
670
+ };
671
+ await tx.insert('outbox', eventId, record);
672
+ return record;
673
+ }
674
+ async transition(tx, cur, to, edge, patch = {}) {
675
+ assertTransition(TASK_MACHINE, cur.value.status, to, edge);
676
+ const next = {
677
+ ...cur.value,
678
+ ...patch,
679
+ status: to,
680
+ updatedAt: this.o.now(),
681
+ };
682
+ const doc = await tx.update('tasks', cur.id, cur.revision, next);
683
+ await this.emit(tx, next, doc.revision);
684
+ return doc;
685
+ }
686
+ /** Terminal transition: aborts queued/leased executions (E7) and revokes wake-ups and subscriptions. */
687
+ async terminate(tx, cur, to, edge, outcome, output) {
688
+ const { waitingOn: _waiting, ...rest } = cur.value;
689
+ void _waiting;
690
+ const doc = await this.transition(tx, { ...cur, value: rest }, to, edge, {
691
+ ...(outcome ? { outcome } : {}),
692
+ ...(output !== undefined ? { output } : {}),
693
+ });
694
+ for (const e of await tx.find('executions', {
695
+ where: { taskId: cur.id },
696
+ })) {
697
+ if (e.value.state === 'queued' || e.value.state === 'leased') {
698
+ assertTransition(EXECUTION_MACHINE, e.value.state, 'aborted', 'E7');
699
+ await tx.update('executions', e.id, e.revision, {
700
+ ...e.value,
701
+ state: 'aborted',
702
+ endedAt: this.o.now(),
703
+ });
704
+ }
705
+ }
706
+ // A parent waiting on this child checks its wake-up on the next poll (FEAT-033.2).
707
+ if (cur.value.parentTaskId)
708
+ await pokeWakeups(tx, cur.value.parentTaskId, this.o.now());
709
+ for (const w of await tx.find('wakeups', {
710
+ where: { taskId: cur.id, status: 'armed' },
711
+ })) {
712
+ await tx.update('wakeups', w.id, w.revision, {
713
+ ...w.value,
714
+ status: 'revoked',
715
+ });
716
+ }
717
+ for (const s of await tx.find('subscriptions', {
718
+ where: { taskId: cur.id, status: 'active' },
719
+ })) {
720
+ await tx.update('subscriptions', s.id, s.revision, {
721
+ ...s.value,
722
+ status: 'revoked',
723
+ });
724
+ }
725
+ const gate = await tx.get('gates', cur.id);
726
+ if (gate)
727
+ await tx.remove('gates', gate.id, gate.revision);
728
+ // A draining instance retires when its last non-terminal task ends.
729
+ const inst = await tx.get('instances', cur.value.instanceId);
730
+ if (inst?.value.draining && inst.value.state !== 'retired') {
731
+ const others = await tx.find('tasks', {
732
+ where: { instanceId: cur.value.instanceId },
733
+ });
734
+ if (others.every((o) => o.id === cur.id || isTerminal(TASK_MACHINE, o.value.status))) {
735
+ assertTransition(INSTANCE_MACHINE, inst.value.state, 'retired');
736
+ await tx.update('instances', inst.id, inst.revision, {
737
+ ...inst.value,
738
+ state: 'retired',
739
+ revision: inst.value.revision + 1,
740
+ });
741
+ }
742
+ }
743
+ // Open human-action requests of a finished task can no longer be decided (H-revoke).
744
+ for (const a of await tx.find('humanActions', { where: { taskId: cur.id } })) {
745
+ if (a.value.status !== 'pending' && a.value.status !== 'claimed')
746
+ continue;
747
+ assertTransition(HUMAN_ACTION_MACHINE, a.value.status, 'revoked', 'H-revoke');
748
+ const revoked = await tx.update('humanActions', a.id, a.revision, {
749
+ ...a.value,
750
+ status: 'revoked',
751
+ });
752
+ await this.emit(tx, doc.value, doc.revision, 'humanActionResolved', {
753
+ requestId: a.value.requestId,
754
+ revision: revoked.revision,
755
+ outcome: 'revoked',
756
+ assignees: actionUsers(a.value, doc.value),
757
+ });
758
+ }
759
+ // Last, after the parent's own wake-ups are revoked: a child that ends pokes them, and the parent must not wake.
760
+ if (to !== 'completed')
761
+ await this.endChildren(tx, doc, to);
762
+ return doc;
763
+ }
764
+ async queueExecution(tx, taskId, activation, attempt, trigger, runAt,
765
+ /** The task's tenant when the caller already holds it; otherwise it is read. */
766
+ knownTenantId) {
767
+ assertTransition(EXECUTION_MACHINE, null, 'queued', 'E1');
768
+ const executionId = this.newId('execution');
769
+ const tenantId = knownTenantId ??
770
+ (await tx.get('tasks', taskId))?.value.tenantId;
771
+ await tx.insert('executions', executionId, {
772
+ executionId,
773
+ taskId,
774
+ ...(tenantId ? { tenantId } : {}),
775
+ activation,
776
+ attempt,
777
+ trigger,
778
+ state: 'queued',
779
+ runAt,
780
+ });
781
+ return executionId;
782
+ }
783
+ }
784
+ /** A child is accepted only under a parent that has not ended (Agent v1 revision 16, FIX-081). */
785
+ function assertParentOpen(parent) {
786
+ if (isTerminal(TASK_MACHINE, parent.status))
787
+ throw new AgentropyError('InvalidState', `Parent task is ${parent.status}`, {
788
+ details: { kind: 'parent', status: parent.status },
789
+ });
790
+ }