@chankov/agent-fleet 0.0.2 → 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.
- package/.claude/commands/doctor-agent-fleet.md +1 -1
- package/.claude/commands/setup-agent-fleet.md +4 -4
- package/.opencode/commands/af-doctor-agent-fleet.md +2 -0
- package/.opencode/commands/af-setup-agent-fleet.md +1 -1
- package/.pi/agents/peers.yaml +4 -0
- package/.pi/agents/teams.yaml +2 -2
- package/.pi/harnesses/agent-hub/README.md +57 -4
- package/.pi/harnesses/agent-hub/index.ts +236 -80
- package/.pi/harnesses/agent-hub/research-retention.js +34 -0
- package/.pi/harnesses/ask-user-remote/README.md +2 -0
- package/.pi/harnesses/coms/README.md +11 -0
- package/.pi/prompts/doctor-agent-fleet.md +1 -1
- package/.pi/prompts/setup-agent-fleet.md +4 -4
- package/README.md +102 -540
- package/agents/architect.md +1 -1
- package/agents/planner.md +1 -1
- package/agents/security-auditor.md +1 -1
- package/bin/snapshot-version.js +17 -1
- package/codex/CONDUCTOR.md +148 -0
- package/docs/ARCHITECTURE.md +165 -0
- package/docs/agent-fleet-setup.md +1 -0
- package/docs/claude-code-coms-bridge.md +10 -0
- package/docs/codex-remote-conductor.md +170 -0
- package/docs/coms-hermes-bridge.md +121 -0
- package/docs/getting-started.md +14 -0
- package/docs/npm-install.md +2 -0
- package/docs/pi-setup.md +2 -0
- package/hermes/README.md +48 -0
- package/hermes/skills/hub-conductor/SKILL.md +84 -0
- package/hermes/skills/hub-liaison/SKILL.md +84 -0
- package/justfile +100 -13
- package/package.json +10 -3
- package/scripts/codex-conductor.ts +41 -0
- package/scripts/codex-remote-control.ts +167 -0
- package/scripts/coms-cli.ts +311 -199
- package/scripts/coms-hermes-bridge.ts +2 -2
- package/scripts/lib/codex-conductor.ts +88 -0
- package/scripts/lib/codex-remote-control.ts +480 -0
- package/scripts/lib/coms-envelope.ts +51 -6
- package/scripts/lib/herdr-layout.ts +18 -3
- package/scripts/lib/hermes-bridge-core.ts +4 -4
- package/scripts/lib/team-project.ts +85 -1
- package/scripts/team-up.ts +77 -18
- package/skills/guided-workspace-setup/SKILL.md +123 -97
- package/skills/guided-workspace-setup/companion-manifest.json +33 -0
- package/skills/peer-coms/SKILL.md +9 -0
- package/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
package/scripts/coms-cli.ts
CHANGED
|
@@ -1,23 +1,9 @@
|
|
|
1
1
|
// scripts/coms-cli.ts
|
|
2
2
|
//
|
|
3
|
-
// Envelope-protocol CLI
|
|
4
|
-
//
|
|
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
|
-
//
|
|
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 =
|
|
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
|
|
53
|
-
|
|
54
|
-
return
|
|
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
|
|
58
|
-
|
|
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
|
|
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
|
|
136
|
+
for (const dir of Object.values(dirs)) fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
74
137
|
return dirs;
|
|
75
138
|
}
|
|
76
139
|
|
|
77
|
-
|
|
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
|
-
(
|
|
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
|
|
117
|
-
|
|
118
|
-
const
|
|
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
|
|
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
|
|
132
|
-
const [
|
|
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 (!
|
|
135
|
-
|
|
136
|
-
const scope = scopeFrom(
|
|
137
|
-
const
|
|
138
|
-
const
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
const
|
|
145
|
-
|
|
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
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
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
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
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
|
-
|
|
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
|
|
240
|
-
|
|
241
|
-
const
|
|
242
|
-
const
|
|
243
|
-
const
|
|
244
|
-
|
|
245
|
-
|
|
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 >
|
|
401
|
+
if (pendingLeft === 0 && Date.now() - startedAt > 3_000) cleanup();
|
|
297
402
|
} catch {
|
|
298
|
-
//
|
|
403
|
+
// Best-effort cleanup only; the TTL remains authoritative.
|
|
299
404
|
}
|
|
300
405
|
}
|
|
301
|
-
setInterval(maybeExit,
|
|
302
|
-
setTimeout(cleanup, ttl);
|
|
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
|
|
311
|
-
if (
|
|
312
|
-
const
|
|
313
|
-
const
|
|
314
|
-
const
|
|
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
|
|
320
|
-
if (
|
|
321
|
-
console.log(typeof
|
|
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((
|
|
430
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
325
431
|
}
|
|
326
|
-
|
|
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
|
|
333
|
-
const [
|
|
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
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
const
|
|
341
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
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 [
|
|
354
|
-
switch (
|
|
456
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
457
|
+
switch (command) {
|
|
355
458
|
case "list":
|
|
356
|
-
|
|
459
|
+
cmdList(rest);
|
|
460
|
+
return;
|
|
357
461
|
case "send":
|
|
358
|
-
|
|
462
|
+
await cmdSend(rest);
|
|
463
|
+
return;
|
|
359
464
|
case "await":
|
|
360
|
-
|
|
465
|
+
await cmdAwait(rest);
|
|
466
|
+
return;
|
|
361
467
|
case "reply":
|
|
362
|
-
|
|
468
|
+
await cmdReply(rest);
|
|
469
|
+
return;
|
|
363
470
|
case "_listen":
|
|
364
|
-
|
|
471
|
+
await cmdListen(rest);
|
|
472
|
+
return;
|
|
365
473
|
default:
|
|
366
|
-
|
|
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)
|
|
479
|
+
if (isEntry) {
|
|
480
|
+
void main().catch((err) => {
|
|
481
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
482
|
+
process.exitCode = 1;
|
|
483
|
+
});
|
|
484
|
+
}
|