@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,386 @@
1
+ /**
2
+ * A2A client (outbound): `A2ACommunicationProvider` implements the Communication SPI for targets with an
3
+ * `endpoint`, and `a2aAgentCard` builds the AgentCard a server publishes.
4
+ *
5
+ * The provider calls only endpoints its `allowEndpoint` list admits (FIX-054): a delegation target can name any
6
+ * address (a handler supplies it), and the call carries this runtime's credential, so an address outside the list
7
+ * is refused with `PermissionDenied` before the credential is looked up and before any request is made.
8
+ */
9
+ import { a2aPushToken } from './a2a-push-receiver.js';
10
+ import { AgentropyError, isAgentropyError, isErrorCode, validateAgentMessage, } from '@agentropy/core';
11
+ import { A2A_ERRORS, A2A_PROTOCOL_VERSION, FROM_A2A, TERMINAL_A2A, decodeParts, encodeInput, } from './a2a-protocol.js';
12
+ import { sseData } from './a2a-sse.js';
13
+ import { ReplyNotJson, ReplyTooLarge, readBoundedJson, } from './bounded-body.js';
14
+ /** Error codes only this runtime may raise about its own authority; from a peer they become `RemoteUnavailable`. */
15
+ const LOCAL_ONLY = new Set([
16
+ 'AuthorityExpired',
17
+ 'PolicyDecisionUnavailable',
18
+ ]);
19
+ /** Validates `push` and returns the base URL a webhook is registered under (no trailing slash). */
20
+ function pushBase(p) {
21
+ if (Buffer.byteLength(p.secret, 'utf8') < 32)
22
+ throw new AgentropyError('InvalidConfiguration', 'push.secret must be at least 32 bytes');
23
+ let u;
24
+ try {
25
+ u = new URL(p.publicUrl);
26
+ }
27
+ catch {
28
+ throw new AgentropyError('InvalidConfiguration', 'push.publicUrl is not a URL');
29
+ }
30
+ if (u.protocol !== 'https:' && !(p.allowHttp && u.protocol === 'http:'))
31
+ throw new AgentropyError('InvalidConfiguration', 'push.publicUrl must be https (or http with allowHttp)');
32
+ if (u.username || u.password || u.search || u.hash)
33
+ throw new AgentropyError('InvalidConfiguration', 'push.publicUrl must not carry credentials, a query or a fragment');
34
+ const path = (p.path ?? '/a2a/push').replace(/\/+$/, '');
35
+ return `${u.origin}${u.pathname.replace(/\/+$/, '')}${path}`;
36
+ }
37
+ export class A2ACommunicationProvider {
38
+ o;
39
+ id = 'a2a';
40
+ features;
41
+ seq = 0;
42
+ pushUrl;
43
+ constructor(o) {
44
+ this.o = o;
45
+ // Enforced at run time too: a plain JavaScript caller, or a test that is not type checked, must not get a
46
+ // provider that calls any address.
47
+ if (typeof o?.allowEndpoint !== 'function')
48
+ throw new AgentropyError('InvalidConfiguration', 'A2ACommunicationProvider needs allowEndpoint, the list of endpoints it may call', { details: { field: 'allowEndpoint' } });
49
+ this.pushUrl = o.push ? pushBase(o.push) : undefined;
50
+ this.features = {
51
+ operations: ['delegate', 'send', 'getTask', 'cancel', 'subscribe'],
52
+ streaming: o.streaming === true,
53
+ pushNotifications: o.push !== undefined,
54
+ durability: 'provider-dependent',
55
+ protocol: 'a2a',
56
+ protocolVersion: A2A_PROTOCOL_VERSION,
57
+ };
58
+ }
59
+ supports(target, operation) {
60
+ return !!target.endpoint && this.features.operations.includes(operation);
61
+ }
62
+ /**
63
+ * The endpoint as a URL the list admits, or `PermissionDenied` (`details.reason: "endpoint"`). The address came from
64
+ * an agent or a registry, so it is not echoed into the error. Every outbound request goes through here.
65
+ */
66
+ admit(endpoint) {
67
+ const denied = () => new AgentropyError('PermissionDenied', 'The remote endpoint is not allowed', {
68
+ details: { reason: 'endpoint' },
69
+ });
70
+ let url;
71
+ try {
72
+ url = new URL(endpoint);
73
+ }
74
+ catch {
75
+ throw denied();
76
+ }
77
+ const scheme = url.protocol === 'https:' ||
78
+ (url.protocol === 'http:' && this.o.allowHttp === true);
79
+ if (!scheme || url.username || url.password)
80
+ throw denied();
81
+ let admitted;
82
+ try {
83
+ admitted = this.o.allowEndpoint(new URL(url.href)) === true;
84
+ }
85
+ catch {
86
+ admitted = false; // a list that cannot answer admits nothing
87
+ }
88
+ if (!admitted)
89
+ throw denied();
90
+ return url;
91
+ }
92
+ async call(endpoint, method, params, ctx) {
93
+ const res = await this.post(endpoint, method, params, ctx);
94
+ return this.result(await this.readJson(res, ctx));
95
+ }
96
+ /** The reply as JSON under the size cap, or `RemoteUnavailable`: a peer's reply never fails as `Internal`. */
97
+ async readJson(res, ctx) {
98
+ try {
99
+ return await readBoundedJson(res, this.o.maxResponseBytes ?? 4 * 1024 * 1024, ctx.signal);
100
+ }
101
+ catch (err) {
102
+ throw new AgentropyError('RemoteUnavailable', err instanceof ReplyTooLarge
103
+ ? 'A2A reply is too large'
104
+ : err instanceof ReplyNotJson
105
+ ? 'A2A peer sent a reply that is not JSON'
106
+ : 'A2A reply could not be read', { details: { protocol: 'a2a' } });
107
+ }
108
+ }
109
+ async post(endpoint, method, params, ctx, accept = 'application/json') {
110
+ // Before anything else: no credential lookup and no request for an endpoint the list does not admit.
111
+ const url = this.admit(endpoint);
112
+ const headers = {
113
+ 'content-type': 'application/json',
114
+ accept,
115
+ 'a2a-version': A2A_PROTOCOL_VERSION,
116
+ };
117
+ if (this.o.credentialRef) {
118
+ if (!this.o.credentials)
119
+ throw new AgentropyError('InvalidConfiguration', 'credentialRef needs a CredentialProvider');
120
+ const cred = (await this.o.credentials.resolve(this.o.credentialRef, {
121
+ tenantId: ctx.caller.tenantId,
122
+ principal: ctx.caller,
123
+ purpose: 'a2a',
124
+ }));
125
+ if (!cred?.token)
126
+ throw new AgentropyError('AuthorityExpired', 'A2A credential unavailable', {
127
+ details: { kind: 'credential', status: 'expired' },
128
+ });
129
+ headers.authorization = `Bearer ${cred.token}`;
130
+ }
131
+ let res;
132
+ try {
133
+ res = await (this.o.fetch ??
134
+ ((u, i) => fetch(u, i)))(url.href, {
135
+ method: 'POST',
136
+ headers,
137
+ body: JSON.stringify({
138
+ jsonrpc: '2.0',
139
+ id: `rpc-${++this.seq}`,
140
+ method,
141
+ params,
142
+ }),
143
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
144
+ redirect: 'manual',
145
+ });
146
+ }
147
+ catch (err) {
148
+ if (isAgentropyError(err))
149
+ throw err;
150
+ throw new AgentropyError('RemoteUnavailable', 'A2A peer unreachable', {
151
+ details: { protocol: 'a2a' },
152
+ });
153
+ }
154
+ // An error reply's body is never read: release its connection (a real fetch Response holds it until read).
155
+ const redirected = res.status >= 300 && res.status < 400;
156
+ if (res.status === 401 ||
157
+ res.status === 403 ||
158
+ res.status >= 500 ||
159
+ redirected)
160
+ void res.body
161
+ ?.cancel?.()
162
+ ?.catch(() => undefined);
163
+ // The endpoint was admitted, the place it points to may not be: a redirect is not followed (FIX-054).
164
+ if (redirected)
165
+ throw new AgentropyError('RemoteUnavailable', 'A2A peer redirected', {
166
+ details: { status: res.status },
167
+ });
168
+ if (res.status === 401 || res.status === 403)
169
+ throw new AgentropyError('AuthorityExpired', 'A2A peer rejected our credential', {
170
+ details: { kind: 'credential', status: 'expired' },
171
+ });
172
+ if (res.status >= 500)
173
+ throw new AgentropyError('RemoteUnavailable', 'A2A peer error', {
174
+ details: { status: res.status },
175
+ });
176
+ return res;
177
+ }
178
+ /** The JSON-RPC result, or the peer's error mapped to a typed code. */
179
+ result(raw) {
180
+ const body = raw;
181
+ if (body.error) {
182
+ // Prefer an Agentropy peer's typed code; otherwise map the A2A code. Remote messages are not trusted text.
183
+ const fromPeer = body.error.data?.code;
184
+ const peerCode = fromPeer && isErrorCode(fromPeer)
185
+ ? fromPeer
186
+ : (A2A_ERRORS[body.error.code ?? 0] ?? 'RemoteUnavailable');
187
+ // Lost authority and a policy outage mean something to the local runtime (a task parks behind the dispatch
188
+ // gate). A peer's claim of them is about the peer, never about local authority (FEAT-038.4).
189
+ const code = LOCAL_ONLY.has(peerCode) ? 'RemoteUnavailable' : peerCode;
190
+ throw new AgentropyError(code, `A2A peer error ${body.error.code ?? ''}`.trim(), {
191
+ details: { protocol: 'a2a', a2aCode: body.error.code ?? null },
192
+ });
193
+ }
194
+ return body.result;
195
+ }
196
+ now() {
197
+ return this.o.now?.() ?? new Date().toISOString();
198
+ }
199
+ state(t) {
200
+ const parts = t.artifacts?.[0]?.parts;
201
+ let output;
202
+ if (t.status.state === 'TASK_STATE_COMPLETED' && parts?.length === 1) {
203
+ try {
204
+ output = decodeParts(parts);
205
+ }
206
+ catch {
207
+ output = undefined; // an unreadable artifact is not a result
208
+ }
209
+ }
210
+ return {
211
+ remoteState: t.status.state,
212
+ normalized: FROM_A2A[t.status.state] ?? 'unknown',
213
+ observedAt: this.now(),
214
+ ...(output !== undefined ? { output } : {}),
215
+ };
216
+ }
217
+ async delegate(route, request, ctx) {
218
+ const endpoint = route.target.endpoint;
219
+ const result = await this.call(endpoint, 'SendMessage', {
220
+ message: {
221
+ role: 'ROLE_USER',
222
+ messageId: request.idempotencyKey,
223
+ contextId: request.correlationId,
224
+ parts: encodeInput(request.input),
225
+ },
226
+ configuration: { returnImmediately: true },
227
+ }, ctx);
228
+ if (!result?.task?.id)
229
+ throw new AgentropyError('RemoteUnavailable', 'A2A peer did not return a task');
230
+ // Remote task mapping: the local projection is keyed by protocol + remote ID; the remote stays authoritative.
231
+ const localTaskId = `a2a:${result.task.id}`;
232
+ if (this.o.push && this.pushUrl)
233
+ try {
234
+ // A hint on top of polling: any failure (no push at the peer, a refusal, the network) is ignored.
235
+ await this.call(endpoint, 'CreateTaskPushNotificationConfig', {
236
+ taskId: result.task.id,
237
+ id: 'agentropy',
238
+ url: `${this.pushUrl}/${encodeURIComponent(localTaskId)}`,
239
+ token: a2aPushToken(this.o.push.secret, localTaskId),
240
+ }, ctx);
241
+ }
242
+ catch {
243
+ // polling stays the fallback
244
+ }
245
+ return { localTaskId, route, remoteTaskId: result.task.id };
246
+ }
247
+ async send(route, message, ctx) {
248
+ validateAgentMessage(message);
249
+ const trusted = {
250
+ ...message,
251
+ tenantId: ctx.caller.tenantId,
252
+ actor: { principalId: ctx.caller.id, principalType: ctx.caller.type },
253
+ };
254
+ const result = await this.call(route.target.endpoint, 'SendMessage', {
255
+ message: {
256
+ role: 'ROLE_USER',
257
+ messageId: message.messageId,
258
+ contextId: message.correlationId,
259
+ parts: [{ text: message.name }],
260
+ metadata: { 'agentropy/envelope': trusted },
261
+ },
262
+ }, ctx);
263
+ const ack = result?.message?.parts?.[0]?.text;
264
+ let accepted = false;
265
+ if (ack) {
266
+ try {
267
+ accepted =
268
+ JSON.parse(ack).accepted === true;
269
+ }
270
+ catch {
271
+ throw new AgentropyError('RemoteUnavailable', 'A2A peer sent an unreadable acknowledgement', { details: { protocol: 'a2a' } });
272
+ }
273
+ }
274
+ return { messageId: message.messageId, accepted };
275
+ }
276
+ async getTask(ref, ctx) {
277
+ return this.state(await this.call(ref.route.target.endpoint, 'GetTask', { id: ref.remoteTaskId }, ctx));
278
+ }
279
+ async cancel(ref, ctx) {
280
+ return this.state(await this.call(ref.route.target.endpoint, 'CancelTask', { id: ref.remoteTaskId }, ctx));
281
+ }
282
+ async *subscribe(ref, ctx) {
283
+ let last;
284
+ let revision = 0;
285
+ const observe = (state) => {
286
+ if (state === last)
287
+ return undefined;
288
+ last = state;
289
+ revision++;
290
+ return {
291
+ eventId: `${ref.remoteTaskId}:${revision}`,
292
+ taskId: ref.remoteTaskId,
293
+ type: 'taskStatusChanged',
294
+ revision,
295
+ payload: {
296
+ status: FROM_A2A[state] ?? 'unknown',
297
+ remoteState: state,
298
+ },
299
+ };
300
+ };
301
+ if (this.o.streaming) {
302
+ for await (const state of this.streamStates(ref, ctx)) {
303
+ const e = observe(state);
304
+ if (e)
305
+ yield e;
306
+ if (TERMINAL_A2A.has(state))
307
+ return;
308
+ }
309
+ // Declined or ended early: the polling loop below continues from the last observed state.
310
+ }
311
+ for (let polls = 0;; polls++) {
312
+ const t = await this.call(ref.route.target.endpoint, 'GetTask', { id: ref.remoteTaskId }, ctx);
313
+ const e = observe(t.status.state);
314
+ if (e)
315
+ yield e;
316
+ if (TERMINAL_A2A.has(t.status.state) ||
317
+ polls >= (this.o.maxPolls ?? Infinity))
318
+ return;
319
+ await new Promise((r) => setTimeout(r, this.o.pollMs ?? 1_000));
320
+ }
321
+ }
322
+ /**
323
+ * Task states from `SubscribeToTask` over SSE. Ends without a terminal state when the peer does not stream
324
+ * (UnsupportedOperation, or a non-SSE reply) or the stream breaks; typed peer errors (NotFound, …) are thrown.
325
+ */
326
+ async *streamStates(ref, ctx) {
327
+ let res;
328
+ try {
329
+ res = await this.post(ref.route.target.endpoint, 'SubscribeToTask', { id: ref.remoteTaskId }, ctx, 'text/event-stream');
330
+ if (!res.body ||
331
+ !(res.headers?.get('content-type') ?? '').includes('text/event-stream')) {
332
+ this.result(await this.readJson(res, ctx)); // a JSON reply is an error (or a peer that ignored the method)
333
+ return;
334
+ }
335
+ }
336
+ catch (err) {
337
+ if (isAgentropyError(err) && err.code === 'UnsupportedOperation')
338
+ return;
339
+ throw err;
340
+ }
341
+ try {
342
+ for await (const data of sseData(res.body)) {
343
+ let frame;
344
+ try {
345
+ frame = JSON.parse(data);
346
+ }
347
+ catch {
348
+ return; // malformed frame: stop trusting the stream, poll instead
349
+ }
350
+ const r = this.result(frame);
351
+ const state = r?.task?.status?.state ?? r?.statusUpdate?.status?.state;
352
+ if (state && state in FROM_A2A)
353
+ yield state;
354
+ }
355
+ }
356
+ catch (err) {
357
+ if (isAgentropyError(err))
358
+ throw err;
359
+ // Transport break mid-stream: fall back to polling.
360
+ }
361
+ }
362
+ }
363
+ /** Minimal A2A AgentCard for an endpoint (spec section 8); serve it at the well-known path. */
364
+ export function a2aAgentCard(o) {
365
+ return {
366
+ name: o.name,
367
+ description: o.description,
368
+ version: o.version,
369
+ supportedInterfaces: [
370
+ {
371
+ url: o.url,
372
+ protocolBinding: 'JSONRPC',
373
+ protocolVersion: A2A_PROTOCOL_VERSION,
374
+ },
375
+ ],
376
+ capabilities: {
377
+ streaming: o.streaming === true,
378
+ pushNotifications: o.pushNotifications === true,
379
+ },
380
+ defaultInputModes: ['text/plain', 'application/json'],
381
+ defaultOutputModes: ['text/plain', 'application/json'],
382
+ ...(o.securitySchemes ? { securitySchemes: o.securitySchemes } : {}),
383
+ ...(o.security ? { security: o.security } : {}),
384
+ skills: o.skills ?? [],
385
+ };
386
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * A2A message history (FEAT-044.2). With `history: { store }` the endpoint keeps the user messages it accepted for a
3
+ * task so that `historyLength` (on `GetTask`, `ListTasks` and the `SendMessage` configuration) has something to
4
+ * return. Nothing is kept without it, and `historyLength` then has no effect.
5
+ *
6
+ * - **Per sender.** A message is recorded for the principal that sent it and read back only for that principal, as
7
+ * push configs are: a task's owner who sent nothing sees no history, and one caller never reads another's messages.
8
+ * - **Bounded.** At most `maxMessages` (default 100) per principal and task, the newest kept; a message is stored
9
+ * once per message ID, so a replay adds nothing.
10
+ * - **Minimal.** Role, message ID, context ID, task ID and parts; `metadata` (which may carry an Agentropy envelope)
11
+ * is never stored. Parts were validated when the message was accepted.
12
+ * - **Retained with the task.** `compact()` removes the rows of an ended task.
13
+ */
14
+ import { type Store, type TrustedPrincipal } from '@agentropy/core';
15
+ import type { A2AMessage } from './a2a-protocol.js';
16
+ export interface A2AHistoryOptions {
17
+ store: Store;
18
+ /** Messages kept per principal and task (default 100); the newest win. */
19
+ maxMessages?: number;
20
+ }
21
+ export interface A2AHistory {
22
+ /** Records an accepted message for the caller; the same message ID is stored once. */
23
+ record(caller: TrustedPrincipal, taskId: string, message: A2AMessage): Promise<void>;
24
+ /** The caller's messages for the task, oldest first; `limit` keeps the most recent ones (0 keeps none). */
25
+ read(caller: TrustedPrincipal, taskId: string, limit: number | undefined): Promise<A2AMessage[]>;
26
+ }
27
+ export declare function createA2AHistory(o: A2AHistoryOptions): A2AHistory;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * A2A message history (FEAT-044.2). With `history: { store }` the endpoint keeps the user messages it accepted for a
3
+ * task so that `historyLength` (on `GetTask`, `ListTasks` and the `SendMessage` configuration) has something to
4
+ * return. Nothing is kept without it, and `historyLength` then has no effect.
5
+ *
6
+ * - **Per sender.** A message is recorded for the principal that sent it and read back only for that principal, as
7
+ * push configs are: a task's owner who sent nothing sees no history, and one caller never reads another's messages.
8
+ * - **Bounded.** At most `maxMessages` (default 100) per principal and task, the newest kept; a message is stored
9
+ * once per message ID, so a replay adds nothing.
10
+ * - **Minimal.** Role, message ID, context ID, task ID and parts; `metadata` (which may carry an Agentropy envelope)
11
+ * is never stored. Parts were validated when the message was accepted.
12
+ * - **Retained with the task.** `compact()` removes the rows of an ended task.
13
+ */
14
+ import { AgentropyError, } from '@agentropy/core';
15
+ const DEFAULT_MAX_MESSAGES = 100;
16
+ export function createA2AHistory(o) {
17
+ const max = o.maxMessages ?? DEFAULT_MAX_MESSAGES;
18
+ if (!Number.isInteger(max) || max < 1)
19
+ throw new AgentropyError('InvalidConfiguration', 'history.maxMessages must be a positive integer');
20
+ return {
21
+ record: (caller, taskId, message) => o.store.transaction(async (tx) => {
22
+ const key = JSON.stringify([
23
+ caller.tenantId,
24
+ caller.id,
25
+ taskId,
26
+ message.messageId,
27
+ ]);
28
+ if (await tx.get('a2aHistory', key))
29
+ return;
30
+ const mine = (await tx.find('a2aHistory', {
31
+ where: { tenantId: caller.tenantId, taskId },
32
+ })).filter((d) => d.value.principalId === caller.id);
33
+ const seq = mine.reduce((m, d) => Math.max(m, d.value.seq), 0) + 1;
34
+ await tx.insert('a2aHistory', key, {
35
+ tenantId: caller.tenantId,
36
+ taskId,
37
+ principalId: caller.id,
38
+ seq,
39
+ message: {
40
+ role: 'ROLE_USER',
41
+ messageId: message.messageId,
42
+ ...(message.contextId ? { contextId: message.contextId } : {}),
43
+ taskId,
44
+ parts: message.parts,
45
+ },
46
+ });
47
+ const excess = mine.length + 1 - max;
48
+ if (excess > 0)
49
+ for (const d of mine
50
+ .sort((a, b) => a.value.seq - b.value.seq)
51
+ .slice(0, excess))
52
+ await tx.remove('a2aHistory', d.id, d.revision);
53
+ }),
54
+ read: async (caller, taskId, limit) => {
55
+ if (limit === 0)
56
+ return [];
57
+ const rows = await o.store.transaction((tx) => tx.find('a2aHistory', {
58
+ where: { tenantId: caller.tenantId, taskId },
59
+ }));
60
+ const all = rows
61
+ .filter((d) => d.value.principalId === caller.id)
62
+ .sort((a, b) => a.value.seq - b.value.seq)
63
+ .map((d) => d.value.message);
64
+ return limit === undefined ? all : all.slice(-limit);
65
+ },
66
+ };
67
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A2A HTTP binding (FEAT-034.1, A2A 1.0 JSON-RPC over HTTP): a Node `http` request handler serving an `A2AServer`.
3
+ *
4
+ * - `POST <path>` with a JSON-RPC body: unary methods answer `application/json`; `SendStreamingMessage` and
5
+ * `SubscribeToTask` answer `text/event-stream` (one JSON-RPC response per event, ending after the terminal status).
6
+ * - `GET /.well-known/agent-card.json`: the AgentCard, when one is configured.
7
+ * - The principal comes only from `authenticate(req)` (the application's bearer, mTLS or gateway check); a request
8
+ * it does not authenticate is answered `401` by the server. Request bodies are bounded; open streams are bounded.
9
+ * - A request target that is not a valid URL (`//`) is answered `400` instead of making the handler reject (FIX-049).
10
+ *
11
+ * The handler returns `false` for paths it does not serve, so a host can route the rest (health probes, metrics).
12
+ */
13
+ import type { IncomingMessage, ServerResponse } from 'node:http';
14
+ import type { TrustedPrincipal } from '@agentropy/core';
15
+ import type { A2AServer } from './a2a-server.js';
16
+ /** Well-known AgentCard path (A2A 1.0, section 8.2). */
17
+ export declare const AGENT_CARD_PATH = "/.well-known/agent-card.json";
18
+ export interface A2AHttpOptions {
19
+ /**
20
+ * Maps the request's credentials to a trusted principal (verify a bearer token, a client certificate, or headers
21
+ * set by a trusted gateway). Return `undefined` when the request is not authenticated; a throw counts the same.
22
+ */
23
+ authenticate(req: IncomingMessage): Promise<TrustedPrincipal | undefined>;
24
+ /** Served at {@link AGENT_CARD_PATH} (e.g. `agentCardForDefinition(def, url)`). */
25
+ agentCard?: Record<string, unknown>;
26
+ /** Path of the JSON-RPC endpoint (default `/a2a`). */
27
+ path?: string;
28
+ /** Largest request body accepted, in bytes (default 1 MiB); larger requests get `413`. */
29
+ maxBodyBytes?: number;
30
+ /**
31
+ * Streams open at once (default 100); more get `503`. A stream is released as soon as its client goes away.
32
+ */
33
+ maxStreams?: number;
34
+ /**
35
+ * Interval of the `: ping` comment written on an open stream (default 15 s), so a proxy's idle timeout does not cut
36
+ * a stream whose task waits a long time for its next state. Clients ignore SSE comments.
37
+ */
38
+ keepAliveMs?: number;
39
+ }
40
+ export interface A2AHttpHandler {
41
+ /** Serves the request when its path belongs to the binding; `false` leaves the response untouched. */
42
+ handle(req: IncomingMessage, res: ServerResponse): Promise<boolean>;
43
+ /** Streams currently open. */
44
+ openStreams(): number;
45
+ }
46
+ export declare function createA2AHttpHandler(server: A2AServer, o: A2AHttpOptions): A2AHttpHandler;