@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,183 @@
1
+ import { sseFrames } from './a2a-sse.js';
2
+ import { requestPath } from './http-path.js';
3
+ /** Well-known AgentCard path (A2A 1.0, section 8.2). */
4
+ export const AGENT_CARD_PATH = '/.well-known/agent-card.json';
5
+ const STREAMING = new Set(['SendStreamingMessage', 'SubscribeToTask']);
6
+ class BodyTooLarge extends Error {
7
+ }
8
+ function readBody(req, max) {
9
+ return new Promise((resolve, reject) => {
10
+ const declared = Number(req.headers['content-length']);
11
+ if (Number.isFinite(declared) && declared > max) {
12
+ req.resume();
13
+ return reject(new BodyTooLarge());
14
+ }
15
+ const chunks = [];
16
+ let size = 0;
17
+ req.on('data', (c) => {
18
+ size += c.length;
19
+ if (size > max) {
20
+ chunks.length = 0;
21
+ req.removeAllListeners('data');
22
+ req.resume();
23
+ reject(new BodyTooLarge());
24
+ }
25
+ else
26
+ chunks.push(c);
27
+ });
28
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
29
+ req.on('error', reject);
30
+ });
31
+ }
32
+ export function createA2AHttpHandler(server, o) {
33
+ const endpoint = o.path ?? '/a2a';
34
+ const maxBody = o.maxBodyBytes ?? 1 << 20;
35
+ const maxStreams = o.maxStreams ?? 100;
36
+ let streams = 0;
37
+ const json = (res, status, body, headers = {}) => {
38
+ res.writeHead(status, {
39
+ 'content-type': 'application/json',
40
+ 'cache-control': 'no-store',
41
+ ...headers,
42
+ });
43
+ res.end(JSON.stringify(body));
44
+ };
45
+ const rpcError = (res, status, id, code, message, headers = {}) => json(res, status, { jsonrpc: '2.0', id: id ?? null, error: { code, message } }, headers);
46
+ const send = (res, r) => json(res, r.status, r.body);
47
+ return {
48
+ openStreams: () => streams,
49
+ async handle(req, res) {
50
+ const path = requestPath(req.url);
51
+ if (path === undefined) {
52
+ req.resume();
53
+ json(res, 400, { error: 'bad request' });
54
+ return true;
55
+ }
56
+ if (path === AGENT_CARD_PATH && o.agentCard) {
57
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
58
+ json(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
59
+ return true;
60
+ }
61
+ json(res, 200, o.agentCard, { 'cache-control': 'max-age=300' });
62
+ return true;
63
+ }
64
+ if (path !== endpoint)
65
+ return false;
66
+ if (req.method !== 'POST') {
67
+ json(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
68
+ return true;
69
+ }
70
+ // Authenticate before reading anything: an unauthenticated caller costs a header check, not a body read.
71
+ const principal = await o.authenticate(req).catch(() => undefined);
72
+ if (!principal) {
73
+ req.resume();
74
+ // RFC 9110: a 401 names the scheme the caller must use.
75
+ rpcError(res, 401, null, -32600, 'Authentication required', {
76
+ 'www-authenticate': 'Bearer',
77
+ });
78
+ return true;
79
+ }
80
+ const type = String(req.headers['content-type'] ?? '');
81
+ if (!/^application\/(a2a\+)?json\s*(;|$)/i.test(type)) {
82
+ req.resume();
83
+ rpcError(res, 415, null, -32005, 'Content type must be application/json');
84
+ return true;
85
+ }
86
+ let raw;
87
+ try {
88
+ raw = await readBody(req, maxBody);
89
+ }
90
+ catch (err) {
91
+ if (err instanceof BodyTooLarge)
92
+ rpcError(res, 413, null, -32600, 'Request body too large', {
93
+ connection: 'close',
94
+ });
95
+ else
96
+ rpcError(res, 400, null, -32600, 'Request body unreadable');
97
+ return true;
98
+ }
99
+ let request;
100
+ try {
101
+ request = JSON.parse(raw);
102
+ }
103
+ catch {
104
+ rpcError(res, 200, null, -32700, 'Parse error');
105
+ return true;
106
+ }
107
+ const version = req.headers['a2a-version'];
108
+ const headers = typeof version === 'string' ? { 'a2a-version': version } : {};
109
+ const method = request?.method;
110
+ const id = request?.id;
111
+ try {
112
+ if (typeof method !== 'string' || !STREAMING.has(method)) {
113
+ send(res, await server.handle(request, principal, headers));
114
+ return true;
115
+ }
116
+ if (streams >= maxStreams) {
117
+ rpcError(res, 503, id, -32603, 'Too many open streams', {
118
+ 'retry-after': '1',
119
+ });
120
+ return true;
121
+ }
122
+ // The slot is taken before the stream is awaited: requests that arrive together all see the count they leave
123
+ // behind, so none can pass the limit while another is still opening (TASK-078). It is released on every way out.
124
+ streams++;
125
+ try {
126
+ // The client going away ends the stream and releases its task subscription.
127
+ const gone = new AbortController();
128
+ res.on('close', () => gone.abort());
129
+ const r = await server.stream(request, principal, headers, {
130
+ signal: gone.signal,
131
+ });
132
+ if (r.kind === 'error') {
133
+ send(res, r.response);
134
+ return true;
135
+ }
136
+ const ping = setInterval(() => {
137
+ if (!gone.signal.aborted)
138
+ res.write(': ping\n\n');
139
+ }, o.keepAliveMs ?? 15_000);
140
+ ping.unref();
141
+ try {
142
+ res.writeHead(200, {
143
+ 'content-type': 'text/event-stream',
144
+ 'cache-control': 'no-store',
145
+ connection: 'keep-alive',
146
+ });
147
+ for await (const event of sseFrames(r.frames)) {
148
+ if (gone.signal.aborted)
149
+ break;
150
+ // A slow reader is waited for (or its disconnect), not buffered without bound.
151
+ if (!res.write(event))
152
+ await new Promise((resolve) => {
153
+ const done = () => {
154
+ res.off('drain', done);
155
+ res.off('close', done);
156
+ resolve();
157
+ };
158
+ res.once('drain', done);
159
+ res.once('close', done);
160
+ });
161
+ }
162
+ }
163
+ finally {
164
+ clearInterval(ping);
165
+ res.end();
166
+ }
167
+ }
168
+ finally {
169
+ streams--;
170
+ }
171
+ return true;
172
+ }
173
+ catch {
174
+ // Never surface internals; the server already maps known errors into JSON-RPC responses.
175
+ if (res.headersSent)
176
+ res.end();
177
+ else
178
+ rpcError(res, 500, id, -32603, 'Internal error');
179
+ return true;
180
+ }
181
+ },
182
+ };
183
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * A2A protocol 1.0 shapes shared by the server and the client (TASK-031 split of `a2a.ts`): message, part and task
3
+ * types, state and error-code mappings, and part encoding.
4
+ */
5
+ import { type TaskSnapshot } from '@agentropy/core';
6
+ export declare const A2A_PROTOCOL_VERSION = "1.0";
7
+ export type A2ATaskState = 'TASK_STATE_SUBMITTED' | 'TASK_STATE_WORKING' | 'TASK_STATE_INPUT_REQUIRED' | 'TASK_STATE_AUTH_REQUIRED' | 'TASK_STATE_COMPLETED' | 'TASK_STATE_FAILED' | 'TASK_STATE_CANCELED' | 'TASK_STATE_REJECTED';
8
+ /** A2A 1.0 `Part`: exactly one of `text`, `raw` (base64 bytes), `url` or `data`. */
9
+ export interface A2APart {
10
+ text?: string;
11
+ raw?: string;
12
+ url?: string;
13
+ data?: unknown;
14
+ mediaType?: string;
15
+ filename?: string;
16
+ metadata?: Record<string, unknown>;
17
+ }
18
+ /**
19
+ * Input handed to an agent for a message that is not a single text or data part (FEAT-034.4). File content is
20
+ * passed as given (base64 or a URL); the runtime never fetches a URL, and agents treat all of it as data.
21
+ */
22
+ export type A2AInputPart = {
23
+ kind: 'text';
24
+ text: string;
25
+ mediaType?: string;
26
+ } | {
27
+ kind: 'file';
28
+ raw?: string;
29
+ url?: string;
30
+ filename?: string;
31
+ mediaType?: string;
32
+ } | {
33
+ kind: 'data';
34
+ data: unknown;
35
+ mediaType?: string;
36
+ };
37
+ /** Parts accepted in one message. */
38
+ export declare const MAX_PARTS = 16;
39
+ export interface A2AMessage {
40
+ role: 'ROLE_USER' | 'ROLE_AGENT';
41
+ messageId: string;
42
+ contextId?: string;
43
+ taskId?: string;
44
+ parts: A2APart[];
45
+ metadata?: Record<string, unknown>;
46
+ }
47
+ export interface A2ATask {
48
+ id: string;
49
+ contextId?: string;
50
+ status: {
51
+ state: A2ATaskState;
52
+ timestamp: string;
53
+ /** Why a task ended badly: the runtime's outcome message of a failed or cancelled task (TASK-035.3). */
54
+ message?: A2AMessage;
55
+ };
56
+ artifacts?: {
57
+ artifactId: string;
58
+ parts: A2APart[];
59
+ }[];
60
+ /** The caller's messages for this task, newest last (FEAT-044.2; only when the endpoint keeps history). */
61
+ history?: A2AMessage[];
62
+ metadata?: Record<string, unknown>;
63
+ }
64
+ export declare const TO_A2A: Record<TaskSnapshot['status'], A2ATaskState>;
65
+ export declare const FROM_A2A: Record<A2ATaskState, TaskSnapshot['status']>;
66
+ export declare const TERMINAL_A2A: Set<A2ATaskState>;
67
+ /** A2A JSON-RPC error codes (spec section 9) and the Errors v1 codes they correspond to. */
68
+ export declare const A2A_ERRORS: Record<number, string>;
69
+ export declare function toA2ACode(code: string): number;
70
+ export declare const encodeInput: (input: unknown) => A2APart[];
71
+ /** Validates one part and returns its input form. */
72
+ export declare function inputPart(p: A2APart): A2AInputPart;
73
+ /**
74
+ * Message parts as agent input: one text part is its text (JSON when `application/json`), one data part is its
75
+ * value; anything else (several parts, file parts) is `{ parts: A2AInputPart[] }`.
76
+ */
77
+ export declare function decodeParts(parts: A2APart[] | undefined): unknown;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * A2A protocol 1.0 shapes shared by the server and the client (TASK-031 split of `a2a.ts`): message, part and task
3
+ * types, state and error-code mappings, and part encoding.
4
+ */
5
+ import { AgentropyError } from '@agentropy/core';
6
+ export const A2A_PROTOCOL_VERSION = '1.0';
7
+ /** Parts accepted in one message. */
8
+ export const MAX_PARTS = 16;
9
+ export const TO_A2A = {
10
+ created: 'TASK_STATE_SUBMITTED',
11
+ assigned: 'TASK_STATE_SUBMITTED',
12
+ running: 'TASK_STATE_WORKING',
13
+ waiting: 'TASK_STATE_WORKING',
14
+ completed: 'TASK_STATE_COMPLETED',
15
+ failed: 'TASK_STATE_FAILED',
16
+ cancelled: 'TASK_STATE_CANCELED',
17
+ };
18
+ export const FROM_A2A = {
19
+ TASK_STATE_SUBMITTED: 'created',
20
+ TASK_STATE_WORKING: 'running',
21
+ TASK_STATE_INPUT_REQUIRED: 'waiting',
22
+ TASK_STATE_AUTH_REQUIRED: 'waiting',
23
+ TASK_STATE_COMPLETED: 'completed',
24
+ TASK_STATE_FAILED: 'failed',
25
+ TASK_STATE_CANCELED: 'cancelled',
26
+ TASK_STATE_REJECTED: 'failed',
27
+ };
28
+ export const TERMINAL_A2A = new Set([
29
+ 'TASK_STATE_COMPLETED',
30
+ 'TASK_STATE_FAILED',
31
+ 'TASK_STATE_CANCELED',
32
+ 'TASK_STATE_REJECTED',
33
+ ]);
34
+ /** A2A JSON-RPC error codes (spec section 9) and the Errors v1 codes they correspond to. */
35
+ export const A2A_ERRORS = {
36
+ [-32001]: 'NotFound', // TaskNotFoundError
37
+ [-32002]: 'InvalidState', // TaskNotCancelableError
38
+ [-32003]: 'UnsupportedOperation', // PushNotificationNotSupportedError
39
+ [-32004]: 'UnsupportedOperation', // UnsupportedOperationError
40
+ [-32005]: 'SchemaViolation', // ContentTypeNotSupportedError
41
+ [-32009]: 'IncompatibleVersion', // VersionNotSupportedError
42
+ [-32600]: 'SchemaViolation',
43
+ [-32601]: 'UnsupportedOperation',
44
+ [-32602]: 'SchemaViolation',
45
+ };
46
+ export function toA2ACode(code) {
47
+ switch (code) {
48
+ case 'NotFound':
49
+ case 'TenantMismatch':
50
+ return -32001;
51
+ case 'InvalidState':
52
+ return -32002;
53
+ case 'UnsupportedOperation':
54
+ return -32004;
55
+ case 'IncompatibleVersion':
56
+ return -32009;
57
+ case 'SchemaViolation':
58
+ return -32602;
59
+ default:
60
+ return -32603;
61
+ }
62
+ }
63
+ export const encodeInput = (input) => typeof input === 'string'
64
+ ? [{ text: input }]
65
+ : [{ text: JSON.stringify(input ?? null), mediaType: 'application/json' }];
66
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
67
+ function invalidPart(message) {
68
+ return new AgentropyError('SchemaViolation', message, {
69
+ details: { reason: 'parts' },
70
+ });
71
+ }
72
+ /** Validates one part and returns its input form. */
73
+ export function inputPart(p) {
74
+ if (typeof p !== 'object' || p === null)
75
+ throw invalidPart('Invalid part');
76
+ const present = ['text', 'raw', 'url', 'data'].filter((k) => p[k] !== undefined);
77
+ if (present.length !== 1)
78
+ throw invalidPart('A part has exactly one of text, raw, url or data');
79
+ for (const f of ['mediaType', 'filename'])
80
+ if (p[f] !== undefined && typeof p[f] !== 'string')
81
+ throw invalidPart(`Invalid ${f}`);
82
+ const meta = {
83
+ ...(p.mediaType ? { mediaType: p.mediaType } : {}),
84
+ };
85
+ switch (present[0]) {
86
+ case 'text':
87
+ if (typeof p.text !== 'string')
88
+ throw invalidPart('Invalid text part');
89
+ return { kind: 'text', text: p.text, ...meta };
90
+ case 'data':
91
+ return { kind: 'data', data: p.data, ...meta };
92
+ case 'raw':
93
+ if (typeof p.raw !== 'string' || !BASE64.test(p.raw))
94
+ throw invalidPart('raw must be base64');
95
+ return {
96
+ kind: 'file',
97
+ raw: p.raw,
98
+ ...(p.filename ? { filename: p.filename } : {}),
99
+ ...meta,
100
+ };
101
+ default: {
102
+ let u;
103
+ try {
104
+ u = new URL(String(p.url));
105
+ }
106
+ catch {
107
+ throw invalidPart('Invalid file url');
108
+ }
109
+ if (u.protocol !== 'https:' && u.protocol !== 'http:')
110
+ throw invalidPart('File url must be http or https');
111
+ return {
112
+ kind: 'file',
113
+ url: u.href,
114
+ ...(p.filename ? { filename: p.filename } : {}),
115
+ ...meta,
116
+ };
117
+ }
118
+ }
119
+ }
120
+ /**
121
+ * Message parts as agent input: one text part is its text (JSON when `application/json`), one data part is its
122
+ * value; anything else (several parts, file parts) is `{ parts: A2AInputPart[] }`.
123
+ */
124
+ export function decodeParts(parts) {
125
+ if (!Array.isArray(parts) || parts.length === 0)
126
+ throw invalidPart('A message needs at least one part');
127
+ if (parts.length > MAX_PARTS)
128
+ throw invalidPart(`At most ${MAX_PARTS} parts are accepted`);
129
+ const decoded = parts.map(inputPart);
130
+ if (decoded.length !== 1 || decoded[0].kind === 'file')
131
+ return { parts: decoded };
132
+ if (decoded[0].kind === 'data')
133
+ return decoded[0].data;
134
+ const [p] = parts;
135
+ if (p.mediaType === 'application/json') {
136
+ try {
137
+ return JSON.parse(p.text);
138
+ }
139
+ catch {
140
+ throw new AgentropyError('SchemaViolation', 'Invalid JSON part');
141
+ }
142
+ }
143
+ if (p.mediaType !== undefined && p.mediaType !== 'text/plain')
144
+ throw new AgentropyError('SchemaViolation', 'Unsupported content type', {
145
+ details: { reason: 'contentType', a2a: -32005 },
146
+ });
147
+ return p.text;
148
+ }
@@ -0,0 +1,24 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ /** The token a peer must present for one remote projection (`localTaskId`, e.g. `a2a:<remote id>`). */
3
+ export declare function a2aPushToken(secret: string, localTaskId: string): string;
4
+ export interface A2APushReceiverOptions {
5
+ /** The shared secret the provider's `push.secret` uses; at least 32 bytes. */
6
+ secret: string;
7
+ /** Refreshes one projection now, e.g. `(id) => app.refreshRemote(id)`. Failures are contained. */
8
+ refresh: (localTaskId: string) => Promise<unknown>;
9
+ /** Path prefix of the receiver (default `/a2a/push`); the task ID follows it, URL-encoded. */
10
+ path?: string;
11
+ /** Largest body accepted from a peer, in bytes (default 64 KiB); the body is read only to be discarded. */
12
+ maxBodyBytes?: number;
13
+ /** Minimum time between refreshes of one task (default 1,000 ms; 0 refreshes on every notification). */
14
+ minIntervalMs?: number;
15
+ }
16
+ export interface A2APushReceiver {
17
+ /** The answer to a notification for a task: `202` accepted (refresh scheduled or coalesced) or `401`. */
18
+ notify(localTaskId: string, token: string | undefined): Promise<202 | 401>;
19
+ /** Serves `POST <path>/<task id>`; `false` leaves the response untouched when the path is not the receiver's. */
20
+ handle(req: IncomingMessage, res: ServerResponse): Promise<boolean>;
21
+ /** Resolves once the refreshes started so far, and any trailing ones, have finished. */
22
+ idle(): Promise<void>;
23
+ }
24
+ export declare function createA2APushReceiver(o: A2APushReceiverOptions): A2APushReceiver;
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Receiving A2A push notifications for remote projections (FEAT-048; docs/plans/FEAT-048-outbound-push.md).
3
+ *
4
+ * A notification is a **wake-up signal, not data**. The receiver authenticates it with a per-task HMAC token, then asks
5
+ * the host to refresh that one projection (`LocalApp.refreshRemote`), which calls `GetTask` at the peer through the
6
+ * normal, validated path. The payload is never parsed, so a forged, replayed or hostile notification can cost one
7
+ * rate-limited `GetTask` and nothing more, and a lost one only means the slower polling runs.
8
+ *
9
+ * - **Token.** `a2aPushToken(secret, localTaskId)`: derived, never stored. The provider sends it to the peer when it
10
+ * registers the webhook; the peer returns it in `X-A2A-Notification-Token`. A token for one task is useless for
11
+ * another, and rotating the secret invalidates old tokens.
12
+ * - **Authenticate first.** The token is compared in constant time before the body is touched: a wrong or missing one
13
+ * is `401` and the body is drained unread. A valid notification's body is bounded (`413`) and discarded.
14
+ * - **Coalescing.** At most one refresh per task per `minIntervalMs` (default 1 s): the first runs at once and a burst
15
+ * is answered `202` and folded into one trailing refresh, so the last state is never lost.
16
+ */
17
+ import { createHmac, timingSafeEqual } from 'node:crypto';
18
+ import { AgentropyError } from '@agentropy/core';
19
+ import { requestPath } from './http-path.js';
20
+ /** Header the peer sends the token in (A2A 1.0 push notifications). */
21
+ const TOKEN_HEADER = 'x-a2a-notification-token';
22
+ const DEFAULT_PATH = '/a2a/push';
23
+ /** The token a peer must present for one remote projection (`localTaskId`, e.g. `a2a:<remote id>`). */
24
+ export function a2aPushToken(secret, localTaskId) {
25
+ return createHmac('sha256', secret)
26
+ .update(`agentropy/a2a-push/v1:${localTaskId}`)
27
+ .digest('base64url');
28
+ }
29
+ /** Entries kept for coalescing; a flood of distinct task IDs cannot grow it without limit. */
30
+ const MAX_TRACKED = 10_000;
31
+ export function createA2APushReceiver(o) {
32
+ if (Buffer.byteLength(o.secret, 'utf8') < 32)
33
+ throw new AgentropyError('InvalidConfiguration', 'The push receiver secret must be at least 32 bytes');
34
+ const base = (o.path ?? DEFAULT_PATH).replace(/\/+$/, '');
35
+ const maxBody = o.maxBodyBytes ?? 64 * 1024;
36
+ const minInterval = o.minIntervalMs ?? 1_000;
37
+ const state = new Map();
38
+ const inflight = new Set();
39
+ const run = (id) => {
40
+ const p = Promise.resolve()
41
+ .then(() => o.refresh(id))
42
+ .then(() => undefined, () => undefined)
43
+ .finally(() => inflight.delete(p));
44
+ inflight.add(p);
45
+ };
46
+ const authentic = (id, token) => {
47
+ if (typeof token !== 'string')
48
+ return false;
49
+ const want = Buffer.from(a2aPushToken(o.secret, id));
50
+ const got = Buffer.from(token);
51
+ return got.length === want.length && timingSafeEqual(got, want);
52
+ };
53
+ const notify = async (id, token) => {
54
+ if (!authentic(id, token))
55
+ return 401;
56
+ const now = Date.now();
57
+ let s = state.get(id);
58
+ if (!s) {
59
+ if (state.size >= MAX_TRACKED)
60
+ for (const [k, v] of state)
61
+ if (!v.trailing)
62
+ state.delete(k);
63
+ s = { last: Number.NEGATIVE_INFINITY };
64
+ state.set(id, s);
65
+ }
66
+ const elapsed = now - s.last;
67
+ if (elapsed >= minInterval) {
68
+ s.last = now;
69
+ run(id);
70
+ }
71
+ else if (!s.trailing) {
72
+ const entry = s;
73
+ entry.trailing = setTimeout(() => {
74
+ entry.trailing = undefined;
75
+ entry.last = Date.now();
76
+ run(id);
77
+ }, minInterval - elapsed);
78
+ entry.trailing.unref();
79
+ }
80
+ return 202;
81
+ };
82
+ const reply = (res, status, headers = {}) => {
83
+ res.writeHead(status, {
84
+ 'content-type': 'application/json',
85
+ 'cache-control': 'no-store',
86
+ ...headers,
87
+ });
88
+ res.end('{}');
89
+ };
90
+ /** Reads and throws away a body up to the bound; false when it is larger. */
91
+ const discard = (req) => new Promise((resolve) => {
92
+ let size = 0;
93
+ req.on('data', (c) => {
94
+ size += c.length;
95
+ if (size > maxBody) {
96
+ req.removeAllListeners('data');
97
+ req.resume();
98
+ resolve(false);
99
+ }
100
+ });
101
+ req.on('end', () => resolve(true));
102
+ req.on('error', () => resolve(false));
103
+ });
104
+ return {
105
+ notify,
106
+ async handle(req, res) {
107
+ const path = requestPath(req.url);
108
+ // Not a valid request target: nobody's path, answered here instead of thrown at the host (FIX-049).
109
+ if (path === undefined) {
110
+ req.resume();
111
+ reply(res, 400);
112
+ return true;
113
+ }
114
+ if (!path.startsWith(`${base}/`))
115
+ return false;
116
+ let id;
117
+ try {
118
+ id = decodeURIComponent(path.slice(base.length + 1));
119
+ }
120
+ catch {
121
+ return false;
122
+ }
123
+ if (!id)
124
+ return false;
125
+ if (req.method !== 'POST') {
126
+ req.resume();
127
+ reply(res, 405, { allow: 'POST' });
128
+ return true;
129
+ }
130
+ const header = req.headers[TOKEN_HEADER];
131
+ const token = Array.isArray(header) ? header[0] : header;
132
+ // Authenticate before reading anything: a forged notification costs a header check, not a body read.
133
+ if (!authentic(id, token)) {
134
+ req.resume();
135
+ reply(res, 401, { connection: 'close' });
136
+ return true;
137
+ }
138
+ const declared = Number(req.headers['content-length']);
139
+ if (Number.isFinite(declared) && declared > maxBody) {
140
+ req.resume();
141
+ reply(res, 413, { connection: 'close' });
142
+ return true;
143
+ }
144
+ if (!(await discard(req))) {
145
+ reply(res, 413, { connection: 'close' });
146
+ return true;
147
+ }
148
+ reply(res, await notify(id, token));
149
+ return true;
150
+ },
151
+ async idle() {
152
+ for (;;) {
153
+ while (inflight.size)
154
+ await Promise.all([...inflight]);
155
+ if (![...state.values()].some((s) => s.trailing))
156
+ return;
157
+ await new Promise((r) => setTimeout(r, 5));
158
+ }
159
+ },
160
+ };
161
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * A2A push notifications (FEAT-029.2): the four TaskPushNotificationConfig methods and best-effort delivery of
3
+ * every `StreamResponse` update to allow-listed webhook URLs. Configs are scoped to tenant + creating principal +
4
+ * task. They live in memory, or in a store (FEAT-034.3): then they survive a restart, `resume()` restarts their
5
+ * watchers and catches a webhook up on a state change it missed, and webhook secrets are stored only sealed.
6
+ * Deleting a config ends its watcher and releases its task subscription at once.
7
+ */
8
+ import { type Store, type TaskSnapshot, type TrustedPrincipal } from '@agentropy/core';
9
+ import type { DirectTarget } from './communication.js';
10
+ import type { A2AStreamFrame } from './a2a-server.js';
11
+ /** Push delivery transport; `redirect: 'manual'` keeps a webhook from bouncing deliveries elsewhere. */
12
+ export type A2APushFetch = (url: string, init: {
13
+ method: 'POST';
14
+ headers: Record<string, string>;
15
+ body: string;
16
+ redirect: 'manual';
17
+ /** Aborts at `timeoutMs`: a webhook that never answers must not hold the watcher. */
18
+ signal: AbortSignal;
19
+ }) => Promise<{
20
+ status: number;
21
+ body?: {
22
+ cancel(): Promise<unknown>;
23
+ } | null;
24
+ }>;
25
+ export interface A2APushOptions {
26
+ /**
27
+ * Required SSRF guard: a webhook URL is accepted only when this admits it (match exact origins; never admit
28
+ * internal addresses a client could name). URLs with embedded credentials are always refused.
29
+ */
30
+ allowUrl: (url: URL) => boolean;
31
+ /** Admit `http:` URLs (default false: `https:` only). */
32
+ allowHttp?: boolean;
33
+ fetch?: A2APushFetch;
34
+ /** Attempts per notification (default 3); 5xx, 429 and transport errors are retried with doubling backoff. */
35
+ maxAttempts?: number;
36
+ /** Time one delivery attempt may take before it is aborted and counted as failed (default 10 s). */
37
+ timeoutMs?: number;
38
+ /** First retry delay in ms (default 200). */
39
+ retryMs?: number;
40
+ /** Configs one principal may hold per task (default 10). */
41
+ maxConfigsPerTask?: number;
42
+ /**
43
+ * Keep configs in this store so they survive a restart; call `A2AServer.resumePush()` when the server starts.
44
+ * Every server that resumes delivers, so with several servers a webhook may get an update more than once.
45
+ */
46
+ store?: Store;
47
+ /**
48
+ * Seals webhook secrets (`token`, `authentication.credentials`) before they are stored, e.g. with a KMS key. With
49
+ * a store and no sealer, configs that carry secrets are refused: secrets are never stored in the clear.
50
+ */
51
+ sealer?: A2ASecretSealer;
52
+ /** Called when a notification is given up on; delivery is best-effort and never fails the task. */
53
+ onDeliveryError?: (e: {
54
+ taskId: string;
55
+ configId: string;
56
+ status?: number;
57
+ }) => void;
58
+ }
59
+ /** Seals and opens webhook secrets at rest (FEAT-034.3). */
60
+ export interface A2ASecretSealer {
61
+ seal(plain: string): Promise<string>;
62
+ open(sealed: string): Promise<string>;
63
+ }
64
+ /** A2A `TaskPushNotificationConfig` (credentials are write-only: reads return the scheme alone). */
65
+ export interface A2APushConfig {
66
+ id: string;
67
+ taskId: string;
68
+ url: string;
69
+ token?: string;
70
+ authentication?: {
71
+ scheme: string;
72
+ credentials?: string;
73
+ };
74
+ }
75
+ /** Push config methods and watchers for one server. */
76
+ export declare function createPushNotifications(target: DirectTarget, options: A2APushOptions | undefined, follow: (id: unknown, first: TaskSnapshot, principal: TrustedPrincipal, contextId?: string, signal?: AbortSignal) => AsyncIterable<A2AStreamFrame>): {
77
+ method: (method: string, p: Record<string, unknown>, caller: TrustedPrincipal) => Promise<unknown>;
78
+ /**
79
+ * Restarts a watcher for every stored config whose task is still live and whose creator can still see it.
80
+ * Returns how many were started.
81
+ */
82
+ resume(): Promise<number>;
83
+ /** Resolves once every watcher has finished. */
84
+ idle(): Promise<void>;
85
+ };