agentcue 0.0.0-stage → 0.0.2

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/dist/cli.js ADDED
@@ -0,0 +1,770 @@
1
+ #!/usr/bin/env node
2
+ // src/cli.ts
3
+ import { resolve as resolve2 } from "node:path";
4
+
5
+ // src/server/server.ts
6
+ import { createServer } from "node:http";
7
+ import { existsSync as existsSync2, readFileSync as readFileSync2, statSync } from "node:fs";
8
+ import { dirname as dirname2, join as join3, resolve } from "node:path";
9
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
10
+
11
+ // src/server/dispatcher.ts
12
+ import { spawn } from "node:child_process";
13
+ import { randomUUID } from "node:crypto";
14
+ import { accessSync, constants } from "node:fs";
15
+ import { delimiter, join } from "node:path";
16
+
17
+ // src/shared/prompt.ts
18
+ function formatStylesInline(styles) {
19
+ const entries = Object.entries(styles).filter(([, val]) => val && val !== "none" && val !== "normal" && val !== "0px");
20
+ if (entries.length === 0)
21
+ return "";
22
+ return entries.map(([k, v]) => `${k}: ${v}`).join("; ");
23
+ }
24
+ function formatPinSection(pin) {
25
+ const { context, note, index } = pin;
26
+ const lines = [];
27
+ lines.push(`### Pin #${index}: ${note.trim()}`);
28
+ if (context.sourceHint) {
29
+ lines.push(`- **Source hint**: \`${context.sourceHint}\``);
30
+ }
31
+ if (context.componentStack) {
32
+ lines.push(`- **Component tree**: \`${context.componentStack}\``);
33
+ }
34
+ lines.push(`- **Selector**: \`${context.selector}\``);
35
+ lines.push(`- **DOM path**: \`${context.breadcrumb}\``);
36
+ const { width, height, x, y } = context.boundingBox;
37
+ lines.push(`- **Box**: ${Math.round(width)}×${Math.round(height)}px at (${Math.round(x)}, ${Math.round(y)})`);
38
+ if (context.textExcerpt) {
39
+ lines.push(`- **Visible text**: ${JSON.stringify(context.textExcerpt)}`);
40
+ }
41
+ const styleSummary = formatStylesInline(context.computedStyles);
42
+ if (styleSummary) {
43
+ lines.push(`- **Computed styles**: \`${styleSummary}\``);
44
+ }
45
+ lines.push("- **DOM snippet**:");
46
+ lines.push("```html");
47
+ lines.push(context.outerHTML);
48
+ lines.push("```");
49
+ return lines.join(`
50
+ `);
51
+ }
52
+ function formatCuePrompt(cue) {
53
+ const urlPath = (() => {
54
+ try {
55
+ const parsed = new URL(cue.pageUrl);
56
+ return `${parsed.pathname}${parsed.search}${parsed.hash}` || "/";
57
+ } catch {
58
+ return cue.pageUrl || "/";
59
+ }
60
+ })();
61
+ const header = [
62
+ "Apply the following visual UI changes directly to the source files in this workspace.",
63
+ "Locate the exact source files using the selectors, visible text, DOM structure, and source hints below, then make minimal, clean edits.",
64
+ "",
65
+ `- **Page**: \`${urlPath}\`${cue.pageTitle ? ` (${cue.pageTitle})` : ""}`,
66
+ `- **Total Pins**: ${cue.pins.length}`
67
+ ].join(`
68
+ `);
69
+ const pinBlocks = cue.pins.map((pin, idx) => formatPinSection({ ...pin, index: idx + 1 }));
70
+ return [header, ...pinBlocks].join(`
71
+
72
+ `) + `
73
+ `;
74
+ }
75
+
76
+ // src/shared/types.ts
77
+ var SUPPORTED_AGENTS = [
78
+ "agy",
79
+ "claude",
80
+ "cursor-agent",
81
+ "codex",
82
+ "pi"
83
+ ];
84
+
85
+ // src/server/dispatcher.ts
86
+ function buildAgentCommand(agent, prompt, continueSession) {
87
+ switch (agent) {
88
+ case "agy":
89
+ return {
90
+ bin: "agy",
91
+ args: [
92
+ "--dangerously-skip-permissions",
93
+ ...continueSession ? ["--continue"] : [],
94
+ "-p",
95
+ prompt
96
+ ]
97
+ };
98
+ case "claude":
99
+ return {
100
+ bin: "claude",
101
+ args: [
102
+ "--dangerously-skip-permissions",
103
+ ...continueSession ? ["--continue"] : [],
104
+ "-p",
105
+ prompt
106
+ ]
107
+ };
108
+ case "cursor-agent":
109
+ return {
110
+ bin: "cursor-agent",
111
+ args: [
112
+ "--yolo",
113
+ ...continueSession ? ["--continue"] : [],
114
+ "-p",
115
+ prompt
116
+ ]
117
+ };
118
+ case "codex":
119
+ if (continueSession) {
120
+ return {
121
+ bin: "codex",
122
+ args: [
123
+ "exec",
124
+ "resume",
125
+ "--dangerously-bypass-approvals-and-sandbox",
126
+ "--skip-git-repo-check",
127
+ "--last",
128
+ prompt
129
+ ]
130
+ };
131
+ }
132
+ return {
133
+ bin: "codex",
134
+ args: [
135
+ "exec",
136
+ "--dangerously-bypass-approvals-and-sandbox",
137
+ "--skip-git-repo-check",
138
+ prompt
139
+ ]
140
+ };
141
+ case "pi":
142
+ return {
143
+ bin: "pi",
144
+ args: [
145
+ "--approve",
146
+ ...continueSession ? ["--continue"] : [],
147
+ "-p",
148
+ "--",
149
+ prompt
150
+ ]
151
+ };
152
+ }
153
+ }
154
+ function isBinaryInPath(bin, pathEnv = process.env.PATH || "") {
155
+ const dirs = pathEnv.split(delimiter).filter(Boolean);
156
+ for (const dir of dirs) {
157
+ const fullPath = join(dir, bin);
158
+ try {
159
+ accessSync(fullPath, constants.X_OK);
160
+ return true;
161
+ } catch {}
162
+ }
163
+ return false;
164
+ }
165
+ function detectAvailableAgents(pathEnv = process.env.PATH || "") {
166
+ return SUPPORTED_AGENTS.filter((agent) => isBinaryInPath(agent, pathEnv));
167
+ }
168
+ function createSpawnExecutor(options) {
169
+ const quiet = options?.quiet ?? false;
170
+ return (invocation) => new Promise((resolve) => {
171
+ const { bin, args } = invocation.command;
172
+ if (!quiet) {
173
+ console.log(`
174
+ \x1B[36m▶ [agentcue]\x1B[0m Running \x1B[1m${invocation.agent}\x1B[0m${invocation.continueSession ? " (continue)" : ""} · cue ${invocation.cueId.slice(0, 8)}`);
175
+ }
176
+ const child = spawn(bin, args, {
177
+ cwd: invocation.cwd,
178
+ shell: false,
179
+ stdio: ["ignore", "pipe", "pipe"],
180
+ env: process.env
181
+ });
182
+ let stderrTail = "";
183
+ child.stdout?.on("data", (chunk) => {
184
+ if (!quiet)
185
+ process.stdout.write(chunk);
186
+ });
187
+ child.stderr?.on("data", (chunk) => {
188
+ const text = chunk.toString();
189
+ stderrTail = (stderrTail + text).slice(-600);
190
+ if (!quiet)
191
+ process.stderr.write(chunk);
192
+ });
193
+ child.on("error", (err) => {
194
+ resolve({
195
+ ok: false,
196
+ exitCode: null,
197
+ error: `Failed to start ${bin}: ${err.message}`
198
+ });
199
+ });
200
+ child.on("close", (code) => {
201
+ if (code === 0) {
202
+ if (!quiet) {
203
+ console.log(`\x1B[32m✓ [agentcue]\x1B[0m ${invocation.agent} finished cue ${invocation.cueId.slice(0, 8)}
204
+ `);
205
+ }
206
+ resolve({ ok: true, exitCode: 0 });
207
+ } else {
208
+ const reason = stderrTail.trim().split(`
209
+ `).slice(-3).join(" ") || `${bin} exited with code ${code}`;
210
+ if (!quiet) {
211
+ console.error(`\x1B[31m✗ [agentcue]\x1B[0m ${invocation.agent} failed: ${reason}
212
+ `);
213
+ }
214
+ resolve({
215
+ ok: false,
216
+ exitCode: code,
217
+ error: reason
218
+ });
219
+ }
220
+ });
221
+ });
222
+ }
223
+ function createDispatcher(options) {
224
+ const agents = options.agents ?? detectAvailableAgents();
225
+ const preferredDefault = options.defaultAgent && agents.includes(options.defaultAgent) ? options.defaultAgent : agents[0] ?? options.defaultAgent ?? null;
226
+ const executor = options.executor ?? createSpawnExecutor();
227
+ const listeners = new Set;
228
+ const queue = [];
229
+ let state = {
230
+ cwd: options.cwd,
231
+ agents,
232
+ defaultAgent: preferredDefault,
233
+ status: "idle",
234
+ activeCue: null,
235
+ queuedCount: 0,
236
+ lastResult: null
237
+ };
238
+ let processing = false;
239
+ function emit(event) {
240
+ for (const listener of listeners) {
241
+ listener(event);
242
+ }
243
+ }
244
+ function emitState() {
245
+ emit({ type: "state", state: getState() });
246
+ }
247
+ function getState() {
248
+ return {
249
+ ...state,
250
+ agents: [...state.agents],
251
+ activeCue: state.activeCue ? { ...state.activeCue } : null,
252
+ lastResult: state.lastResult ? { ...state.lastResult } : null
253
+ };
254
+ }
255
+ async function drainQueue() {
256
+ if (processing)
257
+ return;
258
+ processing = true;
259
+ while (queue.length > 0) {
260
+ const next = queue.shift();
261
+ const startedAt = Date.now();
262
+ state = {
263
+ ...state,
264
+ status: "running",
265
+ activeCue: {
266
+ cueId: next.cueId,
267
+ agent: next.payload.agent,
268
+ pinCount: next.payload.pins.length,
269
+ startedAt
270
+ },
271
+ queuedCount: queue.length
272
+ };
273
+ emitState();
274
+ const command = buildAgentCommand(next.payload.agent, next.prompt, next.payload.continueSession);
275
+ let result;
276
+ try {
277
+ result = await executor({
278
+ cueId: next.cueId,
279
+ agent: next.payload.agent,
280
+ continueSession: next.payload.continueSession,
281
+ prompt: next.prompt,
282
+ cwd: options.cwd,
283
+ command
284
+ });
285
+ } catch (err) {
286
+ result = {
287
+ ok: false,
288
+ exitCode: null,
289
+ error: err instanceof Error ? err.message : String(err)
290
+ };
291
+ }
292
+ const finishedAt = Date.now();
293
+ const durationMs = finishedAt - startedAt;
294
+ state = {
295
+ ...state,
296
+ status: queue.length > 0 ? "running" : result.ok ? "done" : "error",
297
+ activeCue: null,
298
+ queuedCount: queue.length,
299
+ lastResult: {
300
+ cueId: next.cueId,
301
+ agent: next.payload.agent,
302
+ ok: result.ok,
303
+ durationMs,
304
+ error: result.error,
305
+ finishedAt
306
+ }
307
+ };
308
+ if (result.ok) {
309
+ emit({
310
+ type: "cue:done",
311
+ cueId: next.cueId,
312
+ agent: next.payload.agent,
313
+ durationMs
314
+ });
315
+ } else {
316
+ emit({
317
+ type: "cue:error",
318
+ cueId: next.cueId,
319
+ agent: next.payload.agent,
320
+ error: result.error || "Agent command failed"
321
+ });
322
+ }
323
+ emitState();
324
+ }
325
+ processing = false;
326
+ }
327
+ function enqueue(payload) {
328
+ const cueId = randomUUID();
329
+ const prompt = formatCuePrompt(payload);
330
+ queue.push({ cueId, payload, prompt });
331
+ const queuePosition = queue.length + (state.activeCue ? 1 : 0);
332
+ state = {
333
+ ...state,
334
+ queuedCount: queue.length
335
+ };
336
+ emitState();
337
+ drainQueue();
338
+ return { cueId, queuePosition };
339
+ }
340
+ function subscribe(listener) {
341
+ listeners.add(listener);
342
+ return () => {
343
+ listeners.delete(listener);
344
+ };
345
+ }
346
+ return {
347
+ enqueue,
348
+ getState,
349
+ subscribe
350
+ };
351
+ }
352
+
353
+ // src/server/handler.ts
354
+ import { existsSync, readFileSync } from "node:fs";
355
+ import { dirname, join as join2 } from "node:path";
356
+ import { fileURLToPath } from "node:url";
357
+ var CORS_HEADERS = {
358
+ "Access-Control-Allow-Origin": "*",
359
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
360
+ "Access-Control-Allow-Headers": "Content-Type",
361
+ "Access-Control-Allow-Private-Network": "true"
362
+ };
363
+ function sendJson(res, status, body) {
364
+ res.writeHead(status, {
365
+ ...CORS_HEADERS,
366
+ "Content-Type": "application/json; charset=utf-8",
367
+ "Cache-Control": "no-store"
368
+ });
369
+ res.end(JSON.stringify(body));
370
+ }
371
+ function readJsonBody(req, maxBytes = 512000) {
372
+ return new Promise((resolveBody, reject) => {
373
+ const chunks = [];
374
+ let size = 0;
375
+ req.on("data", (chunk) => {
376
+ size += chunk.length;
377
+ if (size > maxBytes) {
378
+ reject(new Error("Payload too large"));
379
+ req.destroy();
380
+ return;
381
+ }
382
+ chunks.push(chunk);
383
+ });
384
+ req.on("end", () => {
385
+ try {
386
+ const raw = Buffer.concat(chunks).toString("utf-8");
387
+ resolveBody(raw ? JSON.parse(raw) : {});
388
+ } catch {
389
+ reject(new Error("Invalid JSON payload"));
390
+ }
391
+ });
392
+ req.on("error", reject);
393
+ });
394
+ }
395
+ function validateCuePayload(raw, allowedAgents) {
396
+ if (!raw || typeof raw !== "object") {
397
+ throw new Error("Cue body must be a JSON object");
398
+ }
399
+ const obj = raw;
400
+ const agent = obj.agent;
401
+ if (!SUPPORTED_AGENTS.includes(agent)) {
402
+ throw new Error(`Unsupported agent "${String(obj.agent)}"`);
403
+ }
404
+ if (allowedAgents.length > 0 && !allowedAgents.includes(agent)) {
405
+ throw new Error(`Agent "${agent}" is not installed on PATH`);
406
+ }
407
+ if (!Array.isArray(obj.pins) || obj.pins.length === 0) {
408
+ throw new Error("Cue must contain at least one Pin");
409
+ }
410
+ for (const pin of obj.pins) {
411
+ if (!pin || typeof pin !== "object")
412
+ throw new Error("Invalid Pin entry");
413
+ const p = pin;
414
+ if (typeof p.note !== "string" || !p.note.trim()) {
415
+ throw new Error("Every Pin requires a non-empty note");
416
+ }
417
+ if (!p.context || typeof p.context !== "object") {
418
+ throw new Error("Every Pin requires DOM context");
419
+ }
420
+ }
421
+ return {
422
+ agent,
423
+ continueSession: Boolean(obj.continueSession),
424
+ pageUrl: typeof obj.pageUrl === "string" ? obj.pageUrl : "/",
425
+ pageTitle: typeof obj.pageTitle === "string" ? obj.pageTitle : "",
426
+ pins: obj.pins
427
+ };
428
+ }
429
+ function resolveClientBundlePath() {
430
+ const here = dirname(fileURLToPath(import.meta.url));
431
+ const candidates = [
432
+ join2(here, "client.js"),
433
+ join2(here, "..", "dist", "client.js"),
434
+ join2(here, "..", "..", "dist", "client.js")
435
+ ];
436
+ return candidates.find((p) => existsSync(p)) || candidates[0];
437
+ }
438
+ function createBridgeHandler(options) {
439
+ const prefix = (options.basePath || "").replace(/\/+$/, "");
440
+ const bundlePath = options.clientBundlePath ?? resolveClientBundlePath();
441
+ const activeCleanups = new Set;
442
+ async function handleCuePost(req, res) {
443
+ try {
444
+ const rawBody = await readJsonBody(req);
445
+ const state = options.dispatcher.getState();
446
+ const payload = validateCuePayload(rawBody, state.agents);
447
+ const queued = options.dispatcher.enqueue(payload);
448
+ sendJson(res, 202, {
449
+ ok: true,
450
+ cueId: queued.cueId,
451
+ queuePosition: queued.queuePosition
452
+ });
453
+ } catch (err) {
454
+ sendJson(res, 400, {
455
+ ok: false,
456
+ error: err instanceof Error ? err.message : "Bad request"
457
+ });
458
+ }
459
+ }
460
+ function middleware(req, res, next) {
461
+ const method = req.method || "GET";
462
+ const urlObj = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
463
+ const pathname = urlObj.pathname;
464
+ let subPath = pathname;
465
+ if (prefix) {
466
+ if (pathname !== prefix && !pathname.startsWith(`${prefix}/`)) {
467
+ next?.();
468
+ return;
469
+ }
470
+ subPath = pathname.slice(prefix.length) || "/";
471
+ }
472
+ if (method === "OPTIONS") {
473
+ res.writeHead(204, CORS_HEADERS);
474
+ res.end();
475
+ return;
476
+ }
477
+ if (method === "GET" && subPath === "/client.js") {
478
+ const origin = typeof options.clientOrigin === "function" ? options.clientOrigin() : options.clientOrigin;
479
+ const scriptBody = options.clientScript ?? (existsSync(bundlePath) ? readFileSync(bundlePath, "utf-8") : "console.error('[agentcue] dist/client.js not built yet.');");
480
+ const injected = `window.__AGENTCUE_ORIGIN__=${JSON.stringify(origin)};
481
+ ${scriptBody}`;
482
+ res.writeHead(200, {
483
+ ...CORS_HEADERS,
484
+ "Content-Type": "application/javascript; charset=utf-8",
485
+ "Cache-Control": "no-store"
486
+ });
487
+ res.end(injected);
488
+ return;
489
+ }
490
+ if (method === "GET" && subPath === "/api/state") {
491
+ sendJson(res, 200, options.dispatcher.getState());
492
+ return;
493
+ }
494
+ if (method === "GET" && subPath === "/api/events") {
495
+ res.writeHead(200, {
496
+ ...CORS_HEADERS,
497
+ "Content-Type": "text/event-stream; charset=utf-8",
498
+ "Cache-Control": "no-cache, no-transform",
499
+ "X-Accel-Buffering": "no",
500
+ ...req.httpVersionMajor >= 2 ? {} : { Connection: "keep-alive" }
501
+ });
502
+ res.flushHeaders?.();
503
+ const writeEvent = (evt) => {
504
+ if (!res.writableEnded) {
505
+ res.write(`data: ${JSON.stringify(evt)}
506
+
507
+ `);
508
+ }
509
+ };
510
+ writeEvent({ type: "state", state: options.dispatcher.getState() });
511
+ const unsubscribe = options.dispatcher.subscribe(writeEvent);
512
+ const heartbeat = setInterval(() => {
513
+ if (!res.writableEnded) {
514
+ res.write(`: ping
515
+
516
+ `);
517
+ }
518
+ }, 15000);
519
+ heartbeat.unref?.();
520
+ let closed = false;
521
+ const cleanup = () => {
522
+ if (closed)
523
+ return;
524
+ closed = true;
525
+ clearInterval(heartbeat);
526
+ unsubscribe();
527
+ activeCleanups.delete(forceClose);
528
+ };
529
+ const forceClose = () => {
530
+ cleanup();
531
+ if (!res.writableEnded) {
532
+ res.end();
533
+ }
534
+ };
535
+ activeCleanups.add(forceClose);
536
+ req.on("close", cleanup);
537
+ return;
538
+ }
539
+ if (method === "POST" && subPath === "/api/cue") {
540
+ handleCuePost(req, res);
541
+ return;
542
+ }
543
+ if (prefix) {
544
+ sendJson(res, 404, { error: "Not found" });
545
+ return;
546
+ }
547
+ if (next) {
548
+ next();
549
+ } else {
550
+ sendJson(res, 404, { error: "Not found" });
551
+ }
552
+ }
553
+ function dispose() {
554
+ for (const closeStream of activeCleanups) {
555
+ closeStream();
556
+ }
557
+ activeCleanups.clear();
558
+ }
559
+ return { middleware, dispose };
560
+ }
561
+
562
+ // src/server/server.ts
563
+ function resolveDefaultDemoPath(cwd) {
564
+ const here = dirname2(fileURLToPath2(import.meta.url));
565
+ const candidatesDemo = [
566
+ join3(cwd, "examples", "html", "index.html"),
567
+ join3(here, "..", "..", "examples", "html", "index.html"),
568
+ join3(here, "..", "..", "..", "examples", "html", "index.html"),
569
+ join3(here, "demo.html"),
570
+ join3(here, "..", "dist", "demo.html"),
571
+ join3(here, "..", "..", "dist", "demo.html")
572
+ ];
573
+ return candidatesDemo.find((p) => existsSync2(p)) || candidatesDemo[0];
574
+ }
575
+ async function startServer(options = {}) {
576
+ const host = options.host ?? "127.0.0.1";
577
+ const requestedPort = options.port ?? 4318;
578
+ const cwd = resolve(options.cwd ?? process.cwd());
579
+ const dispatcher = createDispatcher({
580
+ cwd,
581
+ agents: options.agents,
582
+ defaultAgent: options.defaultAgent,
583
+ executor: options.executor
584
+ });
585
+ const demoPath = options.demoHtmlPath ?? resolveDefaultDemoPath(cwd);
586
+ let boundPort = requestedPort;
587
+ const getOrigin = () => `http://${host === "127.0.0.1" ? "localhost" : host}:${boundPort}`;
588
+ const bridge = createBridgeHandler({
589
+ dispatcher,
590
+ basePath: "",
591
+ clientOrigin: getOrigin,
592
+ clientScript: options.clientScript,
593
+ clientBundlePath: resolveClientBundlePath()
594
+ });
595
+ const server = createServer((req, res) => {
596
+ bridge.middleware(req, res, () => {
597
+ const method = req.method || "GET";
598
+ const urlObj = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
599
+ const pathname = urlObj.pathname;
600
+ if (method === "GET" && pathname === "/api/demo-mtime") {
601
+ const mtime = existsSync2(demoPath) ? statSync(demoPath).mtimeMs : 0;
602
+ sendJson(res, 200, { mtime });
603
+ return;
604
+ }
605
+ if (method === "GET" && (pathname === "/" || pathname === "/demo")) {
606
+ if (!existsSync2(demoPath)) {
607
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
608
+ res.end("Demo page not found.");
609
+ return;
610
+ }
611
+ let html = readFileSync2(demoPath, "utf-8");
612
+ const liveReloadAndClient = `
613
+ <script src="${getOrigin()}/client.js"></script>
614
+ <script>
615
+ (() => {
616
+ let last = 0;
617
+ setInterval(async () => {
618
+ try {
619
+ const r = await fetch("/api/demo-mtime", { cache: "no-store" });
620
+ const { mtime } = await r.json();
621
+ if (last && mtime > last) location.reload();
622
+ last = mtime;
623
+ } catch {}
624
+ }, 900);
625
+ })();
626
+ </script>`;
627
+ html = html.includes("</body>") ? html.replace("</body>", `${liveReloadAndClient}
628
+ </body>`) : `${html}
629
+ ${liveReloadAndClient}`;
630
+ res.writeHead(200, {
631
+ "Content-Type": "text/html; charset=utf-8",
632
+ "Cache-Control": "no-store"
633
+ });
634
+ res.end(html);
635
+ return;
636
+ }
637
+ sendJson(res, 404, { error: "Not found" });
638
+ });
639
+ });
640
+ await new Promise((resolveListen, rejectListen) => {
641
+ server.once("error", rejectListen);
642
+ server.listen(requestedPort, host, () => {
643
+ const addr = server.address();
644
+ if (addr && typeof addr === "object") {
645
+ boundPort = addr.port;
646
+ }
647
+ resolveListen();
648
+ });
649
+ });
650
+ return {
651
+ port: boundPort,
652
+ host,
653
+ origin: getOrigin(),
654
+ dispatcher,
655
+ close: () => {
656
+ bridge.dispose();
657
+ return new Promise((resolveClose, rejectClose) => {
658
+ server.close((err) => err ? rejectClose(err) : resolveClose());
659
+ });
660
+ }
661
+ };
662
+ }
663
+
664
+ // src/cli.ts
665
+ function parseCliArgs(argv) {
666
+ let port = Number(process.env.AGENTCUE_PORT) || 4318;
667
+ let host = "127.0.0.1";
668
+ let cwd = process.cwd();
669
+ let defaultAgent;
670
+ let help = false;
671
+ for (let i = 0;i < argv.length; i++) {
672
+ const arg = argv[i];
673
+ if (arg === "-h" || arg === "--help") {
674
+ help = true;
675
+ } else if (arg === "-p" || arg === "--port") {
676
+ port = Number(argv[++i]);
677
+ } else if (arg.startsWith("--port=")) {
678
+ port = Number(arg.split("=")[1]);
679
+ } else if (arg === "--host") {
680
+ host = argv[++i];
681
+ } else if (arg === "-C" || arg === "--cwd") {
682
+ cwd = resolve2(argv[++i]);
683
+ } else if (arg === "-a" || arg === "--agent") {
684
+ const candidate = argv[++i];
685
+ if (SUPPORTED_AGENTS.includes(candidate))
686
+ defaultAgent = candidate;
687
+ } else if (!arg.startsWith("-")) {
688
+ const normalized = arg === "cursor" ? "cursor-agent" : arg;
689
+ if (SUPPORTED_AGENTS.includes(normalized)) {
690
+ defaultAgent = normalized;
691
+ }
692
+ }
693
+ }
694
+ return { port, host, cwd, defaultAgent, help };
695
+ }
696
+ function printHelp() {
697
+ console.log(`
698
+ agentcue — Pick DOM elements in the browser and push Cues directly to your Agent CLI.
699
+
700
+ Usage:
701
+ agentcue [agent] [options]
702
+
703
+ Agents:
704
+ agy | claude | cursor-agent | codex | pi
705
+
706
+ Options:
707
+ -p, --port <port> Local bridge port (default: 4318)
708
+ -a, --agent <agent> Default selected Agent Target
709
+ -C, --cwd <dir> Target workspace directory (default: current directory)
710
+ --host <host> Bind host (default: 127.0.0.1)
711
+ -h, --help Show this help message
712
+ `);
713
+ }
714
+ async function main() {
715
+ const args = parseCliArgs(process.argv.slice(2));
716
+ if (args.help) {
717
+ printHelp();
718
+ return;
719
+ }
720
+ let running;
721
+ let candidatePort = args.port;
722
+ for (let attempt = 0;attempt < 10; attempt++) {
723
+ try {
724
+ running = await startServer({
725
+ port: candidatePort,
726
+ host: args.host,
727
+ cwd: args.cwd,
728
+ defaultAgent: args.defaultAgent
729
+ });
730
+ break;
731
+ } catch (err) {
732
+ if (err && typeof err === "object" && "code" in err && err.code === "EADDRINUSE") {
733
+ candidatePort += 1;
734
+ continue;
735
+ }
736
+ throw err;
737
+ }
738
+ }
739
+ if (!running) {
740
+ throw new Error(`Could not find an open port starting from ${args.port}`);
741
+ }
742
+ const state = running.dispatcher.getState();
743
+ const agentList = SUPPORTED_AGENTS.map((a) => state.agents.includes(a) ? `\x1B[32m✓ ${a}\x1B[0m` : `\x1B[90m✗ ${a}\x1B[0m`).join(" ");
744
+ const scriptTag = `<script src="${running.origin}/client.js"></script>`;
745
+ const bookmarklet = `javascript:(()=>{const s=document.createElement('script');s.src='${running.origin}/client.js?t='+Date.now();document.head.appendChild(s);})()`;
746
+ console.log(`
747
+ \x1B[1m\x1B[36m✦ agentcue\x1B[0m bridge listening on \x1B[1m${running.origin}\x1B[0m
748
+ Workspace : ${state.cwd}
749
+ Agents : ${agentList}
750
+
751
+ \x1B[1m1) Try the built-in live playground:\x1B[0m
752
+ ${running.origin}/demo
753
+
754
+ \x1B[1m2) Add to any local dev app (HTML / Vite / Next / Vue / Svelte):\x1B[0m
755
+ ${scriptTag}
756
+
757
+ \x1B[1m3) Or run as a zero-config Bookmarklet URL:\x1B[0m
758
+ ${bookmarklet}
759
+
760
+ \x1B[90mShortcuts: Cmd/Ctrl+Shift+F activate · Enter save Pin · S (or Cmd/Ctrl+Enter) send · C copy · X clear · H hide · Esc collapse\x1B[0m
761
+ `);
762
+ const shutdown = () => {
763
+ console.log(`
764
+ Shutting down agentcue…`);
765
+ running.close().finally(() => process.exit(0));
766
+ };
767
+ process.on("SIGINT", shutdown);
768
+ process.on("SIGTERM", shutdown);
769
+ }
770
+ main();