@chankov/agent-fleet 0.0.1 → 0.0.3

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 (65) hide show
  1. package/.claude/commands/doctor-agent-fleet.md +1 -1
  2. package/.claude/commands/setup-agent-fleet.md +4 -4
  3. package/.opencode/commands/af-doctor-agent-fleet.md +2 -0
  4. package/.opencode/commands/af-setup-agent-fleet.md +1 -1
  5. package/.pi/agents/model-profiles.yaml +12 -12
  6. package/.pi/agents/peers.yaml +26 -22
  7. package/.pi/agents/teams.yaml +2 -2
  8. package/.pi/harnesses/agent-hub/README.md +57 -4
  9. package/.pi/harnesses/agent-hub/index.ts +236 -80
  10. package/.pi/harnesses/agent-hub/research-retention.js +34 -0
  11. package/.pi/harnesses/ask-user-remote/README.md +8 -0
  12. package/.pi/harnesses/ask-user-remote/index.ts +41 -1
  13. package/.pi/harnesses/coms/README.md +11 -0
  14. package/.pi/prompts/doctor-agent-fleet.md +1 -1
  15. package/.pi/prompts/setup-agent-fleet.md +4 -4
  16. package/README.md +133 -354
  17. package/agents/architect.md +4 -2
  18. package/agents/bowser.md +2 -1
  19. package/agents/builder.md +3 -2
  20. package/agents/code-reviewer.md +7 -7
  21. package/agents/deep-researcher.md +3 -3
  22. package/agents/documenter.md +3 -1
  23. package/agents/orchestrator.md +5 -3
  24. package/agents/plan-reviewer.md +5 -5
  25. package/agents/planner.md +7 -7
  26. package/agents/releaser.md +3 -1
  27. package/agents/researcher.md +3 -3
  28. package/agents/security-auditor.md +7 -7
  29. package/agents/test-engineer.md +5 -5
  30. package/agents/web-debugger.md +3 -3
  31. package/agents/web-performance-auditor.md +3 -3
  32. package/bin/snapshot-version.js +17 -1
  33. package/codex/CONDUCTOR.md +148 -0
  34. package/docs/ARCHITECTURE.md +165 -0
  35. package/docs/agent-fleet-setup.md +1 -0
  36. package/docs/claude-code-coms-bridge.md +10 -0
  37. package/docs/codex-remote-conductor.md +170 -0
  38. package/docs/coms-hermes-bridge.md +121 -0
  39. package/docs/getting-started.md +14 -0
  40. package/docs/npm-install.md +2 -0
  41. package/docs/pi-extensions.md +16 -0
  42. package/docs/pi-setup.md +2 -0
  43. package/hermes/README.md +48 -0
  44. package/hermes/skills/hub-conductor/SKILL.md +84 -0
  45. package/hermes/skills/hub-liaison/SKILL.md +84 -0
  46. package/justfile +132 -15
  47. package/package.json +10 -3
  48. package/scripts/codex-conductor.ts +41 -0
  49. package/scripts/codex-remote-control.ts +167 -0
  50. package/scripts/coms-cli.ts +311 -199
  51. package/scripts/coms-hermes-bridge.ts +8 -4
  52. package/scripts/lib/codex-conductor.ts +88 -0
  53. package/scripts/lib/codex-remote-control.ts +480 -0
  54. package/scripts/lib/coms-envelope.ts +51 -6
  55. package/scripts/lib/herdr-layout.ts +35 -7
  56. package/scripts/lib/hermes-bridge-core.ts +4 -4
  57. package/scripts/lib/spawn-stagger.ts +101 -0
  58. package/scripts/lib/team-project.ts +112 -3
  59. package/scripts/lib/team-snapshot.ts +3 -2
  60. package/scripts/team-snapshot.ts +23 -6
  61. package/scripts/team-up.ts +106 -18
  62. package/skills/guided-workspace-setup/SKILL.md +123 -97
  63. package/skills/guided-workspace-setup/companion-manifest.json +33 -0
  64. package/skills/peer-coms/SKILL.md +9 -0
  65. package/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
@@ -1,23 +1,9 @@
1
1
  // scripts/coms-cli.ts
2
2
  //
3
- // Envelope-protocol CLI: lets a NON-pi process (a plain shell, Claude Code
4
- // via the peer-coms skill) participate in the coms pool. Speaks the exact
5
- // coms wire protocol (scripts/lib/coms-envelope.ts) over the existing
6
- // registry + unix sockets.
3
+ // Envelope-protocol CLI for non-pi participants in a coms pool. Registry and
4
+ // spool paths are always scoped by a validated project and caller name.
7
5
  //
8
- // list — live peers in scope (name, model, purpose)
9
- // send <peer> <prompt> — send a prompt; prints the msg_id and returns
10
- // (a detached waiter holds the reply socket);
11
- // --await blocks and prints the reply instead
12
- // await <msg_id> — block until the reply for msg_id arrives
13
- // reply <msg_id> <text> — answer an inbound prompt (bridge/hook use)
14
- //
15
- // Identity: each invocation acts as peer `--name` (default "claude-cli"),
16
- // registered EXPLICIT — visible to nobody's pool widget, addressable only by
17
- // exact name — and read-only toward the registry except its own entry.
18
- //
19
- // usage: coms-cli <list|send|await|reply> [args] [--project <p>] [--name <me>]
20
- // [--await] [--timeout <ms>] [--all]
6
+ // usage: coms-cli <list|send|await|reply> [args] --project <p> --name <me>
21
7
 
22
8
  import { spawn } from "node:child_process";
23
9
  import * as fs from "node:fs";
@@ -39,6 +25,8 @@ import {
39
25
  removeRegistryEntry,
40
26
  sendEnvelope,
41
27
  ulid,
28
+ validateComsName,
29
+ validateComsProject,
42
30
  writeAck,
43
31
  writeNack,
44
32
  writeRegistryAtomic,
@@ -46,46 +34,112 @@ import {
46
34
  type SenderIdentity,
47
35
  } from "./lib/coms-envelope.ts";
48
36
 
49
- const DEFAULT_NAME = process.env.COMS_CLI_NAME || "claude-cli";
37
+ const DEFAULT_NAME = "claude-cli";
38
+ const DEFAULT_PROJECT = "default";
50
39
  const DEFAULT_AWAIT_MS = 300_000;
40
+ const MAX_TIMEOUT_MS = 0x7fffffff;
41
+ const COMS_ID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/;
42
+
43
+ type FlagName = "project" | "name" | "await" | "timeout" | "all" | "conductor" | "session" | "ttl";
44
+
45
+ interface ParsedArgs {
46
+ positionals: string[];
47
+ flags: Map<FlagName, string | true>;
48
+ }
49
+
50
+ interface Scope {
51
+ project: string;
52
+ name: string;
53
+ includeExplicit: boolean;
54
+ }
55
+
56
+ interface CodexLock {
57
+ release(): void;
58
+ }
59
+
60
+ function fail(message: string): never {
61
+ throw new Error(message);
62
+ }
63
+
64
+ function parseArgs(argv: string[], allowed: readonly FlagName[]): ParsedArgs {
65
+ const allowedFlags = new Set<FlagName>(allowed);
66
+ const flags = new Map<FlagName, string | true>();
67
+ const positionals: string[] = [];
68
+ for (let i = 0; i < argv.length; i++) {
69
+ const arg = argv[i];
70
+ if (!arg.startsWith("--")) {
71
+ positionals.push(arg);
72
+ continue;
73
+ }
74
+ const flag = arg.slice(2) as FlagName;
75
+ if (!allowedFlags.has(flag)) fail(`unknown flag: ${arg}`);
76
+ if (flags.has(flag)) fail(`--${flag} may only be provided once`);
77
+ if (flag === "await" || flag === "all") {
78
+ flags.set(flag, true);
79
+ continue;
80
+ }
81
+ const value = argv[i + 1];
82
+ if (!value || value.startsWith("--")) fail(`--${flag} requires a value`);
83
+ flags.set(flag, value);
84
+ i++;
85
+ }
86
+ return { positionals, flags };
87
+ }
88
+
89
+ function flagValue(parsed: ParsedArgs, flag: FlagName): string | undefined {
90
+ const value = parsed.flags.get(flag);
91
+ return typeof value === "string" ? value : undefined;
92
+ }
93
+
94
+ function scopeFrom(parsed: ParsedArgs): Scope {
95
+ const project = validateComsProject(flagValue(parsed, "project") ?? process.env.COMS_CLI_PROJECT ?? DEFAULT_PROJECT);
96
+ const name = validateComsName(flagValue(parsed, "name") ?? process.env.COMS_CLI_NAME ?? DEFAULT_NAME);
97
+ return { project, name, includeExplicit: parsed.flags.get("all") === true };
98
+ }
99
+
100
+ function timeoutFrom(parsed: ParsedArgs, flag: "timeout" | "ttl" = "timeout"): number {
101
+ const raw = flagValue(parsed, flag) ?? process.env.PI_COMS_TIMEOUT_MS ?? String(DEFAULT_AWAIT_MS);
102
+ if (!/^\d+$/.test(raw)) fail(`Invalid timeout: ${JSON.stringify(raw)} (use a positive integer no greater than ${MAX_TIMEOUT_MS})`);
103
+ const timeoutMs = Number(raw);
104
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMEOUT_MS) {
105
+ fail(`Invalid timeout: ${JSON.stringify(raw)} (use a positive integer no greater than ${MAX_TIMEOUT_MS})`);
106
+ }
107
+ return timeoutMs;
108
+ }
51
109
 
52
- function flagValue(argv: string[], flag: string): string | null {
53
- const i = argv.indexOf(flag);
54
- return i >= 0 && i + 1 < argv.length ? argv[i + 1] : null;
110
+ function validateComsId(value: string, label: "msg_id" | "listen session"): string {
111
+ if (!COMS_ID_RE.test(value)) fail(`Invalid ${label}: ${JSON.stringify(value)} (expected a 26-character Crockford ULID)`);
112
+ return value;
55
113
  }
56
114
 
57
- function die(msg: string): never {
58
- console.error(msg);
59
- process.exit(1);
115
+ function spoolDir(project: string, name: string): string {
116
+ return path.join(COMS_DIR, "cli", "projects", validateComsProject(project), validateComsName(name));
60
117
  }
61
118
 
62
- function spoolDir(name: string): string {
63
- return path.join(COMS_DIR, "cli", name);
119
+ function legacySpoolDir(name: string): string {
120
+ return path.join(COMS_DIR, "cli", validateComsName(name));
64
121
  }
65
122
 
66
- function ensureSpool(name: string): { pending: string; responses: string; inbound: string } {
67
- const base = spoolDir(name);
123
+ function ensureSpool(project: string, name: string): { pending: string; responses: string; inbound: string } {
124
+ const base = spoolDir(project, name);
125
+ const legacy = legacySpoolDir(name);
126
+ // A legacy name-only queue cannot be assigned to a project safely. Refuse
127
+ // rather than consuming it under whichever project happens to run first.
128
+ if (fs.existsSync(legacy)) {
129
+ fail(`Legacy name-only coms spool exists at ${legacy}; stop that identity, inspect the queue, and move the complete directory under cli/projects/<project>/<name> after confirming its project. Do not delete ambiguous pending data.`);
130
+ }
68
131
  const dirs = {
69
132
  pending: path.join(base, "pending"),
70
133
  responses: path.join(base, "responses"),
71
134
  inbound: path.join(base, "inbound"),
72
135
  };
73
- for (const d of Object.values(dirs)) fs.mkdirSync(d, { recursive: true });
136
+ for (const dir of Object.values(dirs)) fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
74
137
  return dirs;
75
138
  }
76
139
 
77
- interface Scope {
78
- project: string;
79
- includeExplicit: boolean;
80
- }
81
-
82
- function scopeFrom(argv: string[]): Scope {
83
- return { project: flagValue(argv, "--project") ?? "default", includeExplicit: argv.includes("--all") };
84
- }
85
-
86
- function peersInScope(scope: Scope, selfName: string): RegistryEntry[] {
140
+ function peersInScope(scope: Scope): RegistryEntry[] {
87
141
  return pruneDeadEntries(scope.project).filter(
88
- (e) => e.name !== selfName && (scope.includeExplicit || !e.explicit),
142
+ (entry) => entry.name !== scope.name && (scope.includeExplicit || !entry.explicit),
89
143
  );
90
144
  }
91
145
 
@@ -110,144 +164,199 @@ function registerCliEntry(id: SenderIdentity, project: string, purpose: string):
110
164
  writeRegistryAtomic(entry, project);
111
165
  }
112
166
 
167
+ function acquireCodexLock(scope: Scope): CodexLock {
168
+ const lockDir = path.join(COMS_DIR, "locks");
169
+ const lockPath = path.join(lockDir, "codex-send.lock");
170
+ fs.mkdirSync(lockDir, { recursive: true, mode: 0o700 });
171
+ try { fs.chmodSync(lockDir, 0o700); } catch { /* best effort */ }
172
+ let fd: number;
173
+ try {
174
+ fd = fs.openSync(lockPath, "wx", 0o600);
175
+ } catch (err) {
176
+ if ((err as NodeJS.ErrnoException).code === "EEXIST") {
177
+ fail(`Codex send lock is held (or stale) at ${lockPath}; inspect its metadata and remove it manually only after confirming the owner is gone.`);
178
+ }
179
+ throw err;
180
+ }
181
+ try {
182
+ fs.writeFileSync(fd, `${JSON.stringify({ pid: process.pid, started_at: nowIso(), project: scope.project, name: scope.name })}\n`);
183
+ } finally {
184
+ fs.closeSync(fd);
185
+ }
186
+
187
+ let released = false;
188
+ const release = () => {
189
+ if (released) return;
190
+ released = true;
191
+ process.removeListener("SIGTERM", onSigterm);
192
+ process.removeListener("SIGINT", onSigint);
193
+ try { fs.unlinkSync(lockPath); } catch { /* best effort */ }
194
+ };
195
+ const exitForSignal = (signal: NodeJS.Signals) => {
196
+ release();
197
+ process.exit(signal === "SIGINT" ? 130 : 143);
198
+ };
199
+ const onSigterm = () => exitForSignal("SIGTERM");
200
+ const onSigint = () => exitForSignal("SIGINT");
201
+ process.once("SIGTERM", onSigterm);
202
+ process.once("SIGINT", onSigint);
203
+ return { release };
204
+ }
205
+
113
206
  // ━━ list ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
114
207
 
115
208
  function cmdList(argv: string[]): void {
116
- const scope = scopeFrom(argv);
117
- const name = flagValue(argv, "--name") ?? DEFAULT_NAME;
118
- const peers = peersInScope(scope, name);
209
+ const parsed = parseArgs(argv, ["project", "name", "all"]);
210
+ if (parsed.positionals.length > 0) fail("list does not accept positional arguments");
211
+ const scope = scopeFrom(parsed);
212
+ const peers = peersInScope(scope);
119
213
  if (peers.length === 0) {
120
214
  console.log(`(no live peers in project "${scope.project}")`);
121
215
  return;
122
216
  }
123
- for (const p of peers) {
124
- console.log(`${p.name}\t${p.model}\t${p.purpose}`);
125
- }
217
+ for (const peer of peers) console.log(`${peer.name}\t${peer.model}\t${peer.purpose}`);
126
218
  }
127
219
 
128
220
  // ━━ send ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
129
221
 
222
+ function validateCodexMode(parsed: ParsedArgs): boolean {
223
+ const conductor = flagValue(parsed, "conductor");
224
+ if (conductor === undefined) return false;
225
+ if (conductor !== "codex") fail(`Unsupported conductor: ${JSON.stringify(conductor)}`);
226
+ if (!parsed.flags.has("project") || !parsed.flags.has("name") || !parsed.flags.has("timeout") || parsed.flags.get("await") !== true) {
227
+ fail("Codex mode requires explicit --project, --name, --await, and --timeout options.");
228
+ }
229
+ if (parsed.flags.get("all") === true) fail("Codex mode does not allow --all.");
230
+ return true;
231
+ }
232
+
130
233
  async function cmdSend(argv: string[]): Promise<void> {
131
- const positional = argv.filter((a, i) => !a.startsWith("--") && (i === 0 || !argv[i - 1].startsWith("--")));
132
- const [target, ...promptParts] = positional;
234
+ const parsed = parseArgs(argv, ["project", "name", "await", "timeout", "all", "conductor"]);
235
+ const [rawTarget, ...promptParts] = parsed.positionals;
133
236
  const prompt = promptParts.join(" ");
134
- if (!target || !prompt) die("usage: coms-cli send <peer> <prompt…> [--await] [--timeout <ms>]");
135
-
136
- const scope = scopeFrom(argv);
137
- const name = flagValue(argv, "--name") ?? DEFAULT_NAME;
138
- const timeoutMs = Number(flagValue(argv, "--timeout") ?? DEFAULT_AWAIT_MS);
139
- const doAwait = argv.includes("--await");
140
-
141
- const peer = peersInScope(scope, name).find((e) => e.name === target)
142
- ?? pruneDeadEntries(scope.project).find((e) => e.name === target && e.name !== name);
143
- if (!peer) {
144
- const names = peersInScope(scope, name).map((e) => e.name).join(", ") || "(none)";
145
- die(`Peer "${target}" not found in project "${scope.project}". Live peers: ${names}`);
146
- }
237
+ if (!rawTarget || !prompt) fail("usage: coms-cli send <peer> <prompt…> --project <project> --name <name> [--await] [--timeout <ms>]");
238
+ const target = validateComsName(rawTarget);
239
+ const scope = scopeFrom(parsed);
240
+ const timeoutMs = timeoutFrom(parsed);
241
+ const codexMode = validateCodexMode(parsed);
242
+ const lock = codexMode ? acquireCodexLock(scope) : null;
243
+ try {
244
+ // This fresh scoped list is both the only target source and, for Codex,
245
+ // intentionally happens after lock acquisition.
246
+ const peers = peersInScope(scope);
247
+ const peer = peers.find((entry) => entry.name === target);
248
+ if (!peer) {
249
+ const names = peers.map((entry) => entry.name).join(", ") || "(none)";
250
+ fail(`Peer "${target}" not found in project "${scope.project}". Live peers: ${names}`);
251
+ }
147
252
 
148
- ensureComsDirs(scope.project);
149
- const spool = ensureSpool(name);
150
-
151
- if (doAwait) {
152
- // One process does the whole round trip: bind → register → send → wait.
153
- const id = makeIdentity(name, ulid());
154
- let done: (v: { response: unknown; error?: string | null }) => void;
155
- const reply = new Promise<{ response: unknown; error?: string | null }>((res) => (done = res));
156
- const server = await bindEndpoint(
157
- id.endpoint,
158
- makeConnHandler((env, socket) => {
159
- if (isResponseEnvelope(env)) {
160
- writeAck(socket, env.msg_id);
161
- done({ response: env.response, error: env.error ?? null });
162
- } else if ((env as { type?: string }).type === "ping") {
163
- writeAck(socket, (env as { msg_id?: string }).msg_id ?? "");
164
- } else {
165
- writeNack(socket, (env as { msg_id?: string }).msg_id ?? "", "cli awaits responses only");
166
- }
167
- }),
253
+ ensureComsDirs(scope.project);
254
+ const spool = ensureSpool(scope.project, scope.name);
255
+ const doAwait = parsed.flags.get("await") === true;
256
+ if (doAwait) {
257
+ const id = makeIdentity(scope.name, ulid());
258
+ let resolveReply!: (value: { response: unknown; error?: string | null }) => void;
259
+ const reply = new Promise<{ response: unknown; error?: string | null }>((resolve) => { resolveReply = resolve; });
260
+ const server = await bindEndpoint(
261
+ id.endpoint,
262
+ makeConnHandler((env, socket) => {
263
+ if (isResponseEnvelope(env)) {
264
+ writeAck(socket, env.msg_id);
265
+ resolveReply({ response: env.response, error: env.error ?? null });
266
+ } else if ((env as { type?: string }).type === "ping") {
267
+ writeAck(socket, (env as { msg_id?: string }).msg_id ?? "");
268
+ } else {
269
+ writeNack(socket, (env as { msg_id?: string }).msg_id ?? "", "cli awaits responses only");
270
+ }
271
+ }),
272
+ );
273
+ registerCliEntry(id, scope.project, `coms-cli (one-shot ask from ${scope.name})`);
274
+ const cleanup = () => {
275
+ try { server.close(); } catch { /* ignore */ }
276
+ try { fs.unlinkSync(id.endpoint); } catch { /* ignore */ }
277
+ removeRegistryEntry(scope.project, id.name);
278
+ };
279
+ try {
280
+ const env = makePromptEnvelope(id, prompt);
281
+ await sendEnvelope(peer.endpoint, env);
282
+ console.error(`sent ${env.msg_id} → ${peer.name} (awaiting reply, timeout ${timeoutMs}ms)`);
283
+ let timeoutTimer!: NodeJS.Timeout;
284
+ const timeout = new Promise<never>((_resolve, reject) => {
285
+ timeoutTimer = setTimeout(() => reject(new Error(`timeout after ${timeoutMs}ms`)), timeoutMs);
286
+ });
287
+ const result = await Promise.race([reply, timeout]).finally(() => clearTimeout(timeoutTimer));
288
+ if (result.error) fail(`peer error: ${result.error}`);
289
+ console.log(typeof result.response === "string" ? result.response : JSON.stringify(result.response, null, 2));
290
+ } finally {
291
+ cleanup();
292
+ }
293
+ return;
294
+ }
295
+
296
+ const sessionId = ulid();
297
+ const endpoint = makeEndpoint(sessionId);
298
+ const child = spawn(
299
+ process.execPath,
300
+ [
301
+ fileURLToPath(import.meta.url),
302
+ "_listen",
303
+ "--name", scope.name,
304
+ "--project", scope.project,
305
+ "--session", sessionId,
306
+ "--ttl", String(timeoutMs),
307
+ ],
308
+ { detached: true, stdio: ["ignore", "pipe", "ignore"] },
168
309
  );
169
- registerCliEntry(id, scope.project, `coms-cli (one-shot ask from ${name})`);
170
- const cleanup = () => {
171
- try { server.close(); } catch { /* ignore */ }
172
- try { fs.unlinkSync(id.endpoint); } catch { /* ignore */ }
173
- removeRegistryEntry(scope.project, id.name);
174
- };
310
+ await new Promise<void>((resolve, reject) => {
311
+ let settled = false;
312
+ const finish = (fn: () => void) => {
313
+ if (settled) return;
314
+ settled = true;
315
+ clearTimeout(timer);
316
+ fn();
317
+ };
318
+ const timer = setTimeout(() => finish(() => reject(new Error("waiter did not become ready"))), 5_000);
319
+ child.stdout!.on("data", (data) => {
320
+ if (data.toString().includes("READY")) finish(resolve);
321
+ });
322
+ child.once("exit", () => finish(() => reject(new Error("waiter exited early"))));
323
+ });
324
+ child.unref();
325
+ child.stdout!.destroy();
326
+
327
+ const id: SenderIdentity = { session_id: sessionId, name: scope.name, endpoint, cwd: process.cwd() };
328
+ const env = makePromptEnvelope(id, prompt);
329
+ const pendingFile = path.join(spool.pending, `${env.msg_id}.json`);
330
+ fs.writeFileSync(pendingFile, JSON.stringify({ msg_id: env.msg_id, target: peer.name, sent_at: nowIso() }));
175
331
  try {
176
- const env = makePromptEnvelope(id, prompt);
177
332
  await sendEnvelope(peer.endpoint, env);
178
- console.error(`sent ${env.msg_id} → ${peer.name} (awaiting reply, timeout ${timeoutMs}ms)`);
179
- const result = await Promise.race([
180
- reply,
181
- new Promise<never>((_r, rej) => setTimeout(() => rej(new Error(`timeout after ${timeoutMs}ms`)), timeoutMs)),
182
- ]);
183
- if (result.error) die(`peer error: ${result.error}`);
184
- console.log(typeof result.response === "string" ? result.response : JSON.stringify(result.response, null, 2));
185
- } finally {
186
- cleanup();
333
+ } catch (err) {
334
+ try { fs.unlinkSync(pendingFile); } catch { /* ignore */ }
335
+ try { if (child.pid) process.kill(-child.pid, "SIGTERM"); } catch { /* ignore */ }
336
+ fail(`send failed: ${err instanceof Error ? err.message : String(err)}`);
187
337
  }
188
- return;
338
+ console.log(env.msg_id);
339
+ } finally {
340
+ lock?.release();
189
341
  }
190
-
191
- // Detached mode: a waiter child owns the reply socket + registry entry;
192
- // this process sends, prints the msg_id, and exits.
193
- const sessionId = ulid();
194
- const endpoint = makeEndpoint(sessionId);
195
- const child = spawn(
196
- process.execPath,
197
- [
198
- fileURLToPath(import.meta.url),
199
- "_listen",
200
- "--name", name,
201
- "--project", scope.project,
202
- "--session", sessionId,
203
- "--ttl", String(timeoutMs),
204
- ],
205
- { detached: true, stdio: ["ignore", "pipe", "ignore"] },
206
- );
207
- await new Promise<void>((resolve, reject) => {
208
- const t = setTimeout(() => reject(new Error("waiter did not become ready")), 5000);
209
- child.stdout!.on("data", (d) => {
210
- if (d.toString().includes("READY")) {
211
- clearTimeout(t);
212
- resolve();
213
- }
214
- });
215
- child.on("exit", () => reject(new Error("waiter exited early")));
216
- });
217
- child.unref();
218
- child.stdout!.destroy();
219
-
220
- const id: SenderIdentity = { session_id: sessionId, name, endpoint, cwd: process.cwd() };
221
- const env = makePromptEnvelope(id, prompt);
222
- fs.writeFileSync(
223
- path.join(spool.pending, `${env.msg_id}.json`),
224
- JSON.stringify({ msg_id: env.msg_id, target: peer.name, sent_at: nowIso() }),
225
- );
226
- try {
227
- await sendEnvelope(peer.endpoint, env);
228
- } catch (err) {
229
- try { fs.unlinkSync(path.join(spool.pending, `${env.msg_id}.json`)); } catch { /* ignore */ }
230
- try { if (child.pid) process.kill(-child.pid, "SIGTERM"); } catch { /* ignore */ }
231
- die(`send failed: ${err instanceof Error ? err.message : String(err)}`);
232
- }
233
- console.log(env.msg_id);
234
342
  }
235
343
 
236
344
  // ━━ _listen (internal detached waiter) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
237
345
 
238
346
  async function cmdListen(argv: string[]): Promise<void> {
239
- const name = flagValue(argv, "--name") ?? DEFAULT_NAME;
240
- const project = flagValue(argv, "--project") ?? "default";
241
- const sessionId = flagValue(argv, "--session") ?? ulid();
242
- const ttl = Number(flagValue(argv, "--ttl") ?? DEFAULT_AWAIT_MS);
243
- const id = makeIdentity(name, sessionId);
244
- const spool = ensureSpool(name);
245
- ensureComsDirs(project);
347
+ const parsed = parseArgs(argv, ["project", "name", "session", "ttl"]);
348
+ if (parsed.positionals.length > 0) fail("_listen does not accept positional arguments");
349
+ const scope = scopeFrom(parsed);
350
+ const sessionId = validateComsId(flagValue(parsed, "session") ?? ulid(), "listen session");
351
+ const ttl = timeoutFrom(parsed, "ttl");
352
+ ensureComsDirs(scope.project);
353
+ const spool = ensureSpool(scope.project, scope.name);
354
+ const id = makeIdentity(scope.name, sessionId);
246
355
 
247
356
  const server = await bindEndpoint(
248
357
  id.endpoint,
249
358
  makeConnHandler((env, socket) => {
250
- if (isResponseEnvelope(env)) {
359
+ if (isResponseEnvelope(env) && typeof env.msg_id === "string" && COMS_ID_RE.test(env.msg_id)) {
251
360
  writeAck(socket, env.msg_id);
252
361
  fs.writeFileSync(
253
362
  path.join(spool.responses, `${env.msg_id}.json`),
@@ -255,9 +364,7 @@ async function cmdListen(argv: string[]): Promise<void> {
255
364
  );
256
365
  try { fs.unlinkSync(path.join(spool.pending, `${env.msg_id}.json`)); } catch { /* ignore */ }
257
366
  maybeExit();
258
- } else if (isPromptEnvelope(env)) {
259
- // Bidirectionality bonus: inbound prompts spool for a human /
260
- // hook to answer via `coms-cli reply <msg_id> …`.
367
+ } else if (isPromptEnvelope(env) && typeof env.msg_id === "string" && COMS_ID_RE.test(env.msg_id)) {
261
368
  writeAck(socket, env.msg_id);
262
369
  fs.writeFileSync(
263
370
  path.join(spool.inbound, `${env.msg_id}.json`),
@@ -274,32 +381,30 @@ async function cmdListen(argv: string[]): Promise<void> {
274
381
  } else if ((env as { type?: string }).type === "ping") {
275
382
  writeAck(socket, (env as { msg_id?: string }).msg_id ?? "");
276
383
  } else {
277
- writeNack(socket, (env as { msg_id?: string }).msg_id ?? "", "unsupported envelope");
384
+ writeNack(socket, (env as { msg_id?: string }).msg_id ?? "", "unsupported envelope or msg_id");
278
385
  }
279
386
  }),
280
387
  );
281
- registerCliEntry(id, project, "coms-cli reply waiter");
388
+ registerCliEntry(id, scope.project, "coms-cli reply waiter");
282
389
  console.log("READY");
283
390
 
284
391
  const cleanup = () => {
285
392
  try { server.close(); } catch { /* ignore */ }
286
393
  try { fs.unlinkSync(id.endpoint); } catch { /* ignore */ }
287
- removeRegistryEntry(project, id.name);
394
+ removeRegistryEntry(scope.project, id.name);
288
395
  process.exit(0);
289
396
  };
290
- // Exit when no pending markers remain (grace period lets the sender write
291
- // the first marker after READY).
292
397
  const startedAt = Date.now();
293
398
  function maybeExit(): void {
294
399
  try {
295
400
  const pendingLeft = fs.readdirSync(spool.pending).length;
296
- if (pendingLeft === 0 && Date.now() - startedAt > 3000) cleanup();
401
+ if (pendingLeft === 0 && Date.now() - startedAt > 3_000) cleanup();
297
402
  } catch {
298
- // ignore
403
+ // Best-effort cleanup only; the TTL remains authoritative.
299
404
  }
300
405
  }
301
- setInterval(maybeExit, 5000);
302
- setTimeout(cleanup, ttl); // TTL fallback
406
+ setInterval(maybeExit, 5_000);
407
+ setTimeout(cleanup, ttl);
303
408
  process.on("SIGTERM", cleanup);
304
409
  process.on("SIGINT", cleanup);
305
410
  }
@@ -307,66 +412,73 @@ async function cmdListen(argv: string[]): Promise<void> {
307
412
  // ━━ await ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
308
413
 
309
414
  async function cmdAwait(argv: string[]): Promise<void> {
310
- const msgId = argv.find((a) => !a.startsWith("--"));
311
- if (!msgId) die("usage: coms-cli await <msg_id> [--timeout <ms>]");
312
- const name = flagValue(argv, "--name") ?? DEFAULT_NAME;
313
- const timeoutMs = Number(flagValue(argv, "--timeout") ?? DEFAULT_AWAIT_MS);
314
- const spool = ensureSpool(name);
415
+ const parsed = parseArgs(argv, ["project", "name", "timeout"]);
416
+ if (parsed.positionals.length !== 1) fail("usage: coms-cli await <msg_id> --project <project> --name <name> [--timeout <ms>]");
417
+ const msgId = validateComsId(parsed.positionals[0], "msg_id");
418
+ const scope = scopeFrom(parsed);
419
+ const timeoutMs = timeoutFrom(parsed);
420
+ const spool = ensureSpool(scope.project, scope.name);
315
421
  const file = path.join(spool.responses, `${msgId}.json`);
316
422
  const deadline = Date.now() + timeoutMs;
317
423
  while (Date.now() < deadline) {
318
424
  if (fs.existsSync(file)) {
319
- const rec = JSON.parse(fs.readFileSync(file, "utf-8"));
320
- if (rec.error) die(`peer error: ${rec.error}`);
321
- console.log(typeof rec.response === "string" ? rec.response : JSON.stringify(rec.response, null, 2));
425
+ const record = JSON.parse(fs.readFileSync(file, "utf-8"));
426
+ if (record.error) fail(`peer error: ${record.error}`);
427
+ console.log(typeof record.response === "string" ? record.response : JSON.stringify(record.response, null, 2));
322
428
  return;
323
429
  }
324
- await new Promise((r) => setTimeout(r, 500));
430
+ await new Promise((resolve) => setTimeout(resolve, 500));
325
431
  }
326
- die(`timeout: no reply for ${msgId} after ${timeoutMs}ms`);
432
+ fail(`timeout: no reply for ${msgId} after ${timeoutMs}ms`);
327
433
  }
328
434
 
329
435
  // ━━ reply ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
330
436
 
331
437
  async function cmdReply(argv: string[]): Promise<void> {
332
- const positional = argv.filter((a, i) => !a.startsWith("--") && (i === 0 || !argv[i - 1].startsWith("--")));
333
- const [msgId, ...textParts] = positional;
438
+ const parsed = parseArgs(argv, ["project", "name"]);
439
+ const [rawMsgId, ...textParts] = parsed.positionals;
440
+ const msgId = rawMsgId ? validateComsId(rawMsgId, "msg_id") : undefined;
441
+ const scope = scopeFrom(parsed);
334
442
  let text = textParts.join(" ");
335
- if (!text && !process.stdin.isTTY) {
336
- text = fs.readFileSync(0, "utf-8").trim();
337
- }
338
- if (!msgId || !text) die("usage: coms-cli reply <msg_id> <text…> (or pipe the text on stdin)");
339
- const name = flagValue(argv, "--name") ?? DEFAULT_NAME;
340
- const spool = ensureSpool(name);
341
- const recFile = path.join(spool.inbound, `${msgId}.json`);
342
- if (!fs.existsSync(recFile)) die(`No inbound prompt ${msgId} in ${spool.inbound}`);
343
- const rec = JSON.parse(fs.readFileSync(recFile, "utf-8"));
344
- const id = makeIdentity(name, ulid());
345
- await sendEnvelope(rec.sender_endpoint, makeResponseEnvelope(id, msgId, text));
346
- fs.unlinkSync(recFile);
347
- console.log(`replied to ${rec.sender_name ?? rec.sender_session} (${msgId})`);
443
+ if (!text && !process.stdin.isTTY) text = fs.readFileSync(0, "utf-8").trim();
444
+ if (!msgId || !text) fail("usage: coms-cli reply <msg_id> <text…> --project <project> --name <name> (or pipe the text on stdin)");
445
+ const spool = ensureSpool(scope.project, scope.name);
446
+ const recordFile = path.join(spool.inbound, `${msgId}.json`);
447
+ if (!fs.existsSync(recordFile)) fail(`No inbound prompt ${msgId} in ${spool.inbound}`);
448
+ const record = JSON.parse(fs.readFileSync(recordFile, "utf-8"));
449
+ const id = makeIdentity(scope.name, ulid());
450
+ await sendEnvelope(record.sender_endpoint, makeResponseEnvelope(id, msgId, text));
451
+ fs.unlinkSync(recordFile);
452
+ console.log(`replied to ${record.sender_name ?? record.sender_session} (${msgId})`);
348
453
  }
349
454
 
350
- // ━━ main ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
351
-
352
455
  async function main(): Promise<void> {
353
- const [cmd, ...rest] = process.argv.slice(2);
354
- switch (cmd) {
456
+ const [command, ...rest] = process.argv.slice(2);
457
+ switch (command) {
355
458
  case "list":
356
- return cmdList(rest);
459
+ cmdList(rest);
460
+ return;
357
461
  case "send":
358
- return cmdSend(rest);
462
+ await cmdSend(rest);
463
+ return;
359
464
  case "await":
360
- return cmdAwait(rest);
465
+ await cmdAwait(rest);
466
+ return;
361
467
  case "reply":
362
- return cmdReply(rest);
468
+ await cmdReply(rest);
469
+ return;
363
470
  case "_listen":
364
- return cmdListen(rest);
471
+ await cmdListen(rest);
472
+ return;
365
473
  default:
366
- console.error("usage: coms-cli <list|send|await|reply> …");
367
- process.exit(2);
474
+ fail("usage: coms-cli <list|send|await|reply> …");
368
475
  }
369
476
  }
370
477
 
371
478
  const isEntry = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
372
- if (isEntry) void main();
479
+ if (isEntry) {
480
+ void main().catch((err) => {
481
+ console.error(err instanceof Error ? err.message : String(err));
482
+ process.exitCode = 1;
483
+ });
484
+ }