agent-relay-server 0.105.2 → 0.106.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/docs/openapi.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "openapi": "3.1.0",
3
3
  "info": {
4
4
  "title": "Agent Relay API",
5
- "version": "0.105.2",
5
+ "version": "0.106.0",
6
6
  "description": "Real-time message bus for inter-agent communication. Agent-first: this spec is designed for machine consumption — agents can self-discover the full API surface via GET /api/spec.",
7
7
  "license": {
8
8
  "name": "MIT",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-relay-server",
3
- "version": "0.105.2",
3
+ "version": "0.106.0",
4
4
  "description": "Lightweight HTTP message relay for inter-agent communication across machines",
5
5
  "module": "src/index.ts",
6
6
  "type": "module",
@@ -36,6 +36,7 @@
36
36
  "CONTRIBUTING.md"
37
37
  ],
38
38
  "dependencies": {
39
+ "agent-relay-channels-host": "0.106.0",
39
40
  "agent-relay-providers": "0.104.0",
40
41
  "agent-relay-sdk": "0.2.92",
41
42
  "ajv": "^8.20.0"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agent-relay-runner",
3
3
  "description": "Thin Agent Relay runner bridge for Claude Code",
4
- "version": "0.105.2",
4
+ "version": "0.106.0",
5
5
  "agentRelayContracts": {
6
6
  "providerPluginProtocol": 1
7
7
  }
@@ -1035,6 +1035,17 @@ var NOTIFICATION_NUDGE = "\u21AA Notification \u2014 no reply needed.";
1035
1035
  function isNotificationMessage(message) {
1036
1036
  return isPersistedRelayMessage(message) && message.replyExpected === false;
1037
1037
  }
1038
+ function dedupePersistedMessages(messages2) {
1039
+ const seen = new Set;
1040
+ return messages2.filter((message) => {
1041
+ if (!isPersistedRelayMessage(message))
1042
+ return true;
1043
+ if (seen.has(message.id))
1044
+ return false;
1045
+ seen.add(message.id);
1046
+ return true;
1047
+ });
1048
+ }
1038
1049
  function providerAttachmentText(message) {
1039
1050
  const refs = attachmentRefs(message);
1040
1051
  if (!refs.length)
@@ -1165,11 +1176,12 @@ function replyReminder(message, readOnly) {
1165
1176
  }
1166
1177
  function claudeProviderMessageText(messages2, options) {
1167
1178
  const relaySurface = options.relaySurface !== false;
1168
- const sections = messages2.map((message) => formatMessage(message, relaySurface));
1169
- const replyable = latestReplyableMessage(messages2);
1179
+ const uniqueMessages = dedupePersistedMessages(messages2);
1180
+ const sections = uniqueMessages.map((message) => formatMessage(message, relaySurface));
1181
+ const replyable = latestReplyableMessage(uniqueMessages);
1170
1182
  if (relaySurface && replyable && shouldShowReplyReminder(options.deliveryCount)) {
1171
1183
  sections.push(replyReminder(replyable, options.readOnly === true));
1172
- } else if (relaySurface && !replyable && messages2.some(isNotificationMessage)) {
1184
+ } else if (relaySurface && !replyable && uniqueMessages.some(isNotificationMessage)) {
1173
1185
  sections.push(NOTIFICATION_NUDGE);
1174
1186
  }
1175
1187
  return sections.join(`
@@ -304,6 +304,16 @@ function latestReplyableMessage(messages: Message[]): Message | undefined {
304
304
  .at(-1);
305
305
  }
306
306
 
307
+ export function dedupePersistedMessages(messages: Message[]): Message[] {
308
+ const seen = new Set<number>();
309
+ return messages.filter((message) => {
310
+ if (!isPersistedRelayMessage(message)) return true;
311
+ if (seen.has(message.id)) return false;
312
+ seen.add(message.id);
313
+ return true;
314
+ });
315
+ }
316
+
307
317
  function providerSenderLabel(message: Message): string {
308
318
  if (message.from === "user") return "human user";
309
319
  const source = isRecord(message.payload?.source) ? message.payload.source : undefined;
@@ -356,9 +366,10 @@ export function providerAttachmentText(message: Message): string | undefined {
356
366
  }
357
367
 
358
368
  export function providerMessageText(messages: Message[]): string {
359
- const replyable = latestReplyableMessage(messages);
369
+ const uniqueMessages = dedupePersistedMessages(messages);
370
+ const replyable = latestReplyableMessage(uniqueMessages);
360
371
  const maxChars = providerMessageBodyMaxChars();
361
- const sections = messages
372
+ const sections = uniqueMessages
362
373
  .map((message) => {
363
374
  const subject = message.subject ? `Subject: ${message.subject}\n` : "";
364
375
  const isMemoryContext = isMemoryInjection(message);
@@ -404,7 +415,7 @@ export function providerMessageText(messages: Message[]): string {
404
415
  "If you already delivered the useful response through Relay, do not send a separate status-only confirmation.",
405
416
  "If multiple messages arrived together, cover them in one reply instead of answering each line separately.",
406
417
  ].join("\n"));
407
- } else if (messages.some(isNotificationMessage)) {
418
+ } else if (uniqueMessages.some(isNotificationMessage)) {
408
419
  // #283 — pure notification batch: no scaffold, just the one-line no-reply nudge.
409
420
  sections.push(NOTIFICATION_NUDGE);
410
421
  }
package/src/connectors.ts CHANGED
@@ -6,6 +6,7 @@ import { ValidationError } from "./db";
6
6
  import { isRecord } from "agent-relay-sdk";
7
7
  import { registerConnectorConfigSetting, validateConnectorConfig } from "./settings/modules";
8
8
  import { connectorActionTimeoutMs as configuredConnectorActionTimeoutMs, connectorsDirFromEnv } from "./config";
9
+ import { getConfig } from "./config-store";
9
10
 
10
11
  const CONNECTOR_SCHEMA = "agent-relay.connector.v1";
11
12
  const VALID_KINDS = new Set(["channel", "event", "provider", "orchestrator"]);
@@ -248,13 +249,124 @@ async function refreshConnectorStatus(id: string): Promise<void> {
248
249
  }
249
250
 
250
251
  export function startConnectorStatusPoller(): void {
251
- // Relaunch connectors that were running before this process restarted (e.g. a
252
- // deploy that took down the relay/orchestrator tree) BEFORE the first status
253
- // poll overwrites their persisted "running" flag with the now-dead reality.
254
- void reconcileConnectorsOnBoot().finally(() => void refreshAllConnectorStatuses());
252
+ // 1. Auto-register + auto-start the bundled channels host so ntfy/webhook egress
253
+ // survives a deploy/restart with NO manual `register`/`start` (issue #794). Core
254
+ // removed its in-core ntfy transport (v0.102.0), so this connector IS the egress
255
+ // path now. Runs BEFORE reconcile so a fresh install is registered before the
256
+ // boot relaunch + first status poll observe it.
257
+ // 2. Relaunch connectors that were running before this process restarted (e.g. a
258
+ // deploy that took down the relay/orchestrator tree) BEFORE the first status
259
+ // poll overwrites their persisted "running" flag with the now-dead reality.
260
+ void ensureChannelsHostConnector()
261
+ .catch(() => {})
262
+ .finally(() => void reconcileConnectorsOnBoot().finally(() => void refreshAllConnectorStatuses()));
255
263
  setInterval(() => void refreshAllConnectorStatuses(), STATUS_POLL_INTERVAL_MS);
256
264
  }
257
265
 
266
+ const CHANNELS_HOST_ID = "channels-host";
267
+ const CHANNELS_HOST_PACKAGE = "agent-relay-channels-host";
268
+ // The legacy in-core ntfy channel persisted its settings here (src/ntfy.ts, removed in
269
+ // v0.102.0). We migrate that value into the channels-host connector config on first
270
+ // registration so an operator's existing ntfy setup keeps working after the cutover.
271
+ const LEGACY_NTFY_NAMESPACE = "channel-type";
272
+ const LEGACY_NTFY_KEY = "ntfy";
273
+
274
+ /**
275
+ * Resolve the DEPLOYED channels-host CLI entry. In the published runtime it lives at
276
+ * `~/.agent-relay/runtime/node_modules/agent-relay-channels-host` (a dependency of
277
+ * agent-relay-server); in the dev tree it resolves to the workspace symlink. Returns
278
+ * null when the package isn't installed (e.g. a server checkout without the workspace
279
+ * dep) so boot stays a no-op rather than throwing.
280
+ */
281
+ function resolveChannelsHostEntry(): string | null {
282
+ try {
283
+ const pkgJsonPath = Bun.resolveSync(`${CHANNELS_HOST_PACKAGE}/package.json`, import.meta.dir);
284
+ const pkgDir = dirname(pkgJsonPath);
285
+ const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8")) as { bin?: Record<string, string> | string };
286
+ const binRel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.[CHANNELS_HOST_PACKAGE] ?? "src/index.ts";
287
+ return join(pkgDir, binRel);
288
+ } catch {
289
+ return null;
290
+ }
291
+ }
292
+
293
+ /** Ask the deployed binary for its aggregated connector manifest (single source of truth). */
294
+ async function loadChannelsHostManifest(entry: string): Promise<ConnectorManifest | null> {
295
+ try {
296
+ const proc = Bun.spawn({
297
+ cmd: ["bun", entry, "manifest"],
298
+ stdout: "pipe",
299
+ stderr: "ignore",
300
+ env: { ...process.env, AGENT_RELAY_CONNECTOR_ID: CHANNELS_HOST_ID, AGENT_RELAY_CONNECTORS_DIR: connectorRegistryDir() },
301
+ });
302
+ const timeout = setTimeout(() => proc.kill(), connectorActionTimeoutMs());
303
+ const [exitCode, stdout] = await Promise.all([proc.exited, new Response(proc.stdout).text()]);
304
+ clearTimeout(timeout);
305
+ if (exitCode !== 0) return null;
306
+ const parsed = parseJsonMaybe(stdout.trim());
307
+ const manifest = isRecord(parsed) && isRecord(parsed.manifest) ? parsed.manifest : parsed;
308
+ return normalizeConnectorManifest(manifest);
309
+ } catch {
310
+ return null;
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Migrate the legacy core ntfy settings (`channel-type/ntfy`) into channels-host
316
+ * connector config keys. Only an ENABLED legacy channel is migrated — a disabled one
317
+ * stays disabled (channels-host treats a missing NTFY_TOPIC as "off"), preserving
318
+ * operator intent. Returns undefined when there's nothing (active) to carry over.
319
+ */
320
+ export function migrateLegacyNtfyConfig(): Record<string, unknown> | undefined {
321
+ const legacy = getConfig<Record<string, unknown>>(LEGACY_NTFY_NAMESPACE, LEGACY_NTFY_KEY)?.value;
322
+ if (!isRecord(legacy) || legacy.enabled !== true) return undefined;
323
+ const config: Record<string, string> = {};
324
+ const topic = typeof legacy.topic === "string" ? legacy.topic.trim() : "";
325
+ if (!topic) return undefined; // no topic → nothing the adapter can act on
326
+ config.NTFY_TOPIC = topic;
327
+ if (typeof legacy.serverUrl === "string" && legacy.serverUrl.trim()) config.NTFY_SERVER_URL = legacy.serverUrl.trim();
328
+ if (Array.isArray(legacy.defaultTags) && legacy.defaultTags.length) {
329
+ config.NTFY_DEFAULT_TAGS = legacy.defaultTags.filter((t): t is string => typeof t === "string").join(",");
330
+ }
331
+ if (typeof legacy.defaultClick === "string" && legacy.defaultClick.trim()) config.NTFY_DEFAULT_CLICK = legacy.defaultClick.trim();
332
+ if (typeof legacy.timeoutMs === "number" && Number.isFinite(legacy.timeoutMs)) config.NTFY_TIMEOUT_MS = String(legacy.timeoutMs);
333
+ // The legacy config stored the *name* of an env var holding the token, not the token
334
+ // itself; resolve it if that env var is present so the credential carries over.
335
+ if (typeof legacy.tokenEnv === "string" && legacy.tokenEnv.trim()) {
336
+ const token = process.env[legacy.tokenEnv.trim()];
337
+ if (token && token.trim()) config.NTFY_TOKEN = token.trim();
338
+ }
339
+ return config;
340
+ }
341
+
342
+ /**
343
+ * Auto-register and auto-start the channels host on boot (issue #794). Idempotent:
344
+ * - registers/refreshes the manifest from the deployed binary every boot (keeps the
345
+ * binary path + version current across upgrades) without clobbering existing config;
346
+ * - seeds config from the legacy core ntfy setting only on first registration;
347
+ * - starts the daemon unless an operator deliberately stopped it (state.running === false).
348
+ */
349
+ export async function ensureChannelsHostConnector(): Promise<void> {
350
+ const entry = resolveChannelsHostEntry();
351
+ if (!entry) return; // package not installed in this runtime — nothing to bring up
352
+ const existing = getConnector(CHANNELS_HOST_ID);
353
+ const manifest = await loadChannelsHostManifest(entry);
354
+ if (!manifest) return;
355
+
356
+ const hasConfig = isRecord(existing?.config) && Object.keys(existing.config).length > 0;
357
+ const seedConfig = hasConfig ? undefined : migrateLegacyNtfyConfig();
358
+ registerConnectorManifest(manifest, seedConfig ? { config: seedConfig } : {});
359
+
360
+ // Bring it up by default; respect a deliberate stop (persisted running:false).
361
+ const deliberatelyStopped = existing?.state?.running === false;
362
+ if (deliberatelyStopped) return;
363
+ try {
364
+ await runConnectorAction(CHANNELS_HOST_ID, "start");
365
+ } catch {
366
+ /* best-effort; the status poll surfaces failures */
367
+ }
368
+ }
369
+
258
370
  // On boot, bring back any connector whose last persisted state says it was
259
371
  // running. `start` is idempotent — a daemon that survived the restart reports
260
372
  // "already running"; one that died with the process tree is relaunched. A
@@ -8,7 +8,8 @@
8
8
  // the ntfy event payload { title, body, priority?, tags?, click? }. Same tool name
9
9
  // and args as before; async ("accepted for delivery"). Zero ntfy HTTP transport in core.
10
10
  //
11
- // Both tools use notifications:write scope (aliased; DECISION LOCKED — #773).
11
+ // relay_send_to_channel uses channel:egress (least-privilege split — #792).
12
+ // relay_notify_ntfy stays on notifications:write (operator-notification shim — #773).
12
13
 
13
14
  import { MAX_BODY_BYTES } from "./config";
14
15
  import { getChannel, sendMessage, ValidationError } from "./db";
@@ -27,7 +28,7 @@ export const EGRESS_TOOLS: ToolDefinition[] = [
27
28
  {
28
29
  name: "relay_send_to_channel",
29
30
  description: "Send an outbound message to a registered channel agent (e.g. ntfy, webhook). channelId is the channel agent ID; event is an opaque payload the adapter interprets.",
30
- requiredScopes: ["notifications:write"],
31
+ requiredScopes: ["channel:egress"],
31
32
  inputSchema: {
32
33
  type: "object",
33
34
  properties: {
@@ -100,7 +100,7 @@ export function routeNotification(input: RouteNotificationInput): Message[] {
100
100
  subject: input.message.subject,
101
101
  body: input.message.body,
102
102
  payload: { ...(input.message.payload ?? {}), routing: compactRoutingExplanation(routing) },
103
- idempotencyKey: input.message.idempotencyKey,
103
+ idempotencyKey: recipientScopedIdempotencyKey(input.message.idempotencyKey, routing.recipient),
104
104
  kind: input.message.kind,
105
105
  from: input.message.from,
106
106
  replyExpected: input.message.replyExpected,
@@ -111,6 +111,11 @@ export function routeNotification(input: RouteNotificationInput): Message[] {
111
111
  });
112
112
  }
113
113
 
114
+ function recipientScopedIdempotencyKey(key: string | undefined, recipient: string): string | undefined {
115
+ if (!key) return undefined;
116
+ return `${key}:recipient:${recipient}`;
117
+ }
118
+
114
119
  export function previewNotificationRouting(input: Pick<RouteNotificationInput, "type" | "scope" | "recipients">): NotificationRoutingPreview {
115
120
  const candidates = normalizeRoutingRecipients(input);
116
121
  const recipients: NotificationRoutingExplanation[] = [];
package/src/notify.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { sendMessage } from "./db";
1
+ import { sendMessageWithResult } from "./db";
2
2
  import { emitNewMessage } from "./sse";
3
3
  import type { Message, MessageKind } from "./types";
4
4
 
@@ -34,7 +34,7 @@ interface SystemNotifyOptions {
34
34
  * recipient is offline (#234). Used by the GC sweep (maintenance) and lifecycle events (#239).
35
35
  */
36
36
  export function notifySystemMessage(to: string, opts: SystemNotifyOptions): Message {
37
- const msg = sendMessage({
37
+ const result = sendMessageWithResult({
38
38
  from: opts.from ?? "system",
39
39
  to,
40
40
  kind: opts.kind ?? "system",
@@ -45,6 +45,6 @@ export function notifySystemMessage(to: string, opts: SystemNotifyOptions): Mess
45
45
  replyExpected: opts.replyExpected,
46
46
  maxAgeSeconds: opts.maxAgeSeconds,
47
47
  });
48
- emitNewMessage(msg);
49
- return msg;
48
+ if (result.created || result.updated) emitNewMessage(result.message);
49
+ return result.message;
50
50
  }
@@ -247,6 +247,7 @@ function emitBandTransition(input: {
247
247
 
248
248
  const recipients = getSpawnCapableAgentIds();
249
249
  if (recipients.length === 0) return;
250
+ if (!shouldPushBandTransition(window.band, direction)) return;
250
251
 
251
252
  routeNotification({
252
253
  type: "routing.quota.band_transition",
@@ -256,12 +257,17 @@ function emitBandTransition(input: {
256
257
  subject: `${providerLabel(provider)} ${window.role} quota band → ${window.band}`,
257
258
  body: buildBody(input),
258
259
  payload,
260
+ idempotencyKey: `routing.quota.band_transition:${provider}:${window.role}:${window.band}`,
259
261
  replyExpected: false,
260
262
  },
261
263
  emittedAt: now,
262
264
  });
263
265
  }
264
266
 
267
+ function shouldPushBandTransition(newBand: QuotaBand, direction: "degraded" | "recovered"): boolean {
268
+ return direction === "degraded" && bandRank(newBand) >= bandRank("caution");
269
+ }
270
+
265
271
  function buildBody(input: {
266
272
  provider: string;
267
273
  window: ProviderBandWindow;
package/src/token-db.ts CHANGED
@@ -78,7 +78,7 @@ const BUILT_IN_PROFILES: Array<Omit<TokenProfile, "createdAt" | "updatedAt">> =
78
78
  name: "Provider Agent",
79
79
  description: "Coding-agent runtime access for messages, commands, tasks, and scoped memory reads.",
80
80
  role: "provider",
81
- scope: ["agent:read", "agent:write", "message:read", "message:send", "schedule:write", "command:read", "command:write", "task:read", "task:write", "memory:read", "artifact:read", "artifact:write", "mcp:use", "plans:read", "plans:write", "teams:read", "teams:write", "blackboard:read", "blackboard:write", "project:read", "project:write", "issue:read", "issue:write", "notifications:read", "notifications:write", "insights:write", "quota:write"],
81
+ scope: ["agent:read", "agent:write", "message:read", "message:send", "schedule:write", "command:read", "command:write", "task:read", "task:write", "memory:read", "artifact:read", "artifact:write", "mcp:use", "plans:read", "plans:write", "teams:read", "teams:write", "blackboard:read", "blackboard:write", "project:read", "project:write", "issue:read", "issue:write", "notifications:read", "notifications:write", "channel:egress", "insights:write", "quota:write"],
82
82
  ttlSeconds: 24 * 60 * 60,
83
83
  builtIn: true,
84
84
  createdBy: "system",
@@ -88,7 +88,7 @@ const BUILT_IN_PROFILES: Array<Omit<TokenProfile, "createdAt" | "updatedAt">> =
88
88
  name: "Provider Child Agent",
89
89
  description: "Delegated child-agent runtime access, constrained to its parent and spawn request.",
90
90
  role: "provider",
91
- scope: ["agent:read", "agent:write", "message:read", "message:send", "schedule:write", "command:read", "command:write", "task:read", "task:write", "memory:read", "artifact:read", "artifact:write", "mcp:use", "teams:read", "blackboard:read", "blackboard:write", "project:read", "project:write", "issue:read", "issue:write", "notifications:read", "notifications:write", "insights:write", "quota:write"],
91
+ scope: ["agent:read", "agent:write", "message:read", "message:send", "schedule:write", "command:read", "command:write", "task:read", "task:write", "memory:read", "artifact:read", "artifact:write", "mcp:use", "teams:read", "blackboard:read", "blackboard:write", "project:read", "project:write", "issue:read", "issue:write", "notifications:read", "notifications:write", "channel:egress", "insights:write", "quota:write"],
92
92
  constraints: { canDelegate: false },
93
93
  ttlSeconds: 2 * 60 * 60,
94
94
  builtIn: true,
@@ -99,7 +99,7 @@ const BUILT_IN_PROFILES: Array<Omit<TokenProfile, "createdAt" | "updatedAt">> =
99
99
  name: "Provider Interactive Agent",
100
100
  description: "User-launched provider runtime access constrained to its own agent and cwd for long interactive sessions.",
101
101
  role: "provider",
102
- scope: ["agent:read", "agent:write", "message:read", "message:send", "schedule:write", "command:read", "command:write", "task:read", "task:write", "memory:read", "artifact:read", "artifact:write", "mcp:use", "teams:read", "blackboard:read", "blackboard:write", "project:read", "project:write", "issue:read", "issue:write", "notifications:read", "notifications:write", "insights:write", "quota:write"],
102
+ scope: ["agent:read", "agent:write", "message:read", "message:send", "schedule:write", "command:read", "command:write", "task:read", "task:write", "memory:read", "artifact:read", "artifact:write", "mcp:use", "teams:read", "blackboard:read", "blackboard:write", "project:read", "project:write", "issue:read", "issue:write", "notifications:read", "notifications:write", "channel:egress", "insights:write", "quota:write"],
103
103
  constraints: { terminalAttach: false, logsRead: false, canDelegate: false },
104
104
  ttlSeconds: 30 * 24 * 60 * 60,
105
105
  builtIn: true,