rushes 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,48 @@
1
+ const KEPT = 200;
2
+ const record = (v) => (typeof v === "object" && v !== null && !Array.isArray(v) ? v : null);
3
+ const pathsOf = (v) => Array.isArray(v) ? v.filter((l) => typeof record(l)?.path === "string").map((l) => ({ path: l.path })) : undefined;
4
+ /** Keeps the kind, rawInput and locations of a tool_call or tool_call_update, merged by toolCallId. The oldest go past 200. */
5
+ export function noteToolCall(seen, update) {
6
+ const u = record(update);
7
+ if (!u || (u.sessionUpdate !== "tool_call" && u.sessionUpdate !== "tool_call_update") || typeof u.toolCallId !== "string")
8
+ return;
9
+ const prev = seen.get(u.toolCallId) ?? {};
10
+ const locations = pathsOf(u.locations);
11
+ const next = {
12
+ ...prev,
13
+ ...(typeof u.kind === "string" && u.kind !== "" ? { kind: u.kind } : {}),
14
+ ...(u.rawInput !== undefined && u.rawInput !== null ? { rawInput: u.rawInput } : {}),
15
+ ...(locations && locations.length > 0 ? { locations } : {}),
16
+ };
17
+ seen.delete(u.toolCallId);
18
+ seen.set(u.toolCallId, next);
19
+ while (seen.size > KEPT)
20
+ seen.delete(seen.keys().next().value);
21
+ }
22
+ /**
23
+ * The ask with what it lacks filled from its own tool_call: a kind, a rawInput (or its command), locations (an empty list
24
+ * carries none). A field the ask carries is never changed. With no tool_call seen for its toolCallId, the ask as it came.
25
+ */
26
+ export function withSeen(p, seen) {
27
+ const s = seen.get(p.toolCall.toolCallId);
28
+ if (!s)
29
+ return p;
30
+ const tc = { ...p.toolCall };
31
+ // A file change is an edit; anything else that started (a command, however Codex parsed it) is a command.
32
+ const edit = s.kind === "edit";
33
+ if (tc.kind === undefined || tc.kind === null || tc.kind === "")
34
+ tc.kind = edit ? "edit" : "execute";
35
+ const raw = record(tc.rawInput);
36
+ const seenRaw = record(s.rawInput);
37
+ if (tc.rawInput === undefined || tc.rawInput === null) {
38
+ if (s.rawInput !== undefined)
39
+ tc.rawInput = s.rawInput;
40
+ }
41
+ else if (raw && raw.command === undefined && seenRaw?.command !== undefined) {
42
+ tc.rawInput = { ...raw, command: seenRaw.command };
43
+ }
44
+ // Only an edit's paths: a read's path would make a command look like a read in the project.
45
+ if (edit && (tc.locations === undefined || tc.locations.length === 0) && s.locations)
46
+ tc.locations = s.locations;
47
+ return { ...p, toolCall: tc };
48
+ }
@@ -0,0 +1,27 @@
1
+ // "Sign in in Terminal" (§5.1): Rushes never runs a login itself. It opens Terminal with the agent's own
2
+ // login command for the user to run there, and never sees what they type.
3
+ import { execFile } from "node:child_process";
4
+ import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { RushesError } from "../../core/errors.js";
8
+ /** How long the sign-in file is kept after Terminal is asked to open it. */
9
+ export const SIGN_IN_FILE_MS = 60_000;
10
+ /**
11
+ * macOS: writes a `.command` file holding only `#!/bin/sh` and the command, and opens it in Terminal
12
+ * (execFile, no shell). The file is in a private temporary folder, removed a minute later.
13
+ */
14
+ export const openInTerminal = async (command) => {
15
+ if (process.platform !== "darwin") {
16
+ throw new RushesError(`Rushes can open Terminal only on a Mac. Run \`${command}\` in a terminal, then try again.`, 501, "no_terminal");
17
+ }
18
+ const dir = await mkdtemp(join(tmpdir(), "rushes-sign-in-"));
19
+ const file = join(dir, "sign-in.command");
20
+ await writeFile(file, `#!/bin/sh\n${command}\n`, { mode: 0o700 });
21
+ await chmod(file, 0o700);
22
+ // Terminal has read the file long before this: the folder goes, quietly, whatever happens.
23
+ setTimeout(() => void rm(dir, { recursive: true, force: true }).catch(() => undefined), SIGN_IN_FILE_MS).unref();
24
+ await new Promise((resolve, reject) => {
25
+ execFile("open", ["-a", "Terminal", file], (error) => (error ? reject(error) : resolve()));
26
+ });
27
+ };
@@ -4,10 +4,10 @@ import { z } from "zod";
4
4
  import { RushesError, InvalidError, NotFoundError } from "../core/errors.js";
5
5
  import { addFile, addFormat, addVariant, addVersion, ensureProjectIdOnce, lockPicture, noteInPlay, resolveCut, resolveVideo, setShots, setVariantFilms, shelveFilm, shotAt } from "../core/project.js";
6
6
  import { addTake, editSection, setSections } from "../core/script.js";
7
- import { addNote, applyReply, applyUserEdit, checkNoteFormat, filterNotes } from "../core/notes.js";
7
+ import { addNote, addUserReply, applyReply, applyUserEdit, checkNoteFormat, filterNotes } from "../core/notes.js";
8
8
  import { FORMAT_ID_RE, MAX_FORMATS, isPictureSize, labelOfId, versionFormats } from "../core/formats.js";
9
9
  import { createBatch, latestBatch } from "../core/batches.js";
10
- import { markSent, NOTE_STATES, withState } from "../core/noteState.js";
10
+ import { markSent, noteState, NOTE_STATES, withState } from "../core/noteState.js";
11
11
  import { exportFileName, notesMarkdown } from "../core/exportNotes.js";
12
12
  import { tabStates } from "../core/tabs.js";
13
13
  import { addVisualVersion, checkVisualNote, registerVisual, visualNoteView, visualRatios } from "../core/visuals.js";
@@ -27,7 +27,7 @@ import { candidatePaths, listAssets, fpsFor, screenshotName } from "./assets.js"
27
27
  import { osRevealer, osOpener, OPEN_SAFE_EXT } from "./reveal.js";
28
28
  import { inUse, setInUse } from "../core/picks.js";
29
29
  import { filmTakes, putAway } from "../core/takes.js";
30
- import { LaneStageSchema, SectionStatusSchema, StageSchema, BoxSchema, PinSchema, FileKindSchema, MarkSchema, ProjectIdSchema, ShotSchema, LEVEL_MIN, LEVEL_MAX, LEVEL_STEP, lanesForVideo, picksForVideo, variantFilms } from "../core/schema.js";
30
+ import { AGENTS, AgentPermissionsSchema, AlwaysRuleSchema, LaneStageSchema, SectionStatusSchema, StageSchema, BoxSchema, PinSchema, FileKindSchema, MarkSchema, ProjectIdSchema, ShotSchema, LEVEL_MIN, LEVEL_MAX, LEVEL_STEP, lanesForVideo, picksForVideo, variantFilms } from "../core/schema.js";
31
31
  import { LABEL_MAX, oneLineOf } from "../core/labels.js";
32
32
  import { byOf, logBookFor } from "./logbook.js";
33
33
  import { BriefService } from "./brief.js";
@@ -36,7 +36,12 @@ import { buildState, planWarning } from "../core/plan.js";
36
36
  import { broughtInEvent, cutEvent, fileEvent, filmEvent, formatEvent, lineEvent, lockEvent, notesSentEvent, picksEvent, repliesEvent, scriptEvent, takeEvent, variantEvent, variantFilmsEvent, visualEvent, } from "../core/logEvents.js";
37
37
  import { LOG_AREAS, LOG_MAX, changeLogFileName, logText, recentChanges } from "../core/logText.js";
38
38
  import { defaultRunner, measureMix } from "./loudness.js";
39
- export const VERSION = "0.9.1";
39
+ import { clearDetectCache, detectAgents } from "./agent/detect.js";
40
+ import { openInTerminal } from "./agent/terminal.js";
41
+ import { agentRulesFor } from "./agent/rules.js";
42
+ import { notifyWhenWaiting, osNotifier } from "./agent/notify.js";
43
+ import { VERSION } from "../version.js";
44
+ export { VERSION };
40
45
  async function body(c, schema) {
41
46
  let json;
42
47
  try {
@@ -177,6 +182,10 @@ const LevelValue = z.number().min(LEVEL_MIN).max(LEVEL_MAX).multipleOf(LEVEL_STE
177
182
  const LevelsBody = z.object({ voice: LevelValue.nullable(), music: LevelValue.nullable(), sfx: LevelValue.nullable() }).partial();
178
183
  const PutAwayBody = z.object({ away: z.boolean() });
179
184
  const PicksBody = z.object({ video: z.string().min(1).max(200).optional(), lanes: PickMap.optional(), sections: PickMap.optional(), levels: LevelsBody.optional() });
185
+ // §28: the Send to AI switch, the agent and what it may do unasked.
186
+ // `batch` (I3): the filed batch the copy dialog was showing when its Set up opened the sheet. Once Send to AI is on, it is
187
+ // handed to the agent, as Send would have.
188
+ const AgentSetupBody = z.object({ on: z.boolean(), agent: z.enum(AGENTS).optional(), permissions: AgentPermissionsSchema.optional(), batch: z.string().min(1).optional() });
180
189
  // No stage: every tab's open notes (Send). A stage: that tab's only.
181
190
  const BatchBody = z.object({ stage: StageSchema.optional() });
182
191
  const NoteQuery = z.object({
@@ -274,6 +283,27 @@ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
274
283
  export const DEFAULT_WEB_DIR = fileURLToPath(new URL("../../web-dist/", import.meta.url));
275
284
  /** How long a waiting scan (§20.7) answers at most, before it says it is still scanning. */
276
285
  export const FOUND_WAIT_MS = 20_000;
286
+ /** How long Send's response waits for the agent to take the batch (a first start can take minutes). */
287
+ export const SEND_WAIT_MS = 5_000;
288
+ // `asked`: with no runner there is nothing to set up, so Send never opens the first-Send sheet.
289
+ const OFF_STATUS = {
290
+ on: false, agent: null, phase: "off", batches: [], followUps: [], current: { note: null, doing: null }, asks: [], lines: [], error: null, session: null,
291
+ asked: true, permissions: "project-edits", always: [],
292
+ };
293
+ /** The stand-in when no runner is given: Send to AI is off, and nothing can drive an agent. */
294
+ function noAgent() {
295
+ const none = () => Promise.reject(new RushesError("Send to AI runs only in a Rushes server.", 503, "agent_unavailable"));
296
+ return {
297
+ status: () => structuredClone(OFF_STATUS),
298
+ reload: async () => structuredClone(OFF_STATUS),
299
+ send: async () => ({ handedTo: null, why: "Send to AI is off" }),
300
+ resend: async () => null,
301
+ stop: async () => undefined,
302
+ answer: none,
303
+ removeRule: none,
304
+ workingOn: none,
305
+ };
306
+ }
277
307
  const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost"]);
278
308
  /** Hostname of "host[:port]" or a full origin URL, lowercased, or null when it doesn't parse. */
279
309
  function hostnameOf(value, isUrl) {
@@ -294,6 +324,11 @@ export function createApp(store, opts = {}) {
294
324
  const found = opts.found ?? new FoundScanner({ store, probe: ffprobeDuration, announce: foundAnnouncer(store) });
295
325
  const brief = opts.brief ?? new BriefService(store);
296
326
  const storyboard = opts.storyboard ?? new StoryboardService(store);
327
+ // §28: made before any route is reachable, so every agent route and Send has it.
328
+ const agent = opts.agent ?? noAgent();
329
+ const sendWaitMs = opts.sendWaitMs ?? SEND_WAIT_MS;
330
+ const detect = opts.detect ?? (() => detectAgents());
331
+ const terminal = opts.terminal ?? openInTerminal;
297
332
  /** §24.12: whether the plan (brief, script, storyboard) is approved, from the files as they are now. */
298
333
  const planBuild = async () => {
299
334
  const [b, script, sb] = await Promise.all([brief.view(), store.read("script"), storyboard.view()]);
@@ -660,6 +695,9 @@ export function createApp(store, opts = {}) {
660
695
  // Event streams open now. Only `?test=1` shows it, so the e2e suite can check that a browser's
661
696
  // tabs share one stream (§19.8).
662
697
  let streams = 0;
698
+ // §5.4: with a runner, the Mac is told when the agent waits on the user and no desk is open to show it.
699
+ if (opts.agent)
700
+ notifyWhenWaiting(store, opts.notify ?? osNotifier(), () => streams);
663
701
  app.get("/api/health", async (c) => {
664
702
  const [project, id] = await Promise.all([store.read("project"), getProjectId()]);
665
703
  // Ruling e: Change Log lines that couldn't be written are counted for `rushes doctor`, only when there are any.
@@ -838,6 +876,13 @@ export function createApp(store, opts = {}) {
838
876
  const { result } = await store.update("notes", (f) => applyUserEdit(f, { id: c.req.param("id"), ...b }, check));
839
877
  return c.json({ note: withState(result) });
840
878
  });
879
+ app.post("/api/notes/:id/replies", async (c) => {
880
+ const b = await body(c, z.object({ text: z.string() }));
881
+ const id = c.req.param("id");
882
+ const { result } = await store.update("notes", (f) => addUserReply(f, id, b.text));
883
+ store.emit("user-reply", { note: id, text: b.text.trim() });
884
+ return c.json({ note: withState(result) }, 201);
885
+ });
841
886
  app.post("/api/replies", async (c) => {
842
887
  const b = await body(c, RepliesBody);
843
888
  const { result } = await store.update("notes", (f) => b.replies.map((r) => applyReply(f, r)));
@@ -1335,9 +1380,25 @@ export function createApp(store, opts = {}) {
1335
1380
  // is recorded first and the notes are marked second: if the second write fails, the notes are
1336
1381
  // still unsent and go out again in the next batch. The other way round, a failure stranded notes
1337
1382
  // naming a batch that was never recorded, and the next batch reused its id.
1383
+ // §28: once filed, the batch goes to the agent runner (with Send to AI off it says so and the desk copies
1384
+ // the prompt). The hand-over starts inside the queue, so two Sends reach the runner in the order they were
1385
+ // filed, but the queue doesn't wait for it: an agent starting up never holds the next Send's filing.
1338
1386
  let batchQueue = Promise.resolve();
1387
+ /**
1388
+ * What a hand-over says to the desk. It never fails because of the agent: an error becomes the reason it wasn't
1389
+ * handed over, and an agent still starting after sendWaitMs never holds the answer (it says so, and the run carries on).
1390
+ */
1391
+ const handOverOf = async (handing) => {
1392
+ const handed = handing.catch((e) => ({ handedTo: null, why: e instanceof Error ? e.message : String(e) }));
1393
+ let timer;
1394
+ const late = Symbol("late");
1395
+ const waited = new Promise((ok) => { timer = setTimeout(() => ok(late), sendWaitMs); });
1396
+ const settled = await Promise.race([handed, waited]).finally(() => clearTimeout(timer));
1397
+ return settled === late ? { handedTo: agent.status().agent, starting: true } : settled;
1398
+ };
1339
1399
  app.post("/api/batches", async (c) => {
1340
1400
  const { stage } = await body(c, BatchBody);
1401
+ let handing;
1341
1402
  const run = batchQueue.catch(() => undefined).then(async () => {
1342
1403
  const [project, script, notes, batches] = await Promise.all([store.read("project"), store.read("script"), store.read("notes"), store.read("batches")]);
1343
1404
  // createBatch marks the notes it takes and files the batch in `batches`; on copies, it only
@@ -1353,10 +1414,12 @@ export function createApp(store, opts = {}) {
1353
1414
  await store.update("batches", (f) => { f.batches.push(result); });
1354
1415
  await store.update("notes", (f) => markSent(f.notes, result));
1355
1416
  await log.add(() => notesSentEvent(result), by(c));
1417
+ handing = (async () => agent.send(result))();
1356
1418
  return result;
1357
1419
  });
1358
1420
  batchQueue = run;
1359
- return c.json({ batch: await run }, 201);
1421
+ const batch = await run;
1422
+ return c.json({ batch, agent: await handOverOf(handing) }, 201);
1360
1423
  });
1361
1424
  app.get("/api/batches/:id", async (c) => {
1362
1425
  const [batches, notes, script, visuals] = await Promise.all([store.read("batches"), store.read("notes"), store.read("script"), store.read("visuals")]);
@@ -1436,20 +1499,134 @@ export function createApp(store, opts = {}) {
1436
1499
  throw new RushesError("The Change Log couldn't be written. Run `rushes doctor`.", 500, "log_unwritable");
1437
1500
  return c.json({ entry }, 201);
1438
1501
  });
1502
+ // ---- Send to AI (§28) ----
1503
+ const agentStatusOf = async () => ({ status: await agent.reload() });
1504
+ app.get("/api/agent", async (c) => c.json(await agentStatusOf()));
1505
+ // ?fresh=1 checks again now (after the user signs in), not from the last 30 s.
1506
+ app.get("/api/agent/detect", async (c) => {
1507
+ if (c.req.query("fresh") === "1")
1508
+ clearDetectCache();
1509
+ return c.json({ agents: await detect() });
1510
+ });
1511
+ app.post("/api/agent/setup", async (c) => {
1512
+ const b = await body(c, AgentSetupBody);
1513
+ const filed = b.batch === undefined ? null : (await store.read("batches")).batches.find((x) => x.id === b.batch);
1514
+ if (filed === undefined)
1515
+ throw new NotFoundError("batch", b.batch);
1516
+ const rules = agentRulesFor(store);
1517
+ // Consent fix: a change of the level alone (the agent menu's, which names no agent) changes the level and nothing
1518
+ // else. It never chooses an agent, never keeps one the user didn't choose, and leaves the switch as it is.
1519
+ const permissions = b.permissions;
1520
+ if (permissions !== undefined && b.agent === undefined) {
1521
+ await rules.update((f) => void (f.permissions = permissions));
1522
+ return c.json(await agentStatusOf());
1523
+ }
1524
+ // The row's switch names no agent: it turns on the one agent.json names, so it can't stand in for the sheet's "who"
1525
+ // and "what may it do" until the user has answered the sheet once (a prepared project shows Set up, not a switch).
1526
+ if (b.on && b.agent === undefined && !(await rules.read()).setUp) {
1527
+ throw new RushesError("Choose who should get the notes first: Set up Send to AI.", 409, "agent_not_set_up");
1528
+ }
1529
+ let checked = null;
1530
+ if (b.on) {
1531
+ const id = b.agent ?? (await store.read("agent")).agent;
1532
+ if (!id)
1533
+ throw new InvalidError("Choose an agent to turn Send to AI on");
1534
+ // Checked again now, so a user who has just signed in isn't refused from the cache.
1535
+ clearDetectCache();
1536
+ const info = (await detect()).find((a) => a.id === id);
1537
+ const name = info?.name ?? (id === "claude" ? "Claude Code" : "Codex");
1538
+ if (!info?.installed)
1539
+ throw new RushesError(`${name} is not installed.`, 409, "agent_not_installed", { agent: id });
1540
+ if (!info.signedIn)
1541
+ throw new RushesError(`${name} is not signed in. Choose Sign in in Terminal, then try again.`, 409, "agent_not_signed_in", { agent: id });
1542
+ checked = id;
1543
+ }
1544
+ // R10, I1 and the consent fix: the user's answer to the first-Send sheet, the agent they turned on (none after Copy a
1545
+ // prompt or switching off) and what it may do are kept in their own rules file, outside the project, where neither
1546
+ // the agent nor a project folder from someone else can set them. Revoke first, grant last: switching off clears the
1547
+ // agent before agent.json is written, so a failure between the two leaves nothing chosen; turning on writes it only
1548
+ // once agent.json took the change, so a refused setup (409) leaves the file as it was.
1549
+ const consent = () => rules.update((f) => {
1550
+ f.setUp = true;
1551
+ f.agent = checked;
1552
+ if (permissions !== undefined)
1553
+ f.permissions = permissions;
1554
+ });
1555
+ if (!b.on)
1556
+ await consent();
1557
+ await store.update("agent", (f) => {
1558
+ // Turned on only for the agent that was checked: one changed meanwhile (another tab) is refused.
1559
+ if (b.on && (b.agent ?? f.agent) !== checked)
1560
+ throw new RushesError("The agent changed. Try again.", 409, "agent_changed");
1561
+ f.on = b.on;
1562
+ // Another agent can't continue this one's conversation.
1563
+ if (b.agent !== undefined && b.agent !== f.agent) {
1564
+ f.agent = b.agent;
1565
+ f.session = null;
1566
+ }
1567
+ });
1568
+ if (b.on)
1569
+ await consent();
1570
+ // I3: the batch the dialog showed goes to the agent now, if its hand-over was refused and it hasn't gone since (the
1571
+ // runner takes it from its refused set once, under its send lock), while notes of it still wait.
1572
+ if (b.on && filed && (await store.read("notes")).notes.some((n) => n.batch === filed.id && noteState(n) === "sent")) {
1573
+ const handed = await handOverOf(agent.resend(filed));
1574
+ if (handed)
1575
+ return c.json({ ...(await agentStatusOf()), agent: handed });
1576
+ }
1577
+ return c.json(await agentStatusOf());
1578
+ });
1579
+ // Start a fresh conversation: the next Send starts a new session.
1580
+ app.post("/api/agent/fresh", async (c) => {
1581
+ await store.update("agent", (f) => { f.session = null; });
1582
+ return c.json(await agentStatusOf());
1583
+ });
1584
+ app.post("/api/agent/stop", async (c) => {
1585
+ await agent.stop();
1586
+ return c.json(await agentStatusOf());
1587
+ });
1588
+ app.post("/api/agent/permission/:id", async (c) => {
1589
+ const { choice } = await body(c, z.object({ choice: z.enum(["once", "always", "no"]) }));
1590
+ await agent.answer(c.req.param("id"), choice);
1591
+ return c.json(await agentStatusOf());
1592
+ });
1593
+ // T6: a rule is named by what it is, so two tabs removing rules never take out the wrong one.
1594
+ app.delete("/api/agent/always", async (c) => {
1595
+ const rule = await body(c, AlwaysRuleSchema);
1596
+ await agent.removeRule(rule);
1597
+ return c.json(await agentStatusOf());
1598
+ });
1599
+ // The command is the agent's own login command from detection, never text from the request.
1600
+ app.post("/api/agent/sign-in", async (c) => {
1601
+ const b = await body(c, z.object({ agent: z.enum(AGENTS) }));
1602
+ const info = (await detect()).find((a) => a.id === b.agent);
1603
+ if (!info)
1604
+ throw new InvalidError(`Rushes doesn't know how to sign in to ${b.agent}`);
1605
+ await terminal(info.signIn);
1606
+ return c.body(null, 204);
1607
+ });
1608
+ app.post("/api/agent/working-on", async (c) => {
1609
+ const b = await body(c, z.object({ note: z.string().min(1), doing: z.string().min(1).max(200) }));
1610
+ await agent.workingOn(b.note, b.doing);
1611
+ return c.body(null, 204);
1612
+ });
1439
1613
  // ---- live updates ----
1440
1614
  app.get("/api/events", (c) => streamSSE(c, async (stream) => {
1441
1615
  const send = (e) => void stream.writeSSE({ event: "change", data: JSON.stringify(e) });
1442
1616
  const corrupt = (e) => void stream.writeSSE({ event: "corrupt", data: JSON.stringify(e) });
1443
1617
  const proxy = (e) => void stream.writeSSE({ event: "proxy", data: JSON.stringify(e) });
1618
+ const agentStatus = (s) => void stream.writeSSE({ event: "agent", data: JSON.stringify(s) });
1444
1619
  store.on("change", send);
1445
1620
  store.on("corrupt", corrupt);
1446
1621
  store.on("proxy", proxy);
1622
+ store.on("agent", agentStatus);
1447
1623
  streams++;
1448
1624
  stream.onAbort(() => {
1449
1625
  streams--;
1450
1626
  store.off("change", send);
1451
1627
  store.off("corrupt", corrupt);
1452
1628
  store.off("proxy", proxy);
1629
+ store.off("agent", agentStatus);
1453
1630
  });
1454
1631
  await stream.writeSSE({ event: "hello", data: JSON.stringify({ root: store.root }) });
1455
1632
  while (!stream.aborted)
@@ -1,7 +1,11 @@
1
1
  import { createServer } from "node:http";
2
+ import { existsSync, readFileSync } from "node:fs";
2
3
  import { mkdir, realpath } from "node:fs/promises";
3
- import { basename, resolve } from "node:path";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
4
6
  import { getRequestListener } from "@hono/node-server";
7
+ import { z } from "zod";
8
+ import { AGENTS } from "../core/schema.js";
5
9
  import { Store } from "../core/store.js";
6
10
  import { ensureProjectIdOnce } from "../core/project.js";
7
11
  import { createApp } from "./app.js";
@@ -12,7 +16,72 @@ import { StoryboardService } from "./storyboard.js";
12
16
  import { ProxyJobs, removePartials } from "./proxy.js";
13
17
  import { PeakJobs, removeOrphanPeaks, removePeakTemps } from "./peaks.js";
14
18
  import { FoundScanner, ffprobeDuration, foundAnnouncer } from "./found.js";
19
+ import { AgentRunner } from "./agent/runner.js";
20
+ import { rushesMcp } from "./agent/adapters.js";
21
+ import { RUSHES_SERVER } from "./agent/ownTools.js";
15
22
  export const DEFAULT_PORT = 4580;
23
+ /*
24
+ * Browser tests only: RUSHES_TEST_AGENT starts the fake agent (test/helpers/fake-acp.mjs) in place of a real adapter,
25
+ * so no test ever reaches a model. Read only when NODE_ENV is "test" or RUSHES_E2E is "1"; anywhere else it is
26
+ * ignored and the server detects and starts the user's own agents. Options passed to startServer (`agent`) win over it.
27
+ *
28
+ * RUSHES_TEST_AGENT='{ "command": "node", "args": ["test/helpers/fake-acp.mjs"], "env": { "FAKE_ACP_SCENARIO": "…" },
29
+ * "agents": [{ "id": "claude", "installed": true, "signedIn": true }] }'
30
+ *
31
+ * `command`, `args` and `env` start the adapter for either agent, in the project folder. `agents` (optional) stands in
32
+ * for detection: an agent it leaves out is not installed. `agentsFile` (optional) is a JSON file holding the same list,
33
+ * read at every detection, so a test can sign an agent in or out while the server runs; it wins over `agents`. Without it, Claude Code and Codex are both installed and
34
+ * signed in. The fake's scenario must offer the mode each agent asks Rushes in (ASK_MODE), or the start fails:
35
+ * "default" for Claude Code, "read-only" for Codex, as `"modes": ["default", "read-only"]` in the scenario or
36
+ * FAKE_ACP_MODES=default,read-only in `env`.
37
+ */
38
+ const TestAgentShape = z.object({
39
+ command: z.string().min(1),
40
+ args: z.array(z.string()).default([]),
41
+ env: z.record(z.string(), z.string()).default({}),
42
+ agents: z.array(z.object({ id: z.enum(AGENTS), installed: z.boolean(), signedIn: z.boolean() })).optional(),
43
+ agentsFile: z.string().optional(),
44
+ });
45
+ const TestAgentsShape = TestAgentShape.shape.agents.unwrap();
46
+ const TEST_AGENT_INFO = {
47
+ claude: { name: "Claude Code", signIn: "claude auth login", bin: "claude" },
48
+ codex: { name: "Codex", signIn: "codex login", bin: "codex" },
49
+ };
50
+ /** The Rushes MCP server for the fake agent: the built CLI when there is one, as a real run has, else the source under tsx. */
51
+ function testMcp(root) {
52
+ // src/server/ and dist/server/ are both two folders below the package root.
53
+ const pkg = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
54
+ if (existsSync(join(pkg, "dist", "cli", "index.js")))
55
+ return rushesMcp(root);
56
+ return { name: RUSHES_SERVER, command: join(pkg, "node_modules", ".bin", "tsx"), args: [join(pkg, "src", "cli", "index.ts"), "mcp", root, "--pinned"], env: [] };
57
+ }
58
+ /** The runner options RUSHES_TEST_AGENT asks for, or undefined when it is unset or not allowed here. */
59
+ export function testAgentOptions(env = process.env) {
60
+ const raw = env.RUSHES_TEST_AGENT;
61
+ if (!raw || !(env.NODE_ENV === "test" || env.RUSHES_E2E === "1"))
62
+ return undefined;
63
+ let hook;
64
+ try {
65
+ hook = TestAgentShape.parse(JSON.parse(raw));
66
+ }
67
+ catch (e) {
68
+ throw new Error(`RUSHES_TEST_AGENT is not valid: ${e instanceof Error ? e.message : String(e)}`);
69
+ }
70
+ // As detectAgents answers: every agent, in its order, and only an installed one can be signed in.
71
+ const answer = (list) => AGENTS.map((id) => {
72
+ const given = list ? list.find((a) => a.id === id) : { installed: true, signedIn: true };
73
+ const installed = given?.installed ?? false;
74
+ const { name, signIn, bin } = TEST_AGENT_INFO[id];
75
+ return { id, name, installed, signedIn: installed && (given?.signedIn ?? false), path: installed ? `/usr/local/bin/${bin}` : null, signIn };
76
+ });
77
+ const agents = answer(hook.agents);
78
+ const file = hook.agentsFile;
79
+ return {
80
+ detect: async () => (file ? answer(TestAgentsShape.parse(JSON.parse(readFileSync(file, "utf8")))) : structuredClone(agents)),
81
+ spec: (_agent, root) => ({ command: hook.command, args: [...hook.args], env: { ...hook.env }, cwd: root }),
82
+ mcp: testMcp,
83
+ };
84
+ }
16
85
  function listen(server, port, host) {
17
86
  return new Promise((ok, fail) => {
18
87
  const onError = (e) => {
@@ -53,7 +122,14 @@ export async function startServer(rootDir, opts = {}) {
53
122
  const found = new FoundScanner({ store, probe: opts.found?.probe ?? ffprobeDuration, announce: foundAnnouncer(store), limits: opts.found?.limits });
54
123
  const brief = new BriefService(store);
55
124
  const storyboard = new StoryboardService(store);
56
- const appOpts = { brief, storyboard, webDir: opts.webDir, onShutdown: () => void close(), reveal: opts.reveal, proxyJobs, peakJobs, found, formatProbe: opts.formats?.probe };
125
+ // §28: one agent runner per server, on the root it serves, made before the app so every route has it.
126
+ // Browser tests drive the fake agent through RUSHES_TEST_AGENT (ignored outside tests).
127
+ const agentOpts = opts.agent ?? testAgentOptions();
128
+ const runner = new AgentRunner(store, agentOpts);
129
+ const appOpts = {
130
+ brief, storyboard, webDir: opts.webDir, onShutdown: () => void close(), reveal: opts.reveal, proxyJobs, peakJobs, found, formatProbe: opts.formats?.probe,
131
+ agent: runner, detect: agentOpts?.detect, notify: opts.notify,
132
+ };
57
133
  const app = createApp(store, appOpts);
58
134
  const listener = getRequestListener(app.fetch);
59
135
  let lastRequest = Date.now();
@@ -85,6 +161,7 @@ export async function startServer(rootDir, opts = {}) {
85
161
  catch (e) {
86
162
  // Another server owns this project, or the lock couldn't be written: don't leave a socket open.
87
163
  found.close();
164
+ await runner.close();
88
165
  server.closeAllConnections?.();
89
166
  await new Promise((ok) => server.close(() => ok()));
90
167
  throw e;
@@ -129,7 +206,8 @@ export async function startServer(rootDir, opts = {}) {
129
206
  found.close();
130
207
  // A running proxy's ffmpeg must not outlive the server; its partial file is deleted too.
131
208
  // From here no new job starts either (a POST or an autoProxy cut racing the close).
132
- await Promise.all([proxyJobs.close(), peakJobs.close()]);
209
+ // The agent's adapter goes too (its pending asks are cancelled); the notes it had go back to to do.
210
+ await Promise.all([proxyJobs.close(), peakJobs.close(), runner.close()]);
133
211
  server.closeAllConnections?.();
134
212
  await new Promise((ok) => server.close(() => ok()));
135
213
  await removeLock(root, token);
@@ -141,7 +219,8 @@ export async function startServer(rootDir, opts = {}) {
141
219
  const idleMs = opts.idleMs;
142
220
  const tick = () => {
143
221
  server.getConnections((_err, open) => {
144
- if (open === 0 && Date.now() - lastRequest >= idleMs)
222
+ // Never while the agent is working, or waiting on the user: its run would die with the server.
223
+ if (open === 0 && Date.now() - lastRequest >= idleMs && !runner.busy())
145
224
  void close();
146
225
  else
147
226
  idleTimer = setTimeout(tick, Math.max(50, idleMs / 4));
@@ -0,0 +1,2 @@
1
+ /** The Rushes version. A leaf module so any server file can import it without a cycle. */
2
+ export const VERSION = "0.10.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rushes",
3
- "version": "0.9.1",
3
+ "version": "0.10.0",
4
4
  "description": "A local review desk for video made with AI agents: timecoded notes, script edits and audio picks your agent can read and act on.",
5
5
  "keywords": [
6
6
  "video",
@@ -64,7 +64,7 @@ For stills, standalone images and carousels, register one visual per post with `
64
64
  - `rushes_add_variant` for each voice read, music bed or SFX pass, with `video` set to the film it is for, or a list of films when one bed is fitted to several (only those films' tabs list it; with more than one film, one without `video` is on no film until it is put on one, and `rushes_set_films` moves an existing one). Put a take only on the films it was fitted to (a read timed to one film's cut is that film's alone, even when another film shares its script), and when a new cut changes a film's length or timing, fit its bed and effects to that cut as new takes. Voice reads carry `stage: "voice"` and a `round` (its name — reads in one round are compared side by side; a new direction gets a new round); say what the read is, or what changed, in `description`. Music and SFX take a `round` too (each new batch is a round). A take you add is not in use until the user picks it. Music and SFX carry `meta.description` for their row in the list of takes, and SFX passes carry `cues` as `{name, t, file?}`: the same name each time a sound comes back, and `file` (an audio file) when you know which sample you placed;
65
65
  - `rushes_set_shots` for the storyboard's shots, once you have the first cut; send new timings when a later cut moves them.
66
66
  2. Call `rushes_open` and tell the user it's ready, with what it brought in and what it left (below). Each project's dashboard lives at its own address, `/p/<id>/`.
67
- 3. When the user sends a batch, call `rushes_get_batch` and fix every note in it. A batch holds every open note from every tab and film, so each note's own `stage` and `video` say where it belongs. A note carries the `shot` it falls in; on an audio stage, call `rushes_get_picks` first — for a mix note (stage `mix`, made on the Timeline tab) it also returns `levels` (dB per sound), which you read, not set. Its `on` says what it's about: `"<lane>/<variant>"` for a bed, pass or voice read (for a voice read the lane names the round), `"<lane>/<variant>:<cue>"` for an SFX cue, `"vo"` for the voice in the mix, or `null` for the whole mix; older notes may carry a section id or `"<section>:<take>"`. On music, sfx and mix notes treat `marks` (e.g. "Fall", "Quieter 3 dB") as part of the note; voice notes carry none — they're on the whole read, a point in it, or a range of it (`t` to `tOut`: replace or fix just that stretch), and the `text` says what to change. A note on the cut (stage `picture`) has a `format` that is null for every format, or a format id such as `"9x16"`: when it isn't null, fix only that format. Picks are set from the dashboard only — no tool or CLI command sets one.
67
+ 3. When the user sends a batch, call `rushes_get_batch` and fix every note in it. Before you start on each note, call `rushes_working_on` with its id and what you are doing, in a few plain words: the user sees it on the note while you work. A batch holds every open note from every tab and film, so each note's own `stage` and `video` say where it belongs. A note carries the `shot` it falls in; on an audio stage, call `rushes_get_picks` first — for a mix note (stage `mix`, made on the Timeline tab) it also returns `levels` (dB per sound), which you read, not set. Its `on` says what it's about: `"<lane>/<variant>"` for a bed, pass or voice read (for a voice read the lane names the round), `"<lane>/<variant>:<cue>"` for an SFX cue, `"vo"` for the voice in the mix, or `null` for the whole mix; older notes may carry a section id or `"<section>:<take>"`. On music, sfx and mix notes treat `marks` (e.g. "Fall", "Quieter 3 dB") as part of the note; voice notes carry none — they're on the whole read, a point in it, or a range of it (`t` to `tOut`: replace or fix just that stretch), and the `text` says what to change. A note on the cut (stage `picture`) has a `format` that is null for every format, or a format id such as `"9x16"`: when it isn't null, fix only that format. Picks are set from the dashboard only — no tool or CLI command sets one.
68
68
  4. Register the new cut with `rushes_add_version`. On a locked video the reply carries a `warning`.
69
69
  5. Reply to all the notes in one `rushes_reply` call. For each note set `status: "done"`, a one-line `reply`, `fixT` (when the fix is visible in the new cut, in seconds) and `fixVersion`. Each note has a `state`: `todo` (not sent yet), `sent` (yours to fix) or `done`; `rushes_list_notes` with `state: "sent"` finds every note you still owe. `rushes_get_picks` lists each take's `state` too (`in-use`, `new`, `earlier`, `put-away`): never offer a put-away take again.
70
70
  6. For script batches: when a section's `proposed` differs from `current`, adopt it with `rushes_set_script`, sending just that section with its `id`. If voiceover already exists, re-record the picked voice with the corrected script and register it with `rushes_add_variant` as a new read in a new round.
@@ -80,4 +80,4 @@ When asked to open or review work in Rushes, call `rushes_open`, then tell the u
80
80
 
81
81
  No project to show yet? Run `npx -y rushes demo <folder> --no-browser`, then `rushes_open` with `project: "<folder>"`. The demo builds a complete working example on the user's machine, with a cut, script, voice reads, music and notes already in place. Always pass `--no-browser`: without it the command stays running as the server and never returns.
82
82
 
83
- Rushes has twenty-four tools: `rushes_open`, `rushes_status`, `rushes_add_version`, `rushes_add_format`, `rushes_add_visual`, `rushes_add_variant`, `rushes_set_films`, `rushes_set_script`, `rushes_get_script`, `rushes_add_take`, `rushes_list_notes`, `rushes_list_assets`, `rushes_get_batch`, `rushes_reply`, `rushes_get_picks`, `rushes_set_shots`, `rushes_lock_picture`, `rushes_add_file`, `rushes_export_notes`, `rushes_log`, `rushes_get_log`, `rushes_scan`, `rushes_bring_in` and `rushes_doctor` (environment and project health check) — `rushes_add_take` stays only for compatibility and isn't used for voiceover. The full contract is in `AGENTS.md` at the package root.
83
+ Rushes has twenty-five tools: `rushes_open`, `rushes_status`, `rushes_add_version`, `rushes_add_format`, `rushes_add_visual`, `rushes_add_variant`, `rushes_set_films`, `rushes_set_script`, `rushes_get_script`, `rushes_add_take`, `rushes_list_notes`, `rushes_list_assets`, `rushes_get_batch`, `rushes_reply`, `rushes_working_on`, `rushes_get_picks`, `rushes_set_shots`, `rushes_lock_picture`, `rushes_add_file`, `rushes_export_notes`, `rushes_log`, `rushes_get_log`, `rushes_scan`, `rushes_bring_in` and `rushes_doctor` (environment and project health check) — `rushes_add_take` stays only for compatibility and isn't used for voiceover. The full contract is in `AGENTS.md` at the package root.