ceulen 0.7.0 → 0.9.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 (121) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/extensions/lib/registry.test.ts +67 -0
  3. package/extensions/lib/registry.ts +24 -7
  4. package/extensions/modules/a2a/configPanel.ts +435 -0
  5. package/extensions/modules/a2a/index.ts +1117 -0
  6. package/extensions/modules/a2a/lib/activity.ts +173 -0
  7. package/extensions/modules/a2a/lib/client.ts +1061 -0
  8. package/extensions/modules/a2a/lib/config.ts +920 -0
  9. package/extensions/modules/a2a/lib/discovery.ts +158 -0
  10. package/extensions/modules/a2a/lib/gateway.ts +889 -0
  11. package/extensions/modules/a2a/lib/mdns.ts +233 -0
  12. package/extensions/modules/a2a/lib/outcome.ts +48 -0
  13. package/extensions/modules/a2a/lib/persistence.ts +123 -0
  14. package/extensions/modules/a2a/lib/protocol.ts +506 -0
  15. package/extensions/modules/a2a/lib/registry.ts +146 -0
  16. package/extensions/modules/a2a/lib/retry.ts +86 -0
  17. package/extensions/modules/a2a/lib/security.ts +394 -0
  18. package/extensions/modules/a2a/lib/server.ts +1436 -0
  19. package/extensions/modules/a2a/test/activity.test.ts +138 -0
  20. package/extensions/modules/a2a/test/bridge.test.ts +101 -0
  21. package/extensions/modules/a2a/test/broadcast-parse.test.ts +31 -0
  22. package/extensions/modules/a2a/test/chai.ts +101 -0
  23. package/extensions/modules/a2a/test/client.test.ts +856 -0
  24. package/extensions/modules/a2a/test/completion-guard.test.ts +73 -0
  25. package/extensions/modules/a2a/test/config.test.ts +1396 -0
  26. package/extensions/modules/a2a/test/configPanel.test.ts +393 -0
  27. package/extensions/modules/a2a/test/discovery.test.ts +144 -0
  28. package/extensions/modules/a2a/test/extension.test.ts +135 -0
  29. package/extensions/modules/a2a/test/gateway.test.ts +1449 -0
  30. package/extensions/modules/a2a/test/helpers.ts +39 -0
  31. package/extensions/modules/a2a/test/mdns.test.ts +131 -0
  32. package/extensions/modules/a2a/test/outcome.test.ts +61 -0
  33. package/extensions/modules/a2a/test/persistence.test.ts +92 -0
  34. package/extensions/modules/a2a/test/protocol.test.ts +217 -0
  35. package/extensions/modules/a2a/test/registry.test.ts +114 -0
  36. package/extensions/modules/a2a/test/retry.test.ts +136 -0
  37. package/extensions/modules/a2a/test/security.test.ts +281 -0
  38. package/extensions/modules/a2a/test/server.test.ts +1966 -0
  39. package/extensions/modules/a2a/test/tmp.ts +59 -0
  40. package/extensions/modules/a2a/test/vendor.test.ts +57 -0
  41. package/extensions/modules/a2a/types/bonjour-service.d.ts +22 -0
  42. package/extensions/modules/a2a/vendor/VENDORED.md +18 -0
  43. package/extensions/modules/a2a/vendor/package.json +1 -0
  44. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/LICENSE +23 -0
  45. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.d.ts +14 -0
  46. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.js +57 -0
  47. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.d.ts +4 -0
  48. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.js +3 -0
  49. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.d.ts +13 -0
  50. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.js +50 -0
  51. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.d.ts +41 -0
  52. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.js +209 -0
  53. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.d.ts +9 -0
  54. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.js +42 -0
  55. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.d.ts +14 -0
  56. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.js +119 -0
  57. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.d.ts +14 -0
  58. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.js +142 -0
  59. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.d.ts +7 -0
  60. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.js +53 -0
  61. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.d.ts +58 -0
  62. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.js +130 -0
  63. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.d.ts +1 -0
  64. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.js +13 -0
  65. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.d.ts +1 -0
  66. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.js +17 -0
  67. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.d.ts +4 -0
  68. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.js +22 -0
  69. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.d.ts +3 -0
  70. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.js +6 -0
  71. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/LICENSE +21 -0
  72. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/classes.js +23 -0
  73. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/index.js +1761 -0
  74. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/opcodes.js +50 -0
  75. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/optioncodes.js +59 -0
  76. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/rcodes.js +50 -0
  77. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/types.js +103 -0
  78. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/LICENSE +21 -0
  79. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/es6.js +73 -0
  80. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/index.js +46 -0
  81. package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/LICENSE +21 -0
  82. package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/index.cjs +250 -0
  83. package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/LICENSE +21 -0
  84. package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/index.js +205 -0
  85. package/extensions/modules/a2a/vendor/vendored_deps/thunky/LICENSE +21 -0
  86. package/extensions/modules/a2a/vendor/vendored_deps/thunky/index.js +55 -0
  87. package/extensions/modules/advisor/index.ts +20 -2
  88. package/extensions/modules/advisor/lib/watcher.ts +3 -1
  89. package/extensions/modules/advisor/test/module.test.ts +64 -1
  90. package/extensions/modules/composer/test/module.test.ts +2 -2
  91. package/extensions/modules/config/index.ts +2 -0
  92. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  93. package/extensions/modules/munin/configPanel.ts +5 -2
  94. package/extensions/modules/munin/test/configPanel.test.ts +27 -2
  95. package/extensions/modules/router/configPanel.ts +24 -10
  96. package/extensions/modules/router/lib/client.ts +6 -4
  97. package/extensions/modules/router/test/unit.test.ts +83 -2
  98. package/extensions/modules/rules/index.ts +120 -0
  99. package/extensions/modules/rules/lib/rules.ts +348 -0
  100. package/extensions/modules/rules/test/lib.test.ts +263 -0
  101. package/extensions/modules/rules/test/module.test.ts +222 -0
  102. package/extensions/modules/subagent/index.ts +19 -6
  103. package/extensions/modules/subagent/lib/routing.ts +11 -6
  104. package/extensions/modules/subagent/lib/security.ts +12 -1
  105. package/extensions/modules/subagent/test/routing.test.ts +174 -0
  106. package/extensions/modules/todo/configPanel.ts +55 -0
  107. package/extensions/modules/todo/index.ts +511 -0
  108. package/extensions/modules/todo/lib/render.ts +271 -0
  109. package/extensions/modules/todo/lib/settings.ts +73 -0
  110. package/extensions/modules/todo/test/todo.test.ts +528 -0
  111. package/extensions/modules/usage/index.ts +11 -0
  112. package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
  113. package/extensions/modules/web/configPanel.ts +38 -13
  114. package/extensions/modules/web/lib/settings.ts +11 -2
  115. package/extensions/modules/web/test/configPanel.test.ts +67 -1
  116. package/extensions/modules/zai/configPanel.ts +5 -2
  117. package/extensions/modules/zai/lib/signing.ts +4 -1
  118. package/extensions/modules/zai/test/configPanel.test.ts +23 -0
  119. package/extensions/modules/zai/test/signing.test.ts +19 -0
  120. package/package.json +2 -2
  121. package/skills/a2a/SKILL.md +63 -0
@@ -0,0 +1,506 @@
1
+ /**
2
+ * A2A Protocol v1.0 data model — types, Agent Card construction, JSON-RPC
3
+ * framing, Part builders/extractors, task lifecycle.
4
+ *
5
+ * Wire shape follows the A2A Protocol v1.0 (JSON-RPC 2.0 binding over HTTP),
6
+ * stewarded by the Linux Foundation: https://a2a-protocol.org/latest/specification/
7
+ *
8
+ * Ported from Hermes' pure-stdlib Python implementation
9
+ * (plugins/platforms/a2a/protocol.py). Tolerant of v0.3 peers (legacy `kind`
10
+ * Parts and `agent.json` card path).
11
+ */
12
+
13
+ // ---------------------------------------------------------------------------
14
+ // Protocol version
15
+ // ---------------------------------------------------------------------------
16
+
17
+ export const PROTOCOL_VERSION = "1.0";
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Task lifecycle states (v1.0 SCREAMING_SNAKE_CASE)
21
+ // ---------------------------------------------------------------------------
22
+
23
+ export const STATE_SUBMITTED = "TASK_STATE_SUBMITTED";
24
+ export const STATE_WORKING = "TASK_STATE_WORKING";
25
+ export const STATE_INPUT_REQUIRED = "TASK_STATE_INPUT_REQUIRED";
26
+ export const STATE_AUTH_REQUIRED = "TASK_STATE_AUTH_REQUIRED";
27
+ export const STATE_COMPLETED = "TASK_STATE_COMPLETED";
28
+ export const STATE_FAILED = "TASK_STATE_FAILED";
29
+ export const STATE_CANCELED = "TASK_STATE_CANCELED";
30
+ export const STATE_REJECTED = "TASK_STATE_REJECTED";
31
+
32
+ export const TERMINAL_STATES = new Set<string>([
33
+ STATE_COMPLETED,
34
+ STATE_FAILED,
35
+ STATE_CANCELED,
36
+ STATE_REJECTED,
37
+ ]);
38
+
39
+ // v0.3 lowercase aliases (some peers still send these).
40
+ const STATE_ALIASES: Record<string, string> = {
41
+ submitted: STATE_SUBMITTED,
42
+ working: STATE_WORKING,
43
+ input_required: STATE_INPUT_REQUIRED,
44
+ completed: STATE_COMPLETED,
45
+ failed: STATE_FAILED,
46
+ canceled: STATE_CANCELED,
47
+ canceled_v03: STATE_CANCELED,
48
+ rejected: STATE_REJECTED,
49
+ };
50
+
51
+ /** Normalise an inbound state string to the v1.0 SCREAMING_SNAKE_CASE form. */
52
+ export function normalizeState(state: string | undefined | null): string {
53
+ if (!state) return "";
54
+ if (state.startsWith("TASK_STATE_")) return state;
55
+ const lower = state.toLowerCase();
56
+ return STATE_ALIASES[lower] ?? state;
57
+ }
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Message roles
61
+ // ---------------------------------------------------------------------------
62
+
63
+ export const ROLE_USER = "ROLE_USER";
64
+ export const ROLE_AGENT = "ROLE_AGENT";
65
+
66
+ // v0.3 used lowercase "user" / "agent".
67
+ export function normalizeRole(role: string | undefined | null): string {
68
+ if (!role) return ROLE_USER;
69
+ const r = role.toLowerCase();
70
+ if (r === "user") return ROLE_USER;
71
+ if (r === "agent" || r === "assistant" || r === "model") return ROLE_AGENT;
72
+ return role.startsWith("ROLE_") ? role : ROLE_USER;
73
+ }
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // JSON-RPC / A2A error codes
77
+ // ---------------------------------------------------------------------------
78
+
79
+ export const ERR_PARSE = -32700;
80
+ export const ERR_INVALID_REQUEST = -32600;
81
+ export const ERR_METHOD_NOT_FOUND = -32601;
82
+ export const ERR_INVALID_PARAMS = -32602;
83
+ export const ERR_INTERNAL = -32603;
84
+ // A2A spec-defined:
85
+ export const ERR_TASK_NOT_FOUND = -32001;
86
+ export const ERR_TASK_NOT_CANCELABLE = -32002;
87
+ export const ERR_PUSH_NOT_SUPPORTED = -32003;
88
+ // Custom (implementation-defined server-error space, clear of A2A block):
89
+ export const ERR_UNAUTHORIZED = -32050;
90
+ export const ERR_RATE_LIMITED = -32051;
91
+ export const ERR_UNTRUSTED_PEER = -32052;
92
+ export const ERR_UNSUPPORTED_OP = -32053;
93
+
94
+ // ---------------------------------------------------------------------------
95
+ // Timestamps / IDs
96
+ // ---------------------------------------------------------------------------
97
+
98
+ /** ISO 8601 UTC with millisecond precision (A2A v1.0). */
99
+ export function nowIso(): string {
100
+ return new Date().toISOString().replace(/\.\d{3}Z$/, (m) => m); // Date already gives ms precision
101
+ }
102
+
103
+ /** crypto.randomUUID where available, else hex fallback. */
104
+ export function uuid(): string {
105
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
106
+ return crypto.randomUUID();
107
+ }
108
+ return Math.random().toString(16).slice(2) + Date.now().toString(16);
109
+ }
110
+
111
+ export function newTaskId(): string {
112
+ return "task-" + uuid().replace(/-/g, "").slice(0, 16);
113
+ }
114
+
115
+ export function newContextId(): string {
116
+ return "ctx-" + uuid().replace(/-/g, "").slice(0, 16);
117
+ }
118
+
119
+ export function newMessageId(): string {
120
+ return uuid().replace(/-/g, "");
121
+ }
122
+
123
+ // ---------------------------------------------------------------------------
124
+ // Agent Card (v1.0)
125
+ // ---------------------------------------------------------------------------
126
+
127
+ export interface AgentSkill {
128
+ id: string;
129
+ name: string;
130
+ description: string;
131
+ tags?: string[];
132
+ }
133
+
134
+ export interface AgentExtension {
135
+ /** URI identifying the extension (custom URIs are allowed; not dereferenceable). */
136
+ uri: string;
137
+ description?: string;
138
+ /** If true, clients must understand this extension to interact. false = ignorable. */
139
+ required?: boolean;
140
+ }
141
+
142
+ export interface AgentCard {
143
+ name: string;
144
+ description?: string;
145
+ url: string; // convenience for pre-1.0 clients
146
+ version: string;
147
+ provider?: { organization: string; url: string };
148
+ supportedInterfaces: Array<{
149
+ url: string;
150
+ protocolBinding: string;
151
+ protocolVersion: string;
152
+ }>;
153
+ capabilities: {
154
+ streaming: boolean;
155
+ pushNotifications: boolean;
156
+ stateTransitionHistory: boolean;
157
+ extendedAgentCard: boolean;
158
+ /** A2A v1.0 Extensions declared by this agent (custom capabilities). */
159
+ extensions?: AgentExtension[];
160
+ };
161
+ defaultInputModes: string[];
162
+ defaultOutputModes: string[];
163
+ skills: AgentSkill[];
164
+ /** A2A v1.0 security schemes (oneof per a2a.proto SecurityScheme), e.g.
165
+ * { bearer: { httpAuthSecurityScheme: { scheme: "bearer" } } }. */
166
+ securitySchemes?: Record<string, { httpAuthSecurityScheme: { scheme: string; bearerFormat?: string; description?: string } }>;
167
+ /** A2A v1.0 security requirements: OR of ANDs; scopes are a StringList
168
+ * ({ list: [...] }) per a2a.proto and the spec's example card. */
169
+ securityRequirements?: Array<{ schemes: Record<string, { list: string[] }> }>;
170
+ /** v0.3 / OpenAPI-style requirement list. NOT part of the v1.0 card: kept as
171
+ * a legacy alias because hermes's a2a_discover still reads it to show
172
+ * "Auth required" (fleet record eaef8e95). v1.0 parsers ignore it. */
173
+ security?: Array<Record<string, string[]>>;
174
+ /** Implementation-defined metadata (A2A v1.0 — permitted on core structures). */
175
+ metadata?: Record<string, unknown>;
176
+ }
177
+
178
+ /** URI identifying the Pi session-metadata A2A extension. Implementation-defined;
179
+ * peers ignore it when `required` is false (which it always is). */
180
+ export const PI_SESSION_EXTENSION_URI = "https://bacnh85.dev/a2a/extensions/pi-session/v1";
181
+
182
+ export function buildAgentCard(opts: {
183
+ name: string;
184
+ url: string;
185
+ description?: string;
186
+ skills?: AgentSkill[];
187
+ streaming?: boolean;
188
+ pushNotifications?: boolean;
189
+ authRequired?: boolean;
190
+ /** When set, the card advertises the pi-session extension + this metadata. */
191
+ sessionMetadata?: Record<string, unknown>;
192
+ }): AgentCard {
193
+ const card: AgentCard = {
194
+ name: opts.name,
195
+ description: opts.description ?? "",
196
+ url: opts.url,
197
+ version: "1.0.0",
198
+ provider: { organization: "Pi Coding Agent", url: opts.url },
199
+ supportedInterfaces: [
200
+ {
201
+ url: opts.url,
202
+ protocolBinding: "JSONRPC",
203
+ protocolVersion: PROTOCOL_VERSION,
204
+ },
205
+ ],
206
+ capabilities: {
207
+ streaming: !!opts.streaming,
208
+ pushNotifications: !!opts.pushNotifications,
209
+ stateTransitionHistory: false,
210
+ extendedAgentCard: false,
211
+ },
212
+ defaultInputModes: ["text/plain"],
213
+ defaultOutputModes: ["text/plain"],
214
+ skills: opts.skills ?? [
215
+ {
216
+ id: "coding",
217
+ name: "coding",
218
+ description: "General-purpose coding agent (read, edit, run, debug)",
219
+ tags: ["coding", "refactor", "tests"],
220
+ },
221
+ ],
222
+ };
223
+ if (opts.authRequired) {
224
+ // A2A v1.0 shape (fleet task #427). This used to be the v0.3/OpenAPI
225
+ // {type:"http",scheme:"bearer"}, which the #353 spec-oracle conformance
226
+ // suite flagged: a strict v1.0 client cannot read it.
227
+ card.securitySchemes = { bearer: { httpAuthSecurityScheme: { scheme: "bearer" } } };
228
+ card.securityRequirements = [{ schemes: { bearer: { list: [] } } }];
229
+ card.security = [{ bearer: [] }]; // legacy alias, see the AgentCard type
230
+ }
231
+ if (opts.sessionMetadata && Object.keys(opts.sessionMetadata).length > 0) {
232
+ card.capabilities.extensions = [
233
+ {
234
+ uri: PI_SESSION_EXTENSION_URI,
235
+ description: "Pi session metadata (cwd, model, tools, pid)",
236
+ required: false,
237
+ },
238
+ ];
239
+ card.metadata = opts.sessionMetadata;
240
+ }
241
+ return card;
242
+ }
243
+
244
+ // ---------------------------------------------------------------------------
245
+ // JSON-RPC framing
246
+ // ---------------------------------------------------------------------------
247
+
248
+ export interface JsonRpcRequest {
249
+ jsonrpc: "2.0";
250
+ id?: string | number | null;
251
+ method: string;
252
+ params?: any;
253
+ }
254
+
255
+ export interface JsonRpcResponse {
256
+ jsonrpc: "2.0";
257
+ id?: string | number | null;
258
+ result?: any;
259
+ error?: { code: number; message: string; data?: any };
260
+ }
261
+
262
+ export function jsonrpcResult(id: JsonRpcRequest["id"], result: any): JsonRpcResponse {
263
+ return { jsonrpc: "2.0", id, result };
264
+ }
265
+
266
+ export function jsonrpcError(
267
+ id: JsonRpcRequest["id"],
268
+ code: number,
269
+ message: string,
270
+ data?: any,
271
+ ): JsonRpcResponse {
272
+ const err: JsonRpcResponse["error"] = { code, message };
273
+ if (data !== undefined) err.data = data;
274
+ return { jsonrpc: "2.0", id, error: err };
275
+ }
276
+
277
+ /**
278
+ * Wrap a SendMessage result. v1.0 wraps as {task} or {message}; legacy methods
279
+ * may return a bare Task/Message. This wraps a bare payload correctly.
280
+ */
281
+ export function sendMessageResponse(payload: any): any {
282
+ if (typeof payload === "object" && payload && payload.status && payload.id) {
283
+ return { task: payload };
284
+ }
285
+ return { message: payload };
286
+ }
287
+
288
+ /** Unwrap a v1.0 {task}|{message} response, or pass a legacy bare payload through. */
289
+ export function unwrapSendMessageResponse(result: any): any {
290
+ if (result && typeof result === "object") {
291
+ if (result.task && typeof result.task === "object") return result.task;
292
+ if (result.message && typeof result.message === "object") return result.message;
293
+ }
294
+ return result;
295
+ }
296
+
297
+ /** Wrap a Task as the v1.0 SendMessageResponse oneof {"task": …}. */
298
+ export const sendTaskResponse = (task: any): any => ({ task });
299
+
300
+ // StreamResponse builders (v1.0).
301
+ export const streamMessage = (message: any): any => ({ message });
302
+
303
+ /** v1.0 TaskStatusUpdateEvent — {taskId, contextId, status, final}. */
304
+ export const statusUpdateEvent = (task: any, final: boolean): any => ({
305
+ statusUpdate: {
306
+ taskId: task?.id,
307
+ contextId: task?.contextId,
308
+ status: task?.status,
309
+ final,
310
+ },
311
+ });
312
+
313
+ /** v1.0 TaskArtifactUpdateEvent — {taskId, contextId, artifact, lastChunk}. */
314
+ export const artifactUpdateEvent = (task: any, artifact: any, lastChunk = true): any => ({
315
+ artifactUpdate: {
316
+ taskId: task?.id,
317
+ contextId: task?.contextId,
318
+ artifact,
319
+ lastChunk,
320
+ },
321
+ });
322
+
323
+ // ---------------------------------------------------------------------------
324
+ // Parts (v1.0 member-presence discriminated; v0.3 `kind` tolerant)
325
+ // ---------------------------------------------------------------------------
326
+
327
+ export interface TextPart {
328
+ text: string;
329
+ mediaType?: string;
330
+ }
331
+ export interface FilePart {
332
+ url?: string;
333
+ raw?: string;
334
+ filename?: string;
335
+ mediaType?: string;
336
+ }
337
+ export interface DataPart {
338
+ data: any;
339
+ mediaType?: string;
340
+ }
341
+ export type Part = TextPart | FilePart | DataPart | Record<string, any>;
342
+
343
+ export function textPart(text: string): TextPart {
344
+ return { text, mediaType: "text/plain" };
345
+ }
346
+
347
+ export function filePart(opts: {
348
+ url?: string;
349
+ raw?: string;
350
+ filename?: string;
351
+ mediaType?: string;
352
+ }): FilePart {
353
+ const p: FilePart = { mediaType: opts.mediaType ?? "application/octet-stream" };
354
+ if (opts.filename) p.filename = opts.filename;
355
+ if (opts.url) p.url = opts.url;
356
+ else if (opts.raw) p.raw = opts.raw;
357
+ return p;
358
+ }
359
+
360
+ export function dataPart(data: any, mediaType = "application/json"): DataPart {
361
+ return { data, mediaType };
362
+ }
363
+
364
+ // ---------------------------------------------------------------------------
365
+ // Messages
366
+ // ---------------------------------------------------------------------------
367
+
368
+ export interface Message {
369
+ role: string;
370
+ parts: Part[];
371
+ messageId: string;
372
+ contextId?: string;
373
+ taskId?: string;
374
+ /** Implementation-defined metadata (A2A v1.0 — permitted on core structures).
375
+ * pi-a2a stamps the SENDER's session id under "pi/session" (and the
376
+ * configured selfIdentity under "pi/self") so receiving peers can join
377
+ * dispatches to ledger rows and records on one key (fleet task #238). */
378
+ metadata?: Record<string, unknown>;
379
+ }
380
+
381
+ export function textMessage(role: string, text: string, contextId = ""): Message {
382
+ const msg: Message = { role, parts: [textPart(text)], messageId: newMessageId() };
383
+ if (contextId) msg.contextId = contextId;
384
+ return msg;
385
+ }
386
+
387
+ export function messageWithParts(
388
+ role: string,
389
+ parts: Part[],
390
+ contextId = "",
391
+ ): Message {
392
+ const msg: Message = { role, parts, messageId: newMessageId() };
393
+ if (contextId) msg.contextId = contextId;
394
+ return msg;
395
+ }
396
+
397
+ /**
398
+ * Pull concatenated text from an A2A Message / Task result / params payload.
399
+ *
400
+ * v1.0 Parts carry the payload member directly (member-presence, no `kind`).
401
+ * v0.3 used `kind: "text"|"file"|"data"`; pre-0.3 used `type`. All three put
402
+ * text in `part.text`. File Parts are rendered as `[file: name] url`; data
403
+ * Parts as JSON — so the agent sees inbound richness even from text-only reply.
404
+ */
405
+ export function extractText(messageOrParams: any): string {
406
+ if (!messageOrParams || typeof messageOrParams !== "object") {
407
+ return typeof messageOrParams === "string" ? messageOrParams : "";
408
+ }
409
+ const msg = messageOrParams.message ?? messageOrParams;
410
+ // If this is a Task/result with artifacts, extract from the first artifact.
411
+ const artifacts = messageOrParams?.artifacts;
412
+ if (Array.isArray(artifacts)) {
413
+ for (const a of artifacts) {
414
+ const t = extractText(a);
415
+ if (t) return t;
416
+ }
417
+ }
418
+ // If this is a Task with a status.message, extract from that.
419
+ const statusMsg = messageOrParams?.status?.message;
420
+ if (statusMsg && typeof statusMsg === "object") {
421
+ const t = extractText(statusMsg);
422
+ if (t) return t;
423
+ }
424
+ const parts: any[] = Array.isArray(msg?.parts) ? msg.parts : [];
425
+ const chunks: string[] = [];
426
+ for (const part of parts) {
427
+ if (!part || typeof part !== "object") continue;
428
+ // v1.0 text part
429
+ if (typeof part.text === "string") {
430
+ chunks.push(part.text);
431
+ continue;
432
+ }
433
+ // v0.3 kind === "text"
434
+ if (part.kind === "text" && typeof part.text === "string") {
435
+ chunks.push(part.text);
436
+ continue;
437
+ }
438
+ // v1.0 file part with url
439
+ if (typeof part.url === "string" && part.url) {
440
+ const fname = part.filename || part.name || "";
441
+ const mtype = part.mediaType || part.mimeType || "";
442
+ const label = fname ? `[file: ${fname}]` : "[file]";
443
+ chunks.push(`${label} ${part.url}` + (mtype ? ` (${mtype})` : ""));
444
+ continue;
445
+ }
446
+ // v0.3 file with nested fileWithUri
447
+ const v03file = part.file;
448
+ if (v03file && typeof v03file === "object" && typeof v03file.fileWithUri === "string") {
449
+ const uri = v03file.fileWithUri;
450
+ const fname = v03file.name || "";
451
+ const mtype = v03file.mimeType || "";
452
+ const label = fname ? `[file: ${fname}]` : "[file]";
453
+ chunks.push(`${label} ${uri}` + (mtype ? ` (${mtype})` : ""));
454
+ continue;
455
+ }
456
+ // v1.0 file part with raw base64 — note but don't decode
457
+ if (typeof part.raw === "string") {
458
+ const fname = part.filename || "";
459
+ const mtype = part.mediaType || "";
460
+ const label = fname ? `[file: ${fname}]` : "[file]";
461
+ chunks.push(`${label} ${part.raw.length} bytes base64-encoded` + (mtype ? ` (${mtype})` : ""));
462
+ continue;
463
+ }
464
+ // v1.0 data part — include JSON content
465
+ if (part.data !== undefined) {
466
+ try {
467
+ chunks.push(JSON.stringify(part.data));
468
+ } catch {
469
+ chunks.push("[unserializable data part]");
470
+ }
471
+ continue;
472
+ }
473
+ }
474
+ return chunks.join("\n");
475
+ }
476
+
477
+ // ---------------------------------------------------------------------------
478
+ // Task construction
479
+ // ---------------------------------------------------------------------------
480
+
481
+ export interface Task {
482
+ id: string;
483
+ contextId: string;
484
+ status: { state: string; message?: Message; timestamp?: string };
485
+ history?: Message[];
486
+ artifacts?: Array<{ artifactId: string; parts: Part[]; name?: string }>;
487
+ kind?: string;
488
+ metadata?: Record<string, any>;
489
+ }
490
+
491
+ export function buildTask(opts: {
492
+ id: string;
493
+ contextId: string;
494
+ state?: string;
495
+ message?: Message;
496
+ }): Task {
497
+ return {
498
+ id: opts.id,
499
+ contextId: opts.contextId,
500
+ status: {
501
+ state: opts.state ?? STATE_SUBMITTED,
502
+ message: opts.message,
503
+ timestamp: nowIso(),
504
+ },
505
+ };
506
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Local session registry — zero-dep, filesystem-based.
3
+ *
4
+ * Each inbound A2A server writes `<piDir>/a2a_registry/<pid>.json` describing
5
+ * itself (url, port, cwd, model, tools). Other sessions read the directory to
6
+ * discover peers without port-scanning. The proven pattern (VS Code server,
7
+ * Emacs `server`, tmux, Docker) — inspectable, cross-process, self-healing.
8
+ *
9
+ * Stale-entry GC is dual: mtime TTL (cheap) + `process.kill(pid,0)` liveness
10
+ * probe (authoritative). Dead files are swept on every list().
11
+ * All FS ops are best-effort — discovery is non-critical, never throws to caller.
12
+ */
13
+
14
+ import { mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync, type Stats } from "node:fs";
15
+ import { join } from "node:path";
16
+ import type { AgentSkill } from "./protocol";
17
+
18
+ /** What one Pi session declares about itself. */
19
+ export interface SessionDescriptor {
20
+ pid: number; // also the filename key → cleanup target
21
+ url: string; // actual bound URL (after port fallback)
22
+ port: number; // actual bound port
23
+ host: string; // bind host
24
+ cwd: string; // working folder
25
+ model: { provider: string; id: string; name?: string } | null;
26
+ agentName: string; // display name (hostname fallback)
27
+ sessionName?: string; // pi.getSessionName()
28
+ /** The host pi session's session id (ctx.sessionManager.getSessionId()) —
29
+ * the per-session identity peers dispatch to and join receipts on
30
+ * (fleet task #238). Distinct live pi sessions share agentName but never
31
+ * this id. */
32
+ sessionId?: string;
33
+ /** Outbound caller identity (matches a key in server.peerTokens). Other
34
+ * sessions present this name's token when calling THIS session. */
35
+ selfIdentity?: string;
36
+ tools: string[]; // active tools — the "abilities"
37
+ skills: AgentSkill[]; // configured inbound skills
38
+ startedAt: string; // ISO
39
+ mtime: number; // epoch ms — heartbeat freshness (Date.now())
40
+ }
41
+
42
+ function dir(piDir: string): string {
43
+ return join(piDir, "a2a_registry");
44
+ }
45
+
46
+ function fileFor(piDir: string, pid: number): string {
47
+ return join(dir(piDir), `${pid}.json`);
48
+ }
49
+
50
+ function isAlive(pid: number): boolean {
51
+ // ponytail: process.kill(pid,0) is the cheap cross-platform liveness probe
52
+ // (throws ESRCH if the process is gone). Wrapped — it never throws to caller.
53
+ try {
54
+ process.kill(pid, 0);
55
+ return true;
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ export function register(desc: SessionDescriptor, piDir: string): void {
62
+ try {
63
+ const p = fileFor(piDir, desc.pid);
64
+ mkdirSync(dir(piDir), { recursive: true });
65
+ writeFileSync(p, JSON.stringify(desc, null, 2), { encoding: "utf-8" });
66
+ } catch {
67
+ /* best-effort */
68
+ }
69
+ }
70
+
71
+ /** Refresh a descriptor in place (updates mtime + any patched fields). */
72
+ export function heartbeat(desc: SessionDescriptor, piDir: string): void {
73
+ desc.mtime = Date.now();
74
+ register(desc, piDir);
75
+ }
76
+
77
+ export function unregister(pid: number, piDir: string): void {
78
+ try {
79
+ unlinkSync(fileFor(piDir, pid));
80
+ } catch {
81
+ /* ignore ENOENT — idempotent */
82
+ }
83
+ }
84
+
85
+ export interface ListOpts {
86
+ piDir: string;
87
+ ttlSec?: number;
88
+ /** Skip the process-kill probe (tests: probe can't work for fake pids). */
89
+ aliveProbe?: (pid: number) => boolean;
90
+ }
91
+
92
+ /**
93
+ * List live session descriptors. Sweeps stale entries (expired mtime OR dead
94
+ * pid) so the registry self-heals after ungraceful exits.
95
+ */
96
+ export function list(opts: ListOpts): SessionDescriptor[] {
97
+ const d = dir(opts.piDir);
98
+ const ttlMs = (opts.ttlSec ?? 60) * 1000;
99
+ const probe = opts.aliveProbe ?? isAlive;
100
+ let files: string[];
101
+ try {
102
+ files = readdirSync(d).filter((f) => /^\d+\.json$/.test(f));
103
+ } catch {
104
+ return [];
105
+ }
106
+ const now = Date.now();
107
+ const out: SessionDescriptor[] = [];
108
+ for (const f of files) {
109
+ try {
110
+ const path = join(d, f);
111
+ const raw = readJson(path);
112
+ if (!raw) continue;
113
+ const desc = raw as SessionDescriptor;
114
+ const stale = now - desc.mtime > ttlMs;
115
+ const dead = !probe(desc.pid);
116
+ if (stale || dead) {
117
+ // Self-heal: remove stale/dead entry.
118
+ try {
119
+ unlinkSync(path);
120
+ } catch {
121
+ /* race with another sweeper — fine */
122
+ }
123
+ continue;
124
+ }
125
+ out.push(desc);
126
+ } catch {
127
+ /* corrupt file — skip */
128
+ }
129
+ }
130
+ return out;
131
+ }
132
+
133
+ function readJson(p: string): unknown | null {
134
+ try {
135
+ const s: Stats = statSync(p);
136
+ const parsed = JSON.parse(readFileSync(p, "utf-8"));
137
+ if (parsed && typeof parsed === "object") {
138
+ // Prefer the authoritative filesystem mtime over the in-JSON field
139
+ // (guards against a clock-skewed writer).
140
+ parsed.mtime = s.mtimeMs;
141
+ }
142
+ return parsed;
143
+ } catch {
144
+ return null;
145
+ }
146
+ }