@oaslananka/registry 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,171 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form, made
34
+ available under the License, as indicated by a copyright notice that is included
35
+ in or attached to the work.
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work
47
+ by the copyright owner or by an individual or Legal Entity authorized to submit
48
+ on behalf of the copyright owner. For the purposes of this definition,
49
+ "submitted" means any form of electronic, verbal, or written communication sent
50
+ to the Licensor or its representatives, including but not limited to
51
+ communication on electronic mailing lists, source code control systems, and
52
+ issue tracking systems that are managed by, or on behalf of, the Licensor for
53
+ the purpose of discussing and improving the Work, but excluding communication
54
+ that is conspicuously marked or otherwise designated in writing by the copyright
55
+ owner as "Not a Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License.
62
+
63
+ Subject to the terms and conditions of this License, each Contributor hereby
64
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65
+ irrevocable copyright license to reproduce, prepare Derivative Works of,
66
+ publicly display, publicly perform, sublicense, and distribute the Work and such
67
+ Derivative Works in Source or Object form.
68
+
69
+ 3. Grant of Patent License.
70
+
71
+ Subject to the terms and conditions of this License, each Contributor hereby
72
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73
+ irrevocable (except as stated in this section) patent license to make, have
74
+ made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75
+ such license applies only to those patent claims licensable by such Contributor
76
+ that are necessarily infringed by their Contribution(s) alone or by combination
77
+ of their Contribution(s) with the Work to which such Contribution(s) was
78
+ submitted. If You institute patent litigation against any entity alleging that
79
+ the Work or a Contribution incorporated within the Work constitutes direct or
80
+ contributory patent infringement, then any patent licenses granted to You under
81
+ this License for that Work shall terminate as of the date such litigation is
82
+ filed.
83
+
84
+ 4. Redistribution.
85
+
86
+ You may reproduce and distribute copies of the Work or Derivative Works thereof
87
+ in any medium, with or without modifications, and in Source or Object form,
88
+ provided that You meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative Works a copy of
91
+ this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices stating that
94
+ You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works that You
97
+ distribute, all copyright, patent, trademark, and attribution notices from the
98
+ Source form of the Work, excluding those notices that do not pertain to any part
99
+ of the Derivative Works; and
100
+
101
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
102
+ any Derivative Works that You distribute must include a readable copy of the
103
+ attribution notices contained within such NOTICE file, excluding those notices
104
+ that do not pertain to any part of the Derivative Works, in at least one of the
105
+ following places: within a NOTICE text file distributed as part of the
106
+ Derivative Works; within the Source form or documentation, if provided along
107
+ with the Derivative Works; or, within a display generated by the Derivative
108
+ Works, if and wherever such third-party notices normally appear. The contents of
109
+ the NOTICE file are for informational purposes only and do not modify the
110
+ License. You may add Your own attribution notices within Derivative Works that
111
+ You distribute, alongside or as an addendum to the NOTICE text from the Work,
112
+ provided that such additional attribution notices cannot be construed as
113
+ modifying the License.
114
+
115
+ You may add Your own copyright statement to Your modifications and may provide
116
+ additional or different license terms and conditions for use, reproduction, or
117
+ distribution of Your modifications, or for any such Derivative Works as a whole,
118
+ provided Your use, reproduction, and distribution of the Work otherwise complies
119
+ with the conditions stated in this License.
120
+
121
+ 5. Submission of Contributions.
122
+
123
+ Unless You explicitly state otherwise, any Contribution intentionally submitted
124
+ for inclusion in the Work by You to the Licensor shall be under the terms and
125
+ conditions of this License, without any additional terms or conditions.
126
+ Notwithstanding the above, nothing herein shall supersede or modify the terms of
127
+ any separate license agreement you may have executed with Licensor regarding
128
+ such Contributions.
129
+
130
+ 6. Trademarks.
131
+
132
+ This License does not grant permission to use the trade names, trademarks,
133
+ service marks, or product names of the Licensor, except as required for
134
+ reasonable and customary use in describing the origin of the Work and
135
+ reproducing the content of the NOTICE file.
136
+
137
+ 7. Disclaimer of Warranty.
138
+
139
+ Unless required by applicable law or agreed to in writing, Licensor provides the
140
+ Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
141
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
142
+ including, without limitation, any warranties or conditions of TITLE,
143
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
144
+ solely responsible for determining the appropriateness of using or
145
+ redistributing the Work and assume any risks associated with Your exercise of
146
+ permissions under this License.
147
+
148
+ 8. Limitation of Liability.
149
+
150
+ In no event and under no legal theory, whether in tort (including negligence),
151
+ contract, or otherwise, unless required by applicable law (such as deliberate
152
+ and grossly negligent acts) or agreed to in writing, shall any Contributor be
153
+ liable to You for damages, including any direct, indirect, special, incidental,
154
+ or consequential damages of any character arising as a result of this License or
155
+ out of the use or inability to use the Work, including but not limited to
156
+ damages for loss of goodwill, work stoppage, computer failure or malfunction, or
157
+ any and all other commercial damages or losses, even if such Contributor has
158
+ been advised of the possibility of such damages.
159
+
160
+ 9. Accepting Warranty or Additional Liability.
161
+
162
+ While redistributing the Work or Derivative Works thereof, You may choose to
163
+ offer, and charge a fee for, acceptance of support, warranty, indemnity, or
164
+ other liability obligations and/or rights consistent with this License. However,
165
+ in accepting such obligations, You may act only on Your own behalf and on Your
166
+ sole responsibility, not on behalf of any other Contributor, and only if You
167
+ agree to indemnify, defend, and hold each Contributor harmless for any liability
168
+ incurred by, or claims asserted against, such Contributor by reason of your
169
+ accepting any such warranty or additional liability.
170
+
171
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,16 @@
1
+ # @oaslananka/registry
2
+
3
+ Registry APIs and storage backends for discovering and monitoring A2A agents.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @oaslananka/registry
9
+ ```
10
+
11
+ ## Includes
12
+
13
+ - `RegistryServer`
14
+ - `InMemoryStorage`
15
+ - `RedisStorage`
16
+ - metrics and SSE updates
package/dist/index.cjs ADDED
@@ -0,0 +1,292 @@
1
+ 'use strict';
2
+
3
+ const node_events = require('node:events');
4
+ const node_crypto = require('node:crypto');
5
+ const express = require('express');
6
+ const cors = require('cors');
7
+ const core = require('@oaslananka/core');
8
+
9
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
10
+
11
+ const express__default = /*#__PURE__*/_interopDefaultCompat(express);
12
+ const cors__default = /*#__PURE__*/_interopDefaultCompat(cors);
13
+
14
+ class SkillMatcher {
15
+ /**
16
+ * Filters agents based on a skill keyword or tag.
17
+ * @param agents All registered agents.
18
+ * @param query Search query values.
19
+ * @returns Array of matched agents.
20
+ */
21
+ static match(agents, query) {
22
+ const skill = query.skill?.toLowerCase();
23
+ const tag = query.tag?.toLowerCase();
24
+ const name = query.name?.toLowerCase();
25
+ return agents.filter((agent) => {
26
+ if (name && !agent.card.name.toLowerCase().includes(name)) {
27
+ return false;
28
+ }
29
+ const { skills } = agent.card;
30
+ if ((!skills || skills.length === 0) && (skill || tag)) {
31
+ return false;
32
+ }
33
+ if (!skills || skills.length === 0) {
34
+ return true;
35
+ }
36
+ return skills.some((entry) => {
37
+ if (skill && entry.name.toLowerCase().includes(skill)) return true;
38
+ if (skill && entry.description.toLowerCase().includes(skill)) return true;
39
+ if (tag && entry.tags && entry.tags.some((value) => value.toLowerCase().includes(tag))) return true;
40
+ if (!skill && !tag) return true;
41
+ return false;
42
+ });
43
+ });
44
+ }
45
+ }
46
+
47
+ class InMemoryStorage {
48
+ agents = /* @__PURE__ */ new Map();
49
+ async upsert(agent) {
50
+ this.agents.set(agent.id, agent);
51
+ return agent;
52
+ }
53
+ async get(id) {
54
+ return this.agents.get(id) ?? null;
55
+ }
56
+ async getAll() {
57
+ return Array.from(this.agents.values());
58
+ }
59
+ async delete(id) {
60
+ return this.agents.delete(id);
61
+ }
62
+ async updateStatus(id, status) {
63
+ const current = this.agents.get(id);
64
+ if (current) {
65
+ this.agents.set(id, { ...current, status });
66
+ }
67
+ }
68
+ async findBySkill(skill) {
69
+ const normalized = skill.toLowerCase();
70
+ return Array.from(this.agents.values()).filter(
71
+ (agent) => agent.skills.some((value) => value.toLowerCase().includes(normalized))
72
+ );
73
+ }
74
+ }
75
+
76
+ class RegistryServer {
77
+ app;
78
+ store;
79
+ events = new node_events.EventEmitter();
80
+ pingInterval = null;
81
+ metrics = {
82
+ registrations: 0,
83
+ searches: 0,
84
+ heartbeats: 0
85
+ };
86
+ constructor(options = {}) {
87
+ this.app = express__default();
88
+ this.app.use(cors__default());
89
+ this.app.use(express__default.json());
90
+ this.store = options.storage ?? new InMemoryStorage();
91
+ this.setupRoutes();
92
+ }
93
+ setupRoutes() {
94
+ this.app.get("/health", async (_req, res) => {
95
+ const agents = await this.store.getAll();
96
+ res.json({
97
+ status: "ok",
98
+ agents: agents.length,
99
+ healthyAgents: agents.filter((agent) => agent.status === "healthy").length
100
+ });
101
+ });
102
+ this.app.get("/metrics", async (_req, res) => {
103
+ const agents = await this.store.getAll();
104
+ const healthyAgents = agents.filter((agent) => agent.status === "healthy").length;
105
+ res.setHeader("Content-Type", "text/plain; version=0.0.4");
106
+ res.send(
107
+ [
108
+ "# HELP a2a_registry_registrations_total Total agent registrations.",
109
+ "# TYPE a2a_registry_registrations_total counter",
110
+ `a2a_registry_registrations_total ${this.metrics.registrations}`,
111
+ "# HELP a2a_registry_searches_total Total registry searches.",
112
+ "# TYPE a2a_registry_searches_total counter",
113
+ `a2a_registry_searches_total ${this.metrics.searches}`,
114
+ "# HELP a2a_registry_heartbeats_total Total registry heartbeats.",
115
+ "# TYPE a2a_registry_heartbeats_total counter",
116
+ `a2a_registry_heartbeats_total ${this.metrics.heartbeats}`,
117
+ "# HELP a2a_registry_agents Number of known agents.",
118
+ "# TYPE a2a_registry_agents gauge",
119
+ `a2a_registry_agents ${agents.length}`,
120
+ "# HELP a2a_registry_healthy_agents Number of healthy agents.",
121
+ "# TYPE a2a_registry_healthy_agents gauge",
122
+ `a2a_registry_healthy_agents ${healthyAgents}`
123
+ ].join("\n")
124
+ );
125
+ });
126
+ this.app.get("/events", (_req, res) => {
127
+ res.writeHead(200, {
128
+ "Content-Type": "text/event-stream",
129
+ "Cache-Control": "no-cache",
130
+ Connection: "keep-alive"
131
+ });
132
+ const listener = (payload) => {
133
+ res.write(`event: registry_update
134
+ data: ${JSON.stringify(payload)}
135
+
136
+ `);
137
+ };
138
+ this.events.on("registry_update", listener);
139
+ res.on("close", () => {
140
+ this.events.off("registry_update", listener);
141
+ });
142
+ });
143
+ this.app.post("/agents/register", async (req, res) => {
144
+ const { agentUrl, agentCard } = req.body;
145
+ if (!agentUrl || !agentCard) {
146
+ res.status(400).json({ error: "Missing agentUrl or agentCard" });
147
+ return;
148
+ }
149
+ const registered = await this.store.upsert(
150
+ this.toRegisteredAgent(agentUrl, core.normalizeAgentCard(agentCard))
151
+ );
152
+ this.metrics.registrations += 1;
153
+ this.emitRegistryEvent({ type: "registered", agent: registered });
154
+ core.logger.info("Agent registered", { id: registered.id, url: registered.url });
155
+ res.status(201).json(registered);
156
+ });
157
+ this.app.get("/agents", async (_req, res) => {
158
+ res.json(await this.store.getAll());
159
+ });
160
+ this.app.get("/agents/search", async (req, res) => {
161
+ const skill = typeof req.query.skill === "string" ? req.query.skill : "";
162
+ const tag = typeof req.query.tag === "string" ? req.query.tag : "";
163
+ const name = typeof req.query.name === "string" ? req.query.name : "";
164
+ if (!skill && !tag && !name) {
165
+ res.status(400).json({ error: "At least one of skill, tag or name is required" });
166
+ return;
167
+ }
168
+ this.metrics.searches += 1;
169
+ const matches = SkillMatcher.match(await this.store.getAll(), { skill, tag, name });
170
+ res.json(matches);
171
+ });
172
+ this.app.get("/agents/:id", async (req, res) => {
173
+ const agent = await this.store.get(req.params.id);
174
+ if (!agent) {
175
+ res.status(404).json({ error: "Agent not found" });
176
+ return;
177
+ }
178
+ res.json(agent);
179
+ });
180
+ this.app.post("/agents/:id/heartbeat", async (req, res) => {
181
+ const agent = await this.store.get(req.params.id);
182
+ if (!agent) {
183
+ res.status(404).json({ error: "Agent not found" });
184
+ return;
185
+ }
186
+ const updated = {
187
+ ...agent,
188
+ status: "healthy",
189
+ lastHeartbeatAt: (/* @__PURE__ */ new Date()).toISOString()
190
+ };
191
+ await this.store.upsert(updated);
192
+ this.metrics.heartbeats += 1;
193
+ this.emitRegistryEvent({ type: "heartbeat", agent: updated });
194
+ res.json(updated);
195
+ });
196
+ this.app.delete("/agents/:id", async (req, res) => {
197
+ const deleted = await this.store.delete(req.params.id);
198
+ if (!deleted) {
199
+ res.status(404).json({ error: "Agent not found" });
200
+ return;
201
+ }
202
+ this.emitRegistryEvent({ type: "deleted", id: req.params.id });
203
+ res.status(204).send();
204
+ });
205
+ }
206
+ startHealthChecks() {
207
+ this.pingInterval = setInterval(async () => {
208
+ const agents = await this.store.getAll();
209
+ for (const agent of agents) {
210
+ try {
211
+ const res = await fetch(`${agent.url}/health`);
212
+ const status = res.ok ? "healthy" : "unhealthy";
213
+ await this.store.updateStatus(agent.id, status);
214
+ } catch (error) {
215
+ await this.store.updateStatus(agent.id, "unhealthy");
216
+ core.logger.warn("Agent unreachable", { agentId: agent.id, error: String(error) });
217
+ }
218
+ }
219
+ }, 3e4);
220
+ }
221
+ start(port) {
222
+ this.startHealthChecks();
223
+ return this.app.listen(port, () => {
224
+ core.logger.info("Registry Server listening", { port });
225
+ });
226
+ }
227
+ stop() {
228
+ if (this.pingInterval) {
229
+ clearInterval(this.pingInterval);
230
+ }
231
+ }
232
+ emitRegistryEvent(payload) {
233
+ this.events.emit("registry_update", payload);
234
+ }
235
+ toRegisteredAgent(agentUrl, card) {
236
+ const tags = (card.skills ?? []).flatMap((skill) => skill.tags ?? []);
237
+ const skills = (card.skills ?? []).map((skill) => skill.name);
238
+ return {
239
+ id: node_crypto.randomUUID(),
240
+ url: agentUrl,
241
+ card,
242
+ status: "unknown",
243
+ tags,
244
+ skills,
245
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
246
+ };
247
+ }
248
+ }
249
+
250
+ class RedisStorage {
251
+ constructor(client, prefix = "a2a:registry") {
252
+ this.client = client;
253
+ this.prefix = prefix;
254
+ }
255
+ async upsert(agent) {
256
+ await this.client.set(this.key(agent.id), JSON.stringify(agent));
257
+ return agent;
258
+ }
259
+ async get(id) {
260
+ const value = await this.client.get(this.key(id));
261
+ return value ? JSON.parse(value) : null;
262
+ }
263
+ async getAll() {
264
+ const keys = await this.client.keys(this.key("*"));
265
+ const values = await Promise.all(keys.map((key) => this.client.get(key)));
266
+ return values.filter((value) => typeof value === "string").map((value) => JSON.parse(value));
267
+ }
268
+ async delete(id) {
269
+ return await this.client.del(this.key(id)) > 0;
270
+ }
271
+ async updateStatus(id, status) {
272
+ const current = await this.get(id);
273
+ if (current) {
274
+ await this.upsert({ ...current, status });
275
+ }
276
+ }
277
+ async findBySkill(skill) {
278
+ const normalized = skill.toLowerCase();
279
+ const agents = await this.getAll();
280
+ return agents.filter(
281
+ (agent) => agent.skills.some((value) => value.toLowerCase().includes(normalized))
282
+ );
283
+ }
284
+ key(id) {
285
+ return `${this.prefix}:${id}`;
286
+ }
287
+ }
288
+
289
+ exports.InMemoryStorage = InMemoryStorage;
290
+ exports.RedisStorage = RedisStorage;
291
+ exports.RegistryServer = RegistryServer;
292
+ exports.SkillMatcher = SkillMatcher;
@@ -0,0 +1,97 @@
1
+ import * as node_http from 'node:http';
2
+ import { AgentCard } from '@oaslananka/core';
3
+
4
+ type AgentStatus = 'healthy' | 'unhealthy' | 'unknown';
5
+ interface RegisteredAgent {
6
+ id: string;
7
+ url: string;
8
+ card: AgentCard;
9
+ status: AgentStatus;
10
+ tags: string[];
11
+ skills: string[];
12
+ registeredAt: string;
13
+ lastHeartbeatAt?: string;
14
+ }
15
+ interface IAgentStorage {
16
+ upsert(agent: RegisteredAgent): Promise<RegisteredAgent>;
17
+ get(id: string): Promise<RegisteredAgent | null>;
18
+ getAll(): Promise<RegisteredAgent[]>;
19
+ delete(id: string): Promise<boolean>;
20
+ updateStatus(id: string, status: AgentStatus): Promise<void>;
21
+ findBySkill(skill: string): Promise<RegisteredAgent[]>;
22
+ }
23
+
24
+ interface RegistryServerOptions {
25
+ storage?: IAgentStorage;
26
+ }
27
+ /**
28
+ * Registry service for agent registration, discovery, health, metrics, and live updates.
29
+ *
30
+ * @since 1.0.0
31
+ */
32
+ declare class RegistryServer {
33
+ private readonly app;
34
+ private readonly store;
35
+ private readonly events;
36
+ private pingInterval;
37
+ private metrics;
38
+ constructor(options?: RegistryServerOptions);
39
+ private setupRoutes;
40
+ private startHealthChecks;
41
+ start(port: number): node_http.Server<typeof node_http.IncomingMessage, typeof node_http.ServerResponse>;
42
+ stop(): void;
43
+ private emitRegistryEvent;
44
+ private toRegisteredAgent;
45
+ }
46
+
47
+ /**
48
+ * @file SkillMatcher.ts
49
+ * Semantic skill matcher (fallback to tags/substring for now).
50
+ */
51
+
52
+ interface SkillMatcherQuery {
53
+ skill?: string;
54
+ tag?: string;
55
+ name?: string;
56
+ }
57
+ declare class SkillMatcher {
58
+ /**
59
+ * Filters agents based on a skill keyword or tag.
60
+ * @param agents All registered agents.
61
+ * @param query Search query values.
62
+ * @returns Array of matched agents.
63
+ */
64
+ static match(agents: RegisteredAgent[], query: SkillMatcherQuery): RegisteredAgent[];
65
+ }
66
+
67
+ declare class InMemoryStorage implements IAgentStorage {
68
+ private readonly agents;
69
+ upsert(agent: RegisteredAgent): Promise<RegisteredAgent>;
70
+ get(id: string): Promise<RegisteredAgent | null>;
71
+ getAll(): Promise<RegisteredAgent[]>;
72
+ delete(id: string): Promise<boolean>;
73
+ updateStatus(id: string, status: AgentStatus): Promise<void>;
74
+ findBySkill(skill: string): Promise<RegisteredAgent[]>;
75
+ }
76
+
77
+ interface RegistryRedisClient {
78
+ get(key: string): Promise<string | null>;
79
+ set(key: string, value: string): Promise<unknown>;
80
+ del(key: string): Promise<number>;
81
+ keys(pattern: string): Promise<string[]>;
82
+ }
83
+ declare class RedisStorage implements IAgentStorage {
84
+ private readonly client;
85
+ private readonly prefix;
86
+ constructor(client: RegistryRedisClient, prefix?: string);
87
+ upsert(agent: RegisteredAgent): Promise<RegisteredAgent>;
88
+ get(id: string): Promise<RegisteredAgent | null>;
89
+ getAll(): Promise<RegisteredAgent[]>;
90
+ delete(id: string): Promise<boolean>;
91
+ updateStatus(id: string, status: AgentStatus): Promise<void>;
92
+ findBySkill(skill: string): Promise<RegisteredAgent[]>;
93
+ private key;
94
+ }
95
+
96
+ export { InMemoryStorage, RedisStorage, RegistryServer, SkillMatcher };
97
+ export type { AgentStatus, IAgentStorage, RegisteredAgent, RegistryRedisClient, RegistryServerOptions, SkillMatcherQuery };
@@ -0,0 +1,97 @@
1
+ import * as node_http from 'node:http';
2
+ import { AgentCard } from '@oaslananka/core';
3
+
4
+ type AgentStatus = 'healthy' | 'unhealthy' | 'unknown';
5
+ interface RegisteredAgent {
6
+ id: string;
7
+ url: string;
8
+ card: AgentCard;
9
+ status: AgentStatus;
10
+ tags: string[];
11
+ skills: string[];
12
+ registeredAt: string;
13
+ lastHeartbeatAt?: string;
14
+ }
15
+ interface IAgentStorage {
16
+ upsert(agent: RegisteredAgent): Promise<RegisteredAgent>;
17
+ get(id: string): Promise<RegisteredAgent | null>;
18
+ getAll(): Promise<RegisteredAgent[]>;
19
+ delete(id: string): Promise<boolean>;
20
+ updateStatus(id: string, status: AgentStatus): Promise<void>;
21
+ findBySkill(skill: string): Promise<RegisteredAgent[]>;
22
+ }
23
+
24
+ interface RegistryServerOptions {
25
+ storage?: IAgentStorage;
26
+ }
27
+ /**
28
+ * Registry service for agent registration, discovery, health, metrics, and live updates.
29
+ *
30
+ * @since 1.0.0
31
+ */
32
+ declare class RegistryServer {
33
+ private readonly app;
34
+ private readonly store;
35
+ private readonly events;
36
+ private pingInterval;
37
+ private metrics;
38
+ constructor(options?: RegistryServerOptions);
39
+ private setupRoutes;
40
+ private startHealthChecks;
41
+ start(port: number): node_http.Server<typeof node_http.IncomingMessage, typeof node_http.ServerResponse>;
42
+ stop(): void;
43
+ private emitRegistryEvent;
44
+ private toRegisteredAgent;
45
+ }
46
+
47
+ /**
48
+ * @file SkillMatcher.ts
49
+ * Semantic skill matcher (fallback to tags/substring for now).
50
+ */
51
+
52
+ interface SkillMatcherQuery {
53
+ skill?: string;
54
+ tag?: string;
55
+ name?: string;
56
+ }
57
+ declare class SkillMatcher {
58
+ /**
59
+ * Filters agents based on a skill keyword or tag.
60
+ * @param agents All registered agents.
61
+ * @param query Search query values.
62
+ * @returns Array of matched agents.
63
+ */
64
+ static match(agents: RegisteredAgent[], query: SkillMatcherQuery): RegisteredAgent[];
65
+ }
66
+
67
+ declare class InMemoryStorage implements IAgentStorage {
68
+ private readonly agents;
69
+ upsert(agent: RegisteredAgent): Promise<RegisteredAgent>;
70
+ get(id: string): Promise<RegisteredAgent | null>;
71
+ getAll(): Promise<RegisteredAgent[]>;
72
+ delete(id: string): Promise<boolean>;
73
+ updateStatus(id: string, status: AgentStatus): Promise<void>;
74
+ findBySkill(skill: string): Promise<RegisteredAgent[]>;
75
+ }
76
+
77
+ interface RegistryRedisClient {
78
+ get(key: string): Promise<string | null>;
79
+ set(key: string, value: string): Promise<unknown>;
80
+ del(key: string): Promise<number>;
81
+ keys(pattern: string): Promise<string[]>;
82
+ }
83
+ declare class RedisStorage implements IAgentStorage {
84
+ private readonly client;
85
+ private readonly prefix;
86
+ constructor(client: RegistryRedisClient, prefix?: string);
87
+ upsert(agent: RegisteredAgent): Promise<RegisteredAgent>;
88
+ get(id: string): Promise<RegisteredAgent | null>;
89
+ getAll(): Promise<RegisteredAgent[]>;
90
+ delete(id: string): Promise<boolean>;
91
+ updateStatus(id: string, status: AgentStatus): Promise<void>;
92
+ findBySkill(skill: string): Promise<RegisteredAgent[]>;
93
+ private key;
94
+ }
95
+
96
+ export { InMemoryStorage, RedisStorage, RegistryServer, SkillMatcher };
97
+ export type { AgentStatus, IAgentStorage, RegisteredAgent, RegistryRedisClient, RegistryServerOptions, SkillMatcherQuery };
@@ -0,0 +1,97 @@
1
+ import * as node_http from 'node:http';
2
+ import { AgentCard } from '@oaslananka/core';
3
+
4
+ type AgentStatus = 'healthy' | 'unhealthy' | 'unknown';
5
+ interface RegisteredAgent {
6
+ id: string;
7
+ url: string;
8
+ card: AgentCard;
9
+ status: AgentStatus;
10
+ tags: string[];
11
+ skills: string[];
12
+ registeredAt: string;
13
+ lastHeartbeatAt?: string;
14
+ }
15
+ interface IAgentStorage {
16
+ upsert(agent: RegisteredAgent): Promise<RegisteredAgent>;
17
+ get(id: string): Promise<RegisteredAgent | null>;
18
+ getAll(): Promise<RegisteredAgent[]>;
19
+ delete(id: string): Promise<boolean>;
20
+ updateStatus(id: string, status: AgentStatus): Promise<void>;
21
+ findBySkill(skill: string): Promise<RegisteredAgent[]>;
22
+ }
23
+
24
+ interface RegistryServerOptions {
25
+ storage?: IAgentStorage;
26
+ }
27
+ /**
28
+ * Registry service for agent registration, discovery, health, metrics, and live updates.
29
+ *
30
+ * @since 1.0.0
31
+ */
32
+ declare class RegistryServer {
33
+ private readonly app;
34
+ private readonly store;
35
+ private readonly events;
36
+ private pingInterval;
37
+ private metrics;
38
+ constructor(options?: RegistryServerOptions);
39
+ private setupRoutes;
40
+ private startHealthChecks;
41
+ start(port: number): node_http.Server<typeof node_http.IncomingMessage, typeof node_http.ServerResponse>;
42
+ stop(): void;
43
+ private emitRegistryEvent;
44
+ private toRegisteredAgent;
45
+ }
46
+
47
+ /**
48
+ * @file SkillMatcher.ts
49
+ * Semantic skill matcher (fallback to tags/substring for now).
50
+ */
51
+
52
+ interface SkillMatcherQuery {
53
+ skill?: string;
54
+ tag?: string;
55
+ name?: string;
56
+ }
57
+ declare class SkillMatcher {
58
+ /**
59
+ * Filters agents based on a skill keyword or tag.
60
+ * @param agents All registered agents.
61
+ * @param query Search query values.
62
+ * @returns Array of matched agents.
63
+ */
64
+ static match(agents: RegisteredAgent[], query: SkillMatcherQuery): RegisteredAgent[];
65
+ }
66
+
67
+ declare class InMemoryStorage implements IAgentStorage {
68
+ private readonly agents;
69
+ upsert(agent: RegisteredAgent): Promise<RegisteredAgent>;
70
+ get(id: string): Promise<RegisteredAgent | null>;
71
+ getAll(): Promise<RegisteredAgent[]>;
72
+ delete(id: string): Promise<boolean>;
73
+ updateStatus(id: string, status: AgentStatus): Promise<void>;
74
+ findBySkill(skill: string): Promise<RegisteredAgent[]>;
75
+ }
76
+
77
+ interface RegistryRedisClient {
78
+ get(key: string): Promise<string | null>;
79
+ set(key: string, value: string): Promise<unknown>;
80
+ del(key: string): Promise<number>;
81
+ keys(pattern: string): Promise<string[]>;
82
+ }
83
+ declare class RedisStorage implements IAgentStorage {
84
+ private readonly client;
85
+ private readonly prefix;
86
+ constructor(client: RegistryRedisClient, prefix?: string);
87
+ upsert(agent: RegisteredAgent): Promise<RegisteredAgent>;
88
+ get(id: string): Promise<RegisteredAgent | null>;
89
+ getAll(): Promise<RegisteredAgent[]>;
90
+ delete(id: string): Promise<boolean>;
91
+ updateStatus(id: string, status: AgentStatus): Promise<void>;
92
+ findBySkill(skill: string): Promise<RegisteredAgent[]>;
93
+ private key;
94
+ }
95
+
96
+ export { InMemoryStorage, RedisStorage, RegistryServer, SkillMatcher };
97
+ export type { AgentStatus, IAgentStorage, RegisteredAgent, RegistryRedisClient, RegistryServerOptions, SkillMatcherQuery };
package/dist/index.mjs ADDED
@@ -0,0 +1,282 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { randomUUID } from 'node:crypto';
3
+ import express from 'express';
4
+ import cors from 'cors';
5
+ import { normalizeAgentCard, logger } from '@oaslananka/core';
6
+
7
+ class SkillMatcher {
8
+ /**
9
+ * Filters agents based on a skill keyword or tag.
10
+ * @param agents All registered agents.
11
+ * @param query Search query values.
12
+ * @returns Array of matched agents.
13
+ */
14
+ static match(agents, query) {
15
+ const skill = query.skill?.toLowerCase();
16
+ const tag = query.tag?.toLowerCase();
17
+ const name = query.name?.toLowerCase();
18
+ return agents.filter((agent) => {
19
+ if (name && !agent.card.name.toLowerCase().includes(name)) {
20
+ return false;
21
+ }
22
+ const { skills } = agent.card;
23
+ if ((!skills || skills.length === 0) && (skill || tag)) {
24
+ return false;
25
+ }
26
+ if (!skills || skills.length === 0) {
27
+ return true;
28
+ }
29
+ return skills.some((entry) => {
30
+ if (skill && entry.name.toLowerCase().includes(skill)) return true;
31
+ if (skill && entry.description.toLowerCase().includes(skill)) return true;
32
+ if (tag && entry.tags && entry.tags.some((value) => value.toLowerCase().includes(tag))) return true;
33
+ if (!skill && !tag) return true;
34
+ return false;
35
+ });
36
+ });
37
+ }
38
+ }
39
+
40
+ class InMemoryStorage {
41
+ agents = /* @__PURE__ */ new Map();
42
+ async upsert(agent) {
43
+ this.agents.set(agent.id, agent);
44
+ return agent;
45
+ }
46
+ async get(id) {
47
+ return this.agents.get(id) ?? null;
48
+ }
49
+ async getAll() {
50
+ return Array.from(this.agents.values());
51
+ }
52
+ async delete(id) {
53
+ return this.agents.delete(id);
54
+ }
55
+ async updateStatus(id, status) {
56
+ const current = this.agents.get(id);
57
+ if (current) {
58
+ this.agents.set(id, { ...current, status });
59
+ }
60
+ }
61
+ async findBySkill(skill) {
62
+ const normalized = skill.toLowerCase();
63
+ return Array.from(this.agents.values()).filter(
64
+ (agent) => agent.skills.some((value) => value.toLowerCase().includes(normalized))
65
+ );
66
+ }
67
+ }
68
+
69
+ class RegistryServer {
70
+ app;
71
+ store;
72
+ events = new EventEmitter();
73
+ pingInterval = null;
74
+ metrics = {
75
+ registrations: 0,
76
+ searches: 0,
77
+ heartbeats: 0
78
+ };
79
+ constructor(options = {}) {
80
+ this.app = express();
81
+ this.app.use(cors());
82
+ this.app.use(express.json());
83
+ this.store = options.storage ?? new InMemoryStorage();
84
+ this.setupRoutes();
85
+ }
86
+ setupRoutes() {
87
+ this.app.get("/health", async (_req, res) => {
88
+ const agents = await this.store.getAll();
89
+ res.json({
90
+ status: "ok",
91
+ agents: agents.length,
92
+ healthyAgents: agents.filter((agent) => agent.status === "healthy").length
93
+ });
94
+ });
95
+ this.app.get("/metrics", async (_req, res) => {
96
+ const agents = await this.store.getAll();
97
+ const healthyAgents = agents.filter((agent) => agent.status === "healthy").length;
98
+ res.setHeader("Content-Type", "text/plain; version=0.0.4");
99
+ res.send(
100
+ [
101
+ "# HELP a2a_registry_registrations_total Total agent registrations.",
102
+ "# TYPE a2a_registry_registrations_total counter",
103
+ `a2a_registry_registrations_total ${this.metrics.registrations}`,
104
+ "# HELP a2a_registry_searches_total Total registry searches.",
105
+ "# TYPE a2a_registry_searches_total counter",
106
+ `a2a_registry_searches_total ${this.metrics.searches}`,
107
+ "# HELP a2a_registry_heartbeats_total Total registry heartbeats.",
108
+ "# TYPE a2a_registry_heartbeats_total counter",
109
+ `a2a_registry_heartbeats_total ${this.metrics.heartbeats}`,
110
+ "# HELP a2a_registry_agents Number of known agents.",
111
+ "# TYPE a2a_registry_agents gauge",
112
+ `a2a_registry_agents ${agents.length}`,
113
+ "# HELP a2a_registry_healthy_agents Number of healthy agents.",
114
+ "# TYPE a2a_registry_healthy_agents gauge",
115
+ `a2a_registry_healthy_agents ${healthyAgents}`
116
+ ].join("\n")
117
+ );
118
+ });
119
+ this.app.get("/events", (_req, res) => {
120
+ res.writeHead(200, {
121
+ "Content-Type": "text/event-stream",
122
+ "Cache-Control": "no-cache",
123
+ Connection: "keep-alive"
124
+ });
125
+ const listener = (payload) => {
126
+ res.write(`event: registry_update
127
+ data: ${JSON.stringify(payload)}
128
+
129
+ `);
130
+ };
131
+ this.events.on("registry_update", listener);
132
+ res.on("close", () => {
133
+ this.events.off("registry_update", listener);
134
+ });
135
+ });
136
+ this.app.post("/agents/register", async (req, res) => {
137
+ const { agentUrl, agentCard } = req.body;
138
+ if (!agentUrl || !agentCard) {
139
+ res.status(400).json({ error: "Missing agentUrl or agentCard" });
140
+ return;
141
+ }
142
+ const registered = await this.store.upsert(
143
+ this.toRegisteredAgent(agentUrl, normalizeAgentCard(agentCard))
144
+ );
145
+ this.metrics.registrations += 1;
146
+ this.emitRegistryEvent({ type: "registered", agent: registered });
147
+ logger.info("Agent registered", { id: registered.id, url: registered.url });
148
+ res.status(201).json(registered);
149
+ });
150
+ this.app.get("/agents", async (_req, res) => {
151
+ res.json(await this.store.getAll());
152
+ });
153
+ this.app.get("/agents/search", async (req, res) => {
154
+ const skill = typeof req.query.skill === "string" ? req.query.skill : "";
155
+ const tag = typeof req.query.tag === "string" ? req.query.tag : "";
156
+ const name = typeof req.query.name === "string" ? req.query.name : "";
157
+ if (!skill && !tag && !name) {
158
+ res.status(400).json({ error: "At least one of skill, tag or name is required" });
159
+ return;
160
+ }
161
+ this.metrics.searches += 1;
162
+ const matches = SkillMatcher.match(await this.store.getAll(), { skill, tag, name });
163
+ res.json(matches);
164
+ });
165
+ this.app.get("/agents/:id", async (req, res) => {
166
+ const agent = await this.store.get(req.params.id);
167
+ if (!agent) {
168
+ res.status(404).json({ error: "Agent not found" });
169
+ return;
170
+ }
171
+ res.json(agent);
172
+ });
173
+ this.app.post("/agents/:id/heartbeat", async (req, res) => {
174
+ const agent = await this.store.get(req.params.id);
175
+ if (!agent) {
176
+ res.status(404).json({ error: "Agent not found" });
177
+ return;
178
+ }
179
+ const updated = {
180
+ ...agent,
181
+ status: "healthy",
182
+ lastHeartbeatAt: (/* @__PURE__ */ new Date()).toISOString()
183
+ };
184
+ await this.store.upsert(updated);
185
+ this.metrics.heartbeats += 1;
186
+ this.emitRegistryEvent({ type: "heartbeat", agent: updated });
187
+ res.json(updated);
188
+ });
189
+ this.app.delete("/agents/:id", async (req, res) => {
190
+ const deleted = await this.store.delete(req.params.id);
191
+ if (!deleted) {
192
+ res.status(404).json({ error: "Agent not found" });
193
+ return;
194
+ }
195
+ this.emitRegistryEvent({ type: "deleted", id: req.params.id });
196
+ res.status(204).send();
197
+ });
198
+ }
199
+ startHealthChecks() {
200
+ this.pingInterval = setInterval(async () => {
201
+ const agents = await this.store.getAll();
202
+ for (const agent of agents) {
203
+ try {
204
+ const res = await fetch(`${agent.url}/health`);
205
+ const status = res.ok ? "healthy" : "unhealthy";
206
+ await this.store.updateStatus(agent.id, status);
207
+ } catch (error) {
208
+ await this.store.updateStatus(agent.id, "unhealthy");
209
+ logger.warn("Agent unreachable", { agentId: agent.id, error: String(error) });
210
+ }
211
+ }
212
+ }, 3e4);
213
+ }
214
+ start(port) {
215
+ this.startHealthChecks();
216
+ return this.app.listen(port, () => {
217
+ logger.info("Registry Server listening", { port });
218
+ });
219
+ }
220
+ stop() {
221
+ if (this.pingInterval) {
222
+ clearInterval(this.pingInterval);
223
+ }
224
+ }
225
+ emitRegistryEvent(payload) {
226
+ this.events.emit("registry_update", payload);
227
+ }
228
+ toRegisteredAgent(agentUrl, card) {
229
+ const tags = (card.skills ?? []).flatMap((skill) => skill.tags ?? []);
230
+ const skills = (card.skills ?? []).map((skill) => skill.name);
231
+ return {
232
+ id: randomUUID(),
233
+ url: agentUrl,
234
+ card,
235
+ status: "unknown",
236
+ tags,
237
+ skills,
238
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
239
+ };
240
+ }
241
+ }
242
+
243
+ class RedisStorage {
244
+ constructor(client, prefix = "a2a:registry") {
245
+ this.client = client;
246
+ this.prefix = prefix;
247
+ }
248
+ async upsert(agent) {
249
+ await this.client.set(this.key(agent.id), JSON.stringify(agent));
250
+ return agent;
251
+ }
252
+ async get(id) {
253
+ const value = await this.client.get(this.key(id));
254
+ return value ? JSON.parse(value) : null;
255
+ }
256
+ async getAll() {
257
+ const keys = await this.client.keys(this.key("*"));
258
+ const values = await Promise.all(keys.map((key) => this.client.get(key)));
259
+ return values.filter((value) => typeof value === "string").map((value) => JSON.parse(value));
260
+ }
261
+ async delete(id) {
262
+ return await this.client.del(this.key(id)) > 0;
263
+ }
264
+ async updateStatus(id, status) {
265
+ const current = await this.get(id);
266
+ if (current) {
267
+ await this.upsert({ ...current, status });
268
+ }
269
+ }
270
+ async findBySkill(skill) {
271
+ const normalized = skill.toLowerCase();
272
+ const agents = await this.getAll();
273
+ return agents.filter(
274
+ (agent) => agent.skills.some((value) => value.toLowerCase().includes(normalized))
275
+ );
276
+ }
277
+ key(id) {
278
+ return `${this.prefix}:${id}`;
279
+ }
280
+ }
281
+
282
+ export { InMemoryStorage, RedisStorage, RegistryServer, SkillMatcher };
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@oaslananka/registry",
3
+ "version": "1.0.0",
4
+ "description": "Agent registry, discovery API, SSE updates and storage backends for A2A runtimes",
5
+ "keywords": [
6
+ "a2a",
7
+ "agent2agent",
8
+ "registry",
9
+ "discovery",
10
+ "typescript"
11
+ ],
12
+ "author": "oaslananka",
13
+ "license": "Apache-2.0",
14
+ "homepage": "https://github.com/oaslananka/a2a-mesh#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/oaslananka/a2a-mesh.git",
18
+ "directory": "packages/registry"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/oaslananka/a2a-mesh/issues"
22
+ },
23
+ "main": "./dist/index.cjs",
24
+ "module": "./dist/index.mjs",
25
+ "types": "dist/index.d.ts",
26
+ "sideEffects": false,
27
+ "scripts": {
28
+ "build": "unbuild",
29
+ "typecheck": "tsc -b",
30
+ "test": "vitest run"
31
+ },
32
+ "dependencies": {
33
+ "@oaslananka/core": "^1.0.0",
34
+ "express": "^4.18.2",
35
+ "cors": "^2.8.5",
36
+ "uuid": "^9.0.1"
37
+ },
38
+ "devDependencies": {
39
+ "@types/express": "^4.17.21",
40
+ "@types/cors": "^2.8.17",
41
+ "@types/uuid": "^9.0.8",
42
+ "typescript": "^5.2.2"
43
+ },
44
+ "type": "module",
45
+ "engines": {
46
+ "node": ">=20.0.0"
47
+ },
48
+ "exports": {
49
+ ".": {
50
+ "import": "./dist/index.mjs",
51
+ "require": "./dist/index.cjs",
52
+ "types": "./dist/index.d.ts"
53
+ }
54
+ },
55
+ "module": "./dist/index.mjs",
56
+ "files": [
57
+ "dist",
58
+ "README.md",
59
+ "LICENSE"
60
+ ]
61
+ }