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