@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,523 @@
1
+ /**
2
+ * A2A server (inbound): maps A2A JSON-RPC methods onto a `DirectTarget` (e.g. `localAppTarget(app)`) with the
3
+ * principal produced by the transport's authentication, reusing the AgentService PEPs. `stream` serves
4
+ * `SendStreamingMessage` and `SubscribeToTask` (FEAT-029.1); `push` options enable push notifications (FEAT-029.2).
5
+ */
6
+ import { AgentropyError, toAgentropyError, validateAgentMessage, } from '@agentropy/core';
7
+ import { createActivationIngress } from './ingress.js';
8
+ import { A2A_PROTOCOL_VERSION, TERMINAL_A2A, TO_A2A, decodeParts, encodeInput, toA2ACode, } from './a2a-protocol.js';
9
+ import { createA2AHistory } from './a2a-history.js';
10
+ import { createPushNotifications } from './a2a-push.js';
11
+ const STREAMING_METHODS = new Set(['SendStreamingMessage', 'SubscribeToTask']);
12
+ const PUSH_METHODS = new Set([
13
+ 'CreateTaskPushNotificationConfig',
14
+ 'GetTaskPushNotificationConfig',
15
+ 'ListTaskPushNotificationConfigs',
16
+ 'DeleteTaskPushNotificationConfig',
17
+ ]);
18
+ /** A2A state of a task: waiting on a human action is `INPUT_REQUIRED`, other waits are `WORKING`. */
19
+ export function a2aState(s) {
20
+ return s.status === 'waiting' &&
21
+ s.waitingOn?.anyOf.some((c) => c.kind === 'human-action')
22
+ ? 'TASK_STATE_INPUT_REQUIRED'
23
+ : TO_A2A[s.status];
24
+ }
25
+ /** `ListTasks` page size: default and maximum (A2A 1.0 section 3.1.4). */
26
+ const LIST_DEFAULT = 50;
27
+ const LIST_MAX = 100;
28
+ /** Visible tasks scanned for one `ListTasks` call (`listScanLimit`). */
29
+ const LIST_SCAN = 10_000;
30
+ const A2A_STATES = new Set([
31
+ 'TASK_STATE_SUBMITTED',
32
+ 'TASK_STATE_WORKING',
33
+ 'TASK_STATE_INPUT_REQUIRED',
34
+ 'TASK_STATE_AUTH_REQUIRED',
35
+ 'TASK_STATE_COMPLETED',
36
+ 'TASK_STATE_FAILED',
37
+ 'TASK_STATE_CANCELED',
38
+ 'TASK_STATE_REJECTED',
39
+ ]);
40
+ /** Progress rank: a stream never reports a state behind one it already reported. */
41
+ const RANK = (s) => s === 'TASK_STATE_SUBMITTED' ? 0 : TERMINAL_A2A.has(s) ? 2 : 1;
42
+ export function createA2AServer(target, o = {}) {
43
+ const now = o.now ?? (() => new Date().toISOString());
44
+ const task = (s, contextId) => ({
45
+ id: s.taskId,
46
+ ...((contextId ?? s.correlationId)
47
+ ? { contextId: contextId ?? s.correlationId }
48
+ : {}),
49
+ status: {
50
+ state: a2aState(s),
51
+ timestamp: s.updatedAt ?? now(),
52
+ // The outcome tells the peer why a task failed or was cancelled; its code travels as metadata.
53
+ ...(s.outcome && (s.status === 'failed' || s.status === 'cancelled')
54
+ ? {
55
+ message: {
56
+ role: 'ROLE_AGENT',
57
+ messageId: `${s.taskId}:outcome`,
58
+ parts: [{ text: s.outcome.message }],
59
+ metadata: { 'agentropy/code': s.outcome.code },
60
+ },
61
+ }
62
+ : {}),
63
+ },
64
+ ...(s.status === 'completed' && s.output !== undefined
65
+ ? {
66
+ artifacts: [
67
+ { artifactId: `${s.taskId}:output`, parts: encodeInput(s.output) },
68
+ ],
69
+ }
70
+ : {}),
71
+ });
72
+ const history = o.history ? createA2AHistory(o.history) : undefined;
73
+ /** `historyLength`: unset keeps every message, 0 keeps none, n the n most recent (A2A 1.0). */
74
+ const historyLength = (v) => {
75
+ if (v === undefined)
76
+ return undefined;
77
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 0)
78
+ throw new AgentropyError('SchemaViolation', 'historyLength must be a non-negative integer');
79
+ return v;
80
+ };
81
+ /** The task with the caller's recorded messages, limited by `historyLength`. */
82
+ const view = async (s, caller, hl, contextId) => {
83
+ const t = task(s, contextId);
84
+ const h = history && hl !== 0 ? await history.read(caller, s.taskId, hl) : [];
85
+ return h.length ? { ...t, history: h } : t;
86
+ };
87
+ const failure = (id, status, code, err) => ({
88
+ status,
89
+ body: {
90
+ jsonrpc: '2.0',
91
+ id,
92
+ error: { code, message: err.message, data: err.toJSON() },
93
+ },
94
+ });
95
+ const mapped = (id, err) => {
96
+ const e = toAgentropyError(err);
97
+ const a2a = e.details?.['a2a'] ?? toA2ACode(e.code);
98
+ return failure(id, 200, a2a, e);
99
+ };
100
+ /** Authentication, version and request-shape checks shared by unary and streaming calls. */
101
+ const precheck = (req, principal, headers) => {
102
+ const id = req?.id ?? null;
103
+ if (!principal?.id || !principal.tenantId)
104
+ return failure(id, 401, -32600, new AgentropyError('Unauthenticated', 'Authentication required'));
105
+ const version = headers['a2a-version'];
106
+ if (version !== undefined && version !== A2A_PROTOCOL_VERSION)
107
+ return failure(id, 200, -32009, new AgentropyError('IncompatibleVersion', `A2A version ${version} is not supported`, { details: { supported: A2A_PROTOCOL_VERSION } }));
108
+ if (req?.jsonrpc !== '2.0' || typeof req.method !== 'string')
109
+ return failure(id, 200, -32600, new AgentropyError('SchemaViolation', 'Invalid JSON-RPC request'));
110
+ return undefined;
111
+ };
112
+ const userMessage = (p) => {
113
+ const m = p['message'];
114
+ if (!m?.messageId || m.role !== 'ROLE_USER')
115
+ throw new AgentropyError('SchemaViolation', 'message with messageId and ROLE_USER required');
116
+ return m;
117
+ };
118
+ /**
119
+ * A message with `taskId` continues that task (A2A 1.0 section 3.4): it must exist and be visible, must not be
120
+ * terminal, its `contextId` (when given) must match the task's, and the task must be waiting for input.
121
+ */
122
+ const continueMessage = async (m, principal) => {
123
+ const taskId = m.taskId;
124
+ const snap = await target.getTask(taskId, principal);
125
+ if (TERMINAL_A2A.has(TO_A2A[snap.status]))
126
+ throw new AgentropyError('UnsupportedOperation', 'Task is in a terminal state');
127
+ if (m.contextId && snap.correlationId && m.contextId !== snap.correlationId)
128
+ throw new AgentropyError('SchemaViolation', 'contextId does not match the task', { details: { reason: 'contextId' } });
129
+ if (!target.continueTask)
130
+ throw new AgentropyError('UnsupportedOperation', 'Continuing a task is not supported');
131
+ await target.continueTask(taskId, decodeParts(m.parts), m.messageId, principal);
132
+ return target.getTask(taskId, principal);
133
+ };
134
+ const delegateMessage = async (m, principal) => {
135
+ const input = decodeParts(m.parts);
136
+ const { taskId } = await target.delegate({
137
+ target: o.instanceId ? { instanceId: o.instanceId } : {},
138
+ input,
139
+ idempotencyKey: m.messageId,
140
+ correlationId: m.contextId ?? m.messageId,
141
+ }, principal);
142
+ return taskId;
143
+ };
144
+ /** Task frame, then forward-only status updates (the output artifact precedes `completed`) until terminal. */
145
+ async function* follow(id, first, principal, contextId, signal) {
146
+ const frame = (result) => ({
147
+ jsonrpc: '2.0',
148
+ id,
149
+ result,
150
+ });
151
+ const taskId = first.taskId;
152
+ // TaskStatusUpdateEvent/TaskArtifactUpdateEvent require context_id; without one the task ID stands in.
153
+ const ctx = { contextId: contextId ?? taskId };
154
+ let last = a2aState(first);
155
+ yield frame({ task: task(first, contextId) });
156
+ if (TERMINAL_A2A.has(last))
157
+ return;
158
+ /** Frames for a newly observed local status; none when it is not forward progress. */
159
+ async function* advance(status) {
160
+ if (!status || !(status in TO_A2A))
161
+ return;
162
+ // A wait may be for input: the task tells which.
163
+ const state = status === 'waiting'
164
+ ? a2aState(await target.getTask(taskId, principal))
165
+ : TO_A2A[status];
166
+ if (state === last || RANK(state) < RANK(last))
167
+ return;
168
+ last = state;
169
+ if (state === 'TASK_STATE_COMPLETED') {
170
+ const done = task(await target.getTask(taskId, principal), contextId);
171
+ for (const artifact of done.artifacts ?? [])
172
+ yield frame({
173
+ artifactUpdate: {
174
+ taskId,
175
+ ...ctx,
176
+ artifact,
177
+ append: false,
178
+ lastChunk: true,
179
+ },
180
+ });
181
+ }
182
+ yield frame({
183
+ statusUpdate: { taskId, ...ctx, status: { state, timestamp: now() } },
184
+ });
185
+ }
186
+ try {
187
+ for await (const e of target.subscribe(taskId, principal, signal ? { signal } : undefined)) {
188
+ yield* advance(e.payload?.status);
189
+ if (TERMINAL_A2A.has(last))
190
+ return;
191
+ }
192
+ if (signal?.aborted)
193
+ return;
194
+ // The event stream can end without its terminal event (e.g. compacted events): reconcile with the task.
195
+ yield* advance((await target.getTask(taskId, principal)).status);
196
+ }
197
+ catch (err) {
198
+ // An error after the stream opened ends it with a JSON-RPC error frame.
199
+ yield mapped(id, err).body;
200
+ }
201
+ }
202
+ /**
203
+ * A2A `ListTasks` over the tasks the caller may see on this endpoint: filtered by `contextId`, `status` and
204
+ * `statusTimestampAfter`, newest task first, with a cursor into the store (FIX-062).
205
+ * `historyLength` applies when the endpoint keeps history (`history` option); artifacts only with `includeArtifacts`.
206
+ */
207
+ const listTasks = async (p, caller) => {
208
+ if (!target.listTasks)
209
+ throw new AgentropyError('UnsupportedOperation', 'ListTasks is not supported');
210
+ const bad = (field) => new AgentropyError('SchemaViolation', `Invalid ${field}`, {
211
+ details: { reason: field },
212
+ });
213
+ const size = p['pageSize'] === undefined ? LIST_DEFAULT : p['pageSize'];
214
+ if (!Number.isInteger(size) ||
215
+ size < 1 ||
216
+ size > LIST_MAX)
217
+ throw bad('pageSize');
218
+ const status = p['status'];
219
+ if (status !== undefined &&
220
+ (typeof status !== 'string' || !A2A_STATES.has(status)))
221
+ throw bad('status');
222
+ const contextId = p['contextId'];
223
+ if (contextId !== undefined && typeof contextId !== 'string')
224
+ throw bad('contextId');
225
+ const afterRaw = p['statusTimestampAfter'];
226
+ const after = afterRaw === undefined ? undefined : Date.parse(String(afterRaw));
227
+ if (after !== undefined && Number.isNaN(after))
228
+ throw bad('statusTimestampAfter');
229
+ // The token is the store position to continue from and, after the first page, the count of matching tasks.
230
+ let cursor;
231
+ let known;
232
+ if (p['pageToken'] !== undefined && p['pageToken'] !== '') {
233
+ try {
234
+ const tok = JSON.parse(Buffer.from(String(p['pageToken']), 'base64url').toString('utf8'));
235
+ if (typeof tok.c !== 'string' || !tok.c)
236
+ throw new Error();
237
+ if (typeof tok.n !== 'number' || !Number.isSafeInteger(tok.n))
238
+ throw new Error();
239
+ cursor = tok.c;
240
+ known = tok.n;
241
+ }
242
+ catch {
243
+ throw bad('pageToken');
244
+ }
245
+ }
246
+ const hl = historyLength(p['historyLength']);
247
+ const scanLimit = Math.max(1, Math.floor(o.listScanLimit ?? LIST_SCAN));
248
+ const at = (t) => t.updatedAt ?? '';
249
+ // Newest task first (creation order, the order the store can page without reading the history). The first page
250
+ // reads on to count what matches; later pages stop as soon as one more than a page is known.
251
+ const matches = [];
252
+ let total = known ?? 0;
253
+ let scanned = 0;
254
+ let resume = cursor;
255
+ let exhausted = false;
256
+ scan: while (scanned < scanLimit) {
257
+ const asked = Math.min(200, scanLimit - scanned);
258
+ const r = await target.listTasks({
259
+ ...(o.instanceId ? { instanceId: o.instanceId } : {}),
260
+ ...(resume ? { cursor: resume } : {}),
261
+ newestFirst: true,
262
+ limit: asked,
263
+ }, caller);
264
+ for (const [i, t] of r.tasks.entries()) {
265
+ scanned++;
266
+ if ((contextId === undefined || t.correlationId === contextId) &&
267
+ (status === undefined || a2aState(t) === status) &&
268
+ (after === undefined || Date.parse(at(t)) >= after)) {
269
+ if (known === undefined)
270
+ total++;
271
+ if (matches.length <= size)
272
+ matches.push({ task: t, next: r.cursors[i] });
273
+ // A later page is full once one more match is known: continue after its last task, not after this batch.
274
+ if (known !== undefined && matches.length > size)
275
+ break scan;
276
+ }
277
+ }
278
+ resume = r.cursor || undefined;
279
+ if (r.tasks.length < asked) {
280
+ exhausted = true;
281
+ break;
282
+ }
283
+ }
284
+ const page = matches.slice(0, size).map((m) => m.task);
285
+ const more = matches.length > size;
286
+ // After a full page: right after its last task. Otherwise, if the scan stopped at its bound, where it stopped.
287
+ const nextCursor = more
288
+ ? matches[size - 1].next
289
+ : exhausted
290
+ ? undefined
291
+ : resume;
292
+ const tasks = await Promise.all(page.map(async (t) => {
293
+ let out;
294
+ if (p['includeArtifacts'] === true && t.status === 'completed')
295
+ out = task(await target.getTask(t.taskId, caller));
296
+ else {
297
+ const { artifacts: _omit, ...plain } = task(t);
298
+ void _omit;
299
+ out = plain;
300
+ }
301
+ const h = history && hl !== 0 ? await history.read(caller, t.taskId, hl) : [];
302
+ return h.length ? { ...out, history: h } : out;
303
+ }));
304
+ return {
305
+ tasks,
306
+ nextPageToken: nextCursor
307
+ ? Buffer.from(JSON.stringify({ c: nextCursor, n: total })).toString('base64url')
308
+ : '',
309
+ pageSize: size,
310
+ totalSize: total,
311
+ };
312
+ };
313
+ const notifications = createPushNotifications(target, o.push, follow);
314
+ return {
315
+ pushIdle: () => notifications.idle(),
316
+ resumePush: () => notifications.resume(),
317
+ async handle(raw, principal, headers = {}) {
318
+ const req = raw;
319
+ const id = req?.id ?? null;
320
+ const rejected = precheck(req, principal, headers);
321
+ if (rejected)
322
+ return rejected;
323
+ const caller = principal;
324
+ try {
325
+ const p = req.params ?? {};
326
+ switch (req.method) {
327
+ case 'SendMessage': {
328
+ const m = userMessage(p);
329
+ const envelope = m.metadata?.['agentropy/envelope'];
330
+ if (envelope !== undefined) {
331
+ // Agentropy envelope: identity always comes from the transport principal.
332
+ const msg = validateAgentMessage(envelope);
333
+ const { accepted } = await target.receive({
334
+ ...msg,
335
+ tenantId: caller.tenantId,
336
+ actor: {
337
+ principalId: caller.id,
338
+ principalType: caller.type,
339
+ },
340
+ }, caller);
341
+ return {
342
+ status: 200,
343
+ body: {
344
+ jsonrpc: '2.0',
345
+ id,
346
+ result: {
347
+ message: {
348
+ role: 'ROLE_AGENT',
349
+ messageId: `${m.messageId}:ack`,
350
+ parts: [
351
+ {
352
+ text: JSON.stringify({ accepted }),
353
+ mediaType: 'application/json',
354
+ },
355
+ ],
356
+ },
357
+ },
358
+ },
359
+ };
360
+ }
361
+ const hl = historyLength(p['configuration']
362
+ ?.historyLength);
363
+ const snap = m.taskId
364
+ ? await continueMessage(m, caller)
365
+ : await target.getTask(await delegateMessage(m, caller), caller);
366
+ await history?.record(caller, snap.taskId, m);
367
+ return {
368
+ status: 200,
369
+ body: {
370
+ jsonrpc: '2.0',
371
+ id,
372
+ result: { task: await view(snap, caller, hl, m.contextId) },
373
+ },
374
+ };
375
+ }
376
+ case 'GetTask': {
377
+ if (typeof p['id'] !== 'string')
378
+ throw new AgentropyError('SchemaViolation', 'id required');
379
+ const hl = historyLength(p['historyLength']);
380
+ const snap = await target.getTask(p['id'], caller);
381
+ return {
382
+ status: 200,
383
+ body: {
384
+ jsonrpc: '2.0',
385
+ id,
386
+ result: await view(snap, caller, hl),
387
+ },
388
+ };
389
+ }
390
+ case 'ListTasks':
391
+ return {
392
+ status: 200,
393
+ body: { jsonrpc: '2.0', id, result: await listTasks(p, caller) },
394
+ };
395
+ case 'CancelTask': {
396
+ if (typeof p['id'] !== 'string')
397
+ throw new AgentropyError('SchemaViolation', 'id required');
398
+ const snap = await target.cancel(p['id'], caller);
399
+ return {
400
+ status: 200,
401
+ body: { jsonrpc: '2.0', id, result: task(snap) },
402
+ };
403
+ }
404
+ default:
405
+ if (PUSH_METHODS.has(req.method))
406
+ return {
407
+ status: 200,
408
+ body: {
409
+ jsonrpc: '2.0',
410
+ id,
411
+ result: await notifications.method(req.method, p, caller),
412
+ },
413
+ };
414
+ if (STREAMING_METHODS.has(req.method))
415
+ throw new AgentropyError('UnsupportedOperation', `Method ${req.method} needs the streaming transport`);
416
+ return failure(id, 200, -32601, new AgentropyError('UnsupportedOperation', `Method ${req.method} not supported`));
417
+ }
418
+ }
419
+ catch (err) {
420
+ return mapped(id, err);
421
+ }
422
+ },
423
+ async stream(raw, principal, headers = {}, options = {}) {
424
+ const req = raw;
425
+ const id = req?.id ?? null;
426
+ const rejected = precheck(req, principal, headers);
427
+ if (rejected)
428
+ return { kind: 'error', response: rejected };
429
+ const caller = principal;
430
+ try {
431
+ const p = req.params ?? {};
432
+ switch (req.method) {
433
+ case 'SendStreamingMessage': {
434
+ const m = userMessage(p);
435
+ if (m.metadata?.['agentropy/envelope'] !== undefined)
436
+ throw new AgentropyError('UnsupportedOperation', 'Agentropy envelopes travel as SendMessage');
437
+ const first = m.taskId
438
+ ? await continueMessage(m, caller)
439
+ : await target.getTask(await delegateMessage(m, caller), caller);
440
+ return {
441
+ kind: 'stream',
442
+ status: 200,
443
+ frames: follow(id, first, caller, m.contextId, options.signal),
444
+ };
445
+ }
446
+ case 'SubscribeToTask': {
447
+ if (typeof p['id'] !== 'string')
448
+ throw new AgentropyError('SchemaViolation', 'id required');
449
+ const first = await target.getTask(p['id'], caller);
450
+ // Spec: subscribing to a task in a terminal state is UnsupportedOperationError.
451
+ if (TERMINAL_A2A.has(TO_A2A[first.status]))
452
+ throw new AgentropyError('UnsupportedOperation', 'Task is in a terminal state');
453
+ return {
454
+ kind: 'stream',
455
+ status: 200,
456
+ frames: follow(id, first, caller, undefined, options.signal),
457
+ };
458
+ }
459
+ default:
460
+ return {
461
+ kind: 'error',
462
+ response: failure(id, 200, -32601, new AgentropyError('UnsupportedOperation', `Method ${req.method} is not a streaming method`)),
463
+ };
464
+ }
465
+ }
466
+ catch (err) {
467
+ return { kind: 'error', response: mapped(id, err) };
468
+ }
469
+ },
470
+ };
471
+ }
472
+ /** Exposes one instance of a LocalApp as an A2A target (inbound), reusing every AgentService check. */
473
+ export function localAppTarget(app) {
474
+ const ingress = createActivationIngress(app);
475
+ return {
476
+ delegate: (request, caller) => app.delegate(request, caller),
477
+ getTask: async (taskId, caller) => {
478
+ const s = await app.getTask(taskId, caller);
479
+ if (s.status !== 'completed')
480
+ return s;
481
+ return {
482
+ ...s,
483
+ output: await app.getResult(taskId, caller),
484
+ };
485
+ },
486
+ cancel: (taskId, caller) => app.cancel(taskId, caller),
487
+ listTasks: (query, caller) => app.listTasks(query, caller),
488
+ continueTask: async (taskId, input, messageId, caller) => {
489
+ const snap = await app.getTask(taskId, caller);
490
+ const wait = snap.waitingOn?.anyOf.find((c) => c.kind === 'human-action');
491
+ if (snap.status !== 'waiting' || !wait || wait.kind !== 'human-action')
492
+ throw new AgentropyError('UnsupportedOperation', 'Task is not waiting for input');
493
+ const action = await app.getHumanAction(wait.requestId, caller);
494
+ await app.provideHumanInput({
495
+ requestId: wait.requestId,
496
+ expectedRevision: action.revision,
497
+ input,
498
+ idempotencyKey: messageId,
499
+ }, caller);
500
+ },
501
+ subscribe: (taskId, caller, options) => {
502
+ const stream = app.subscribe(taskId, caller, undefined, options);
503
+ return (async function* () {
504
+ for await (const e of stream)
505
+ yield {
506
+ eventId: `${taskId}:${e.revision}:${e.sequence}`,
507
+ taskId,
508
+ type: e.type,
509
+ revision: e.revision,
510
+ payload: { status: e.status },
511
+ };
512
+ })();
513
+ },
514
+ // Agentropy envelopes (`agent.delegate`, `agent.event`, `agent.callback`) take the activation ingress, which
515
+ // re-validates them and applies the same policy as any other ingress; a refusal reaches the peer typed.
516
+ receive: async (message, caller) => {
517
+ const r = await ingress.receive(message, caller);
518
+ if (r.status === 'rejected')
519
+ throw new AgentropyError(r.error.code, r.error.message);
520
+ return { accepted: true };
521
+ },
522
+ };
523
+ }
@@ -0,0 +1,5 @@
1
+ import type { A2AStreamFrame } from './a2a-server.js';
2
+ /** Server-Sent Events serialization of stream frames (`text/event-stream`). */
3
+ export declare function sseFrames(frames: AsyncIterable<A2AStreamFrame>): AsyncIterable<string>;
4
+ /** `data:` payloads of a `text/event-stream` body, one per event. */
5
+ export declare function sseData(body: AsyncIterable<Uint8Array | string>): AsyncIterable<string>;
@@ -0,0 +1,36 @@
1
+ /** Server-Sent Events framing for A2A streaming: serialization (server) and parsing (client). */
2
+ import { AgentropyError } from '@agentropy/core';
3
+ /** Server-Sent Events serialization of stream frames (`text/event-stream`). */
4
+ export async function* sseFrames(frames) {
5
+ for await (const f of frames)
6
+ yield `data: ${JSON.stringify(f)}\n\n`;
7
+ }
8
+ /** Largest single SSE event accepted from a peer. */
9
+ const MAX_SSE_EVENT = 1 << 20;
10
+ /** `data:` payloads of a `text/event-stream` body, one per event. */
11
+ export async function* sseData(body) {
12
+ const decoder = new TextDecoder();
13
+ let buf = '';
14
+ for await (const chunk of body) {
15
+ buf +=
16
+ typeof chunk === 'string'
17
+ ? chunk
18
+ : decoder.decode(chunk, { stream: true });
19
+ buf = buf.replace(/\r\n/g, '\n');
20
+ for (let i = buf.indexOf('\n\n'); i >= 0; i = buf.indexOf('\n\n')) {
21
+ const data = buf
22
+ .slice(0, i)
23
+ .split('\n')
24
+ .filter((l) => l.startsWith('data:'))
25
+ .map((l) => l.slice(5).replace(/^ /, ''))
26
+ .join('\n');
27
+ buf = buf.slice(i + 2);
28
+ if (data)
29
+ yield data;
30
+ }
31
+ if (buf.length > MAX_SSE_EVENT)
32
+ throw new AgentropyError('SchemaViolation', 'A2A stream event too large', {
33
+ details: { protocol: 'a2a', limit: MAX_SSE_EVENT },
34
+ });
35
+ }
36
+ }
package/dist/a2a.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * A2A provider (C-03, FEAT-027.8): JSON-RPC binding of the A2A protocol, pinned to protocol version 1.0
3
+ * (a2a-protocol.org specification 1.0.0; the normative field list is the spec's `a2a.proto`).
4
+ *
5
+ * - Outbound: `A2ACommunicationProvider` implements the Communication SPI for targets with an `endpoint`. It sends
6
+ * `SendMessage`, `GetTask` and `CancelTask` with the `A2A-Version` header and a credential resolved per call for
7
+ * this runtime's own service identity. Local grants never cross the boundary; the caller's identity is not
8
+ * forwarded as authority (threat model TM-27/TM-28). The remote task stays authoritative; local state is a
9
+ * normalized projection.
10
+ * - Inbound: `createA2AServer` maps the same methods onto a `DirectTarget` (e.g. `localAppTarget(app, …)`), with the
11
+ * principal produced by the transport's authentication. It reuses the AgentService PEPs.
12
+ *
13
+ * - Streaming (FEAT-029.1): `A2AServer.stream` serves `SendStreamingMessage` and `SubscribeToTask` as JSON-RPC
14
+ * `StreamResponse` frames (serialize with `sseFrames`). With `streaming: true` the provider's `subscribe` reads
15
+ * `SubscribeToTask` over SSE and falls back to polling `GetTask` when the peer declines or the stream breaks.
16
+ *
17
+ * - Push notifications (FEAT-029.2): with `push` options the server serves the four TaskPushNotificationConfig
18
+ * methods and POSTs each `StreamResponse` update to allow-listed webhook URLs (best-effort; configs in memory or,
19
+ * with `push.store`, stored and resumed, FEAT-034.3).
20
+ *
21
+ * HTTP: `createA2AHttpHandler` (a2a-http) serves an A2AServer on a Node `http` server: JSON-RPC POST, SSE for the
22
+ * streaming methods, the AgentCard at `/.well-known/agent-card.json`, principal from the application's
23
+ * `authenticate`.
24
+ *
25
+ * FEAT-034.4: `ListTasks` (the caller's tasks on this endpoint, newest status first, cursor pages), continuing a
26
+ * task waiting for input with a `message.taskId` (answers its human action), and A2A 1.0 parts (`text`, `raw`,
27
+ * `url`, `data`; several parts or file parts reach the agent as `{ parts }`, URLs are never fetched).
28
+ * Agentropy-to-Agentropy envelopes (`send`) travel as a `SendMessage` whose `metadata["agentropy/envelope"]`
29
+ * carries the AgentMessage; that key is an Agentropy extension, ignored by other peers.
30
+ *
31
+ * Modules (TASK-031): `a2a-protocol` (shapes and mappings), `a2a-server` (inbound), `a2a-push` (push
32
+ * notifications), `a2a-sse` (SSE framing), `a2a-http` (Node HTTP binding, FEAT-034.1) and `a2a-client` (outbound,
33
+ * AgentCard). This file re-exports their
34
+ * public API.
35
+ */
36
+ export { A2A_PROTOCOL_VERSION, type A2AMessage, type A2APart, type A2ATask, type A2ATaskState, } from './a2a-protocol.js';
37
+ export { createA2AServer, localAppTarget, type A2AHttpResponse, type A2AServer, type A2AServerOptions, type A2AStreamFrame, type A2AStreamResult, } from './a2a-server.js';
38
+ export type { A2APushConfig, A2APushFetch, A2APushOptions, A2ASecretSealer, } from './a2a-push.js';
39
+ export { sseFrames } from './a2a-sse.js';
40
+ export { AGENT_CARD_PATH, createA2AHttpHandler, type A2AHttpHandler, type A2AHttpOptions, } from './a2a-http.js';
41
+ export { A2ACommunicationProvider, a2aAgentCard, type A2AProviderOptions, } from './a2a-client.js';
package/dist/a2a.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * A2A provider (C-03, FEAT-027.8): JSON-RPC binding of the A2A protocol, pinned to protocol version 1.0
3
+ * (a2a-protocol.org specification 1.0.0; the normative field list is the spec's `a2a.proto`).
4
+ *
5
+ * - Outbound: `A2ACommunicationProvider` implements the Communication SPI for targets with an `endpoint`. It sends
6
+ * `SendMessage`, `GetTask` and `CancelTask` with the `A2A-Version` header and a credential resolved per call for
7
+ * this runtime's own service identity. Local grants never cross the boundary; the caller's identity is not
8
+ * forwarded as authority (threat model TM-27/TM-28). The remote task stays authoritative; local state is a
9
+ * normalized projection.
10
+ * - Inbound: `createA2AServer` maps the same methods onto a `DirectTarget` (e.g. `localAppTarget(app, …)`), with the
11
+ * principal produced by the transport's authentication. It reuses the AgentService PEPs.
12
+ *
13
+ * - Streaming (FEAT-029.1): `A2AServer.stream` serves `SendStreamingMessage` and `SubscribeToTask` as JSON-RPC
14
+ * `StreamResponse` frames (serialize with `sseFrames`). With `streaming: true` the provider's `subscribe` reads
15
+ * `SubscribeToTask` over SSE and falls back to polling `GetTask` when the peer declines or the stream breaks.
16
+ *
17
+ * - Push notifications (FEAT-029.2): with `push` options the server serves the four TaskPushNotificationConfig
18
+ * methods and POSTs each `StreamResponse` update to allow-listed webhook URLs (best-effort; configs in memory or,
19
+ * with `push.store`, stored and resumed, FEAT-034.3).
20
+ *
21
+ * HTTP: `createA2AHttpHandler` (a2a-http) serves an A2AServer on a Node `http` server: JSON-RPC POST, SSE for the
22
+ * streaming methods, the AgentCard at `/.well-known/agent-card.json`, principal from the application's
23
+ * `authenticate`.
24
+ *
25
+ * FEAT-034.4: `ListTasks` (the caller's tasks on this endpoint, newest status first, cursor pages), continuing a
26
+ * task waiting for input with a `message.taskId` (answers its human action), and A2A 1.0 parts (`text`, `raw`,
27
+ * `url`, `data`; several parts or file parts reach the agent as `{ parts }`, URLs are never fetched).
28
+ * Agentropy-to-Agentropy envelopes (`send`) travel as a `SendMessage` whose `metadata["agentropy/envelope"]`
29
+ * carries the AgentMessage; that key is an Agentropy extension, ignored by other peers.
30
+ *
31
+ * Modules (TASK-031): `a2a-protocol` (shapes and mappings), `a2a-server` (inbound), `a2a-push` (push
32
+ * notifications), `a2a-sse` (SSE framing), `a2a-http` (Node HTTP binding, FEAT-034.1) and `a2a-client` (outbound,
33
+ * AgentCard). This file re-exports their
34
+ * public API.
35
+ */
36
+ export { A2A_PROTOCOL_VERSION, } from './a2a-protocol.js';
37
+ export { createA2AServer, localAppTarget, } from './a2a-server.js';
38
+ export { sseFrames } from './a2a-sse.js';
39
+ export { AGENT_CARD_PATH, createA2AHttpHandler, } from './a2a-http.js';
40
+ export { A2ACommunicationProvider, a2aAgentCard, } from './a2a-client.js';