@openmuster/muster 0.3.1-alpha.3 → 0.3.1-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +16 -10
  2. package/dist/{args-DX9QSK1f.js → args-CaFBa2IP.js} +305 -23
  3. package/dist/cli.js +3 -3
  4. package/dist/index.d.ts +67 -18
  5. package/dist/index.js +106 -41
  6. package/dist/inspect/app.js +79 -51
  7. package/dist/{main-DgrIMbeA.js → main-BeEB08iI.js} +397 -26
  8. package/dist/main-CLzQkYeG.js +6 -0
  9. package/dist/mcp-CAAZRJgv.js +6 -0
  10. package/dist/{module-C-HJjWWo.js → module-BX2IjSiv.js} +2 -2
  11. package/dist/{module-CxoN1MOe.js → module-D9KdbEpS.js} +1 -1
  12. package/dist/skills/board/SKILL.md +5 -0
  13. package/dist/{steps-DtzUdcBE.js → steps-FNDWY1P_.js} +16 -4
  14. package/docs/01-concepts/09-watchers.md +4 -32
  15. package/docs/01-concepts/10-schedules.md +1 -1
  16. package/docs/01-concepts/11-access.md +19 -3
  17. package/docs/01-concepts/13-budgets.md +66 -3
  18. package/docs/01-concepts/15-outgoing-webhooks.md +6 -19
  19. package/docs/01-concepts/16-workflows.md +22 -2
  20. package/docs/01-quickstart.md +74 -42
  21. package/docs/02-sync/01-overview.md +34 -2
  22. package/docs/02-sync/02-github.md +40 -19
  23. package/docs/02-sync/03-linear.md +103 -85
  24. package/docs/02-sync/04-slack.md +116 -111
  25. package/docs/02-sync/05-notion.md +46 -25
  26. package/docs/03-guides/01-coding-agents.md +51 -33
  27. package/docs/03-guides/02-swarm.md +30 -15
  28. package/docs/03-guides/03-factory.md +193 -80
  29. package/docs/03-guides/04-inspector.md +79 -29
  30. package/docs/03-guides/05-running-agents.md +62 -35
  31. package/docs/03-guides/06-sandboxed-agents.md +488 -305
  32. package/docs/03-guides/07-build-a-ui.md +86 -31
  33. package/docs/03-guides/08-ci.md +59 -36
  34. package/docs/03-guides/09-daemon.md +121 -53
  35. package/docs/03-guides/10-two-agents.md +31 -22
  36. package/docs/03-guides/11-person-in-the-loop.md +47 -34
  37. package/docs/03-guides/12-unattended.md +46 -27
  38. package/docs/03-guides/13-terminals.md +51 -39
  39. package/docs/03-guides/14-no-cloud.md +31 -19
  40. package/docs/03-guides/15-several-boards.md +61 -27
  41. package/docs/03-guides/16-non-code.md +29 -18
  42. package/docs/03-guides/17-mcp.md +37 -30
  43. package/docs/03-guides/18-a-board-on-a-server.md +66 -43
  44. package/docs/03-guides/19-a-card-queue.md +210 -121
  45. package/docs/03-guides/20-a-feedback-loop.md +298 -134
  46. package/docs/03-guides/21-running-the-loop.md +94 -64
  47. package/docs/03-guides/22-building-from-linear.md +81 -57
  48. package/docs/04-reference/01-cli.md +8 -0
  49. package/docs/04-reference/02-handle.md +10 -15
  50. package/docs/04-reference/03-http.md +1 -1
  51. package/docs/04-reference/04-events.md +2 -1
  52. package/docs/04-reference/05-errors.md +3 -0
  53. package/docs/04-reference/08-files.md +49 -0
  54. package/docs/index.md +22 -0
  55. package/package.json +1 -1
  56. package/dist/main-CdVlnWHy.js +0 -6
  57. package/dist/mcp-NueWYyQs.js +0 -6
@@ -1,6 +1,6 @@
1
- import { A as file, C as ROUTES, D as releaseTarball, E as VERSION, F as dropClaim, I as heldClaim, K as processStart, L as keepClaim, O as loadOidc, P as configDir, S as listen, T as RELEASE_HOSTS, Z as actorId, _ as why, a as on, c as str, d as board, f as syncLoop, g as ping, h as armHooks, i as list, it as misuse, j as boardKey, k as boardPath, m as HOOKS_LEASE, n as duration, nt as profileName, o as pairs, p as DROPPED, r as id, rt as Failure, s as parse, t as cursor, tt as labelFilter, u as ROOT, v as holdLease, x as isLoopback } from "./args-DX9QSK1f.js";
2
- import { E as KEEP_LOGS_MS, F as conformance, M as generic, N as isSessionId, O as runLocal, P as http, T as installationToken, _ as BUNDLE_MAX, b as openPullRequest, c as runWorkflows, d as workflowsPath, f as e2b, g as BUNDLE, h as vercel, i as pushesTask, k as AGENTS, l as spawnWorker, m as cloudflare, n as fillResults, p as SANDBOX_ENV, r as pullTitle, s as openRuns, t as FillRefused, u as loadWorkflows, v as branchState, w as githubApp, x as pushBundle, y as githubRepo } from "./steps-DtzUdcBE.js";
3
- import { C as begin, D as reset, E as readGuard, O as retryAt, S as STEADY_AFTER, T as guardPath, b as RESTART_LIMIT, c as chooseModule, d as invokedAs, f as launchGuard, k as steady, l as defaultModule, m as loadsModule, p as loadBoard, s as SERVE_SPEC, t as DAEMON_SPEC, u as endLaunch, v as refusal, w as ended, x as RESTART_WINDOW, y as self } from "./module-CxoN1MOe.js";
1
+ import { A as boardPath, B as heldClaim, C as listen, D as VERSION, E as RELEASE_HOSTS, F as retiredKeys, I as rotateKey, M as boardKey, N as dropRetiredKeys, O as releaseTarball, R as configDir, S as isLoopback, V as keepClaim, X as processStart, _ as ping, a as list, at as labelFilter, c as parse, ct as cursorAhead, d as ROOT, f as board, g as armHooks, h as HOOKS_LEASE, i as id, j as file, k as loadOidc, l as str, lt as misuse, m as DROPPED, n as cursor, o as on, ot as profileName, p as syncLoop, r as duration, s as pairs, st as Failure, t as GLOBAL, tt as actorId, v as why, w as ROUTES, y as holdLease, z as dropClaim } from "./args-CaFBa2IP.js";
2
+ import { E as KEEP_LOGS_MS, F as conformance, M as generic, N as isSessionId, O as runLocal, P as http, T as installationToken, _ as BUNDLE_MAX, b as openPullRequest, c as runWorkflows, d as workflowsPath, f as e2b, g as BUNDLE, h as vercel, i as pushesTask, k as AGENTS, l as spawnWorker, m as cloudflare, n as fillResults, p as SANDBOX_ENV, r as pullTitle, s as openRuns, t as FillRefused, u as loadWorkflows, v as branchState, w as githubApp, x as pushBundle, y as githubRepo } from "./steps-FNDWY1P_.js";
3
+ import { C as begin, D as reset, E as readGuard, O as retryAt, S as STEADY_AFTER, T as guardPath, b as RESTART_LIMIT, c as chooseModule, d as invokedAs, f as launchGuard, k as steady, l as defaultModule, m as loadsModule, p as loadBoard, s as SERVE_SPEC, t as DAEMON_SPEC, u as endLaunch, v as refusal, w as ended, x as RESTART_WINDOW, y as self } from "./module-D9KdbEpS.js";
4
4
  import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
5
5
  import { homedir, tmpdir } from "node:os";
6
6
  import { basename, dirname, join, resolve } from "node:path";
@@ -10,6 +10,90 @@ import { createServer } from "node:http";
10
10
  import { fileURLToPath } from "node:url";
11
11
  import { createInterface } from "node:readline";
12
12
 
13
+ //#region src/cli/update.ts
14
+ /**
15
+ * Says when a newer muster is out, for whoever asked to be told: off unless `MUSTER_UPDATE_CHECK=1`.
16
+ * muster makes no request of its own otherwise. Asked for, it asks npm's registry (or the one
17
+ * `npm_config_registry` names) for the version tagged latest, at most once a day, from a process of
18
+ * its own that no command waits for, and sends nothing but that request. What it learned is kept in
19
+ * the config folder, and the next command in a terminal says so in one line on stderr.
20
+ */
21
+ const PACKAGE = "@openmuster/muster";
22
+ /** A release number and nothing else: what the registry or the kept file says is printed only if it is one. */
23
+ const RELEASE = /^\d{1,6}\.\d{1,6}\.\d{1,6}(-[0-9A-Za-z]{1,20}(\.[0-9A-Za-z]{1,20}){0,3})?$/;
24
+ const DAY = 1440 * 60 * 1e3;
25
+ /** Release numbers in order: 0.3.1-alpha.2 < 0.3.1-alpha.10 < 0.3.1-beta.1 < 0.3.1. Negative when a is older. */
26
+ function compareVersions(a, b) {
27
+ const split = (version) => {
28
+ const [core, pre] = version.split(/-(.*)/s, 2);
29
+ return {
30
+ core: core.split(".").map(Number),
31
+ pre: pre === void 0 ? null : pre.split(".")
32
+ };
33
+ };
34
+ const x = split(a);
35
+ const y = split(b);
36
+ for (let i = 0; i < 3; i++) if ((x.core[i] ?? 0) !== (y.core[i] ?? 0)) return (x.core[i] ?? 0) - (y.core[i] ?? 0);
37
+ if (x.pre === null || y.pre === null) return x.pre === y.pre ? 0 : x.pre === null ? 1 : -1;
38
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
39
+ const p = x.pre[i];
40
+ const q = y.pre[i];
41
+ if (p === void 0 || q === void 0) return p === void 0 ? -1 : 1;
42
+ if (p === q) continue;
43
+ return /^\d+$/.test(p) && /^\d+$/.test(q) ? Number(p) - Number(q) : p < q ? -1 : 1;
44
+ }
45
+ return 0;
46
+ }
47
+ const checkPath = (env) => join(env.MUSTER_CONFIG ?? join(env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "muster"), "update-check.json");
48
+ const registryOf = (env) => (env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
49
+ /** Whether to say anything, and whether to ask again: only for someone who opted in, at a terminal. */
50
+ function updateNotice(input) {
51
+ const { version, env, tty, json, now, checked } = input;
52
+ if (env.MUSTER_UPDATE_CHECK !== "1" || !tty || json || env.CI || version === "0.0.0") return {
53
+ notice: null,
54
+ ask: false
55
+ };
56
+ const newer = typeof checked?.latest === "string" && RELEASE.test(checked.latest) && compareVersions(checked.latest, version) > 0 ? checked.latest : null;
57
+ return {
58
+ notice: newer ? `muster ${newer} is out; this is ${version}. npm install -g ${PACKAGE}` : null,
59
+ ask: checked === null || !(now - checked.checked < DAY)
60
+ };
61
+ }
62
+ function readChecked(path) {
63
+ try {
64
+ const found = JSON.parse(readFileSync(path, "utf8"));
65
+ return typeof found.checked === "number" ? found : null;
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+ const ASK = `
71
+ const [path, url, before] = process.argv.slice(1)
72
+ const fs = require('node:fs')
73
+ const write = (latest) => { try { fs.mkdirSync(require('node:path').dirname(path), { recursive: true }); fs.writeFileSync(path, JSON.stringify({ checked: Date.now(), latest })) } catch {} }
74
+ fetch(url, { signal: AbortSignal.timeout(5000), headers: { accept: 'application/json' } })
75
+ .then((response) => (response.ok ? response.json() : null))
76
+ .then((tags) => write(tags && typeof tags.latest === 'string' ? tags.latest : before || null), () => write(before || null))
77
+ `;
78
+ /** Starts the check and leaves it: the command that started it ends when it would have. */
79
+ function ask(env, checked) {
80
+ const url = `${registryOf(env)}/-/package/${PACKAGE.replace("/", "%2f")}/dist-tags`;
81
+ try {
82
+ spawn(process.execPath, [
83
+ "-e",
84
+ ASK,
85
+ checkPath(env),
86
+ url,
87
+ checked?.latest ?? ""
88
+ ], {
89
+ detached: true,
90
+ stdio: "ignore",
91
+ env
92
+ }).unref();
93
+ } catch {}
94
+ }
95
+
96
+ //#endregion
13
97
  //#region src/cli/format.ts
14
98
  /** How long ago, or how long until, in a word: `11s`, `5m`, `3h`, `2d`. */
15
99
  function span(ms) {
@@ -89,6 +173,36 @@ function eventLine(event, now) {
89
173
  else if (event.type === "task.failed" || event.type === "task.blocked") detail = firstLine([data.kind, data.reason].filter(Boolean).join(": "), 70);
90
174
  return detail ? `${head}\n${indent(detail)}` : head;
91
175
  }
176
+ /**
177
+ * A report as columns: one table by agent and, when any task had one, one by workflow. A cost is shown
178
+ * only where an agent reported one; a task no agent was recorded for is `(none)`. A long name is never
179
+ * cut, so two names alike are two rows: its row runs wider instead.
180
+ */
181
+ function reportText(report) {
182
+ const day = report.since.slice(0, 10);
183
+ const where = report.channel === null ? "" : ` in #${report.channel}`;
184
+ if (report.agents.length === 0) return `no tasks${where} since ${day}`;
185
+ const usd = (n) => n === null ? "-" : `$${n.toFixed(2)}`;
186
+ const head = (first) => `${first.padEnd(10)} tasks 1st round rounds failed failing input cost per task`;
187
+ const row = (r) => [
188
+ (r.key ?? "(none)").padEnd(10),
189
+ String(r.tasks).padStart(5),
190
+ `${r.firstRound} ${Math.round(100 * r.firstRound / r.tasks)}%`.padStart(9),
191
+ r.rounds.toFixed(2).padStart(6),
192
+ String(r.failed).padStart(6),
193
+ String(r.failing).padStart(7),
194
+ String(r.needsInput).padStart(5),
195
+ (r.costed ? usd(r.cost) : "-").padEnd(8),
196
+ r.costed ? usd(r.perTask) : "-"
197
+ ].join(" ");
198
+ const lines = [
199
+ `since ${day}${where}`,
200
+ head("agent"),
201
+ ...report.agents.map(row)
202
+ ];
203
+ if (report.workflows.length) lines.push(head("workflow"), ...report.workflows.map(row));
204
+ return lines.join("\n");
205
+ }
92
206
 
93
207
  //#endregion
94
208
  //#region src/daemon/daemon.ts
@@ -176,6 +290,7 @@ async function runDaemon(options) {
176
290
  for (const id$1 of did.schedules.canceled) options.log(`canceled schedule ${id$1} its token was revoked`);
177
291
  if (did.workflows?.started.length) options.log(`started workflow ${did.workflows.started.join(" ")}`);
178
292
  if (did.workflows?.refused.length) options.log(`refused workflow ${did.workflows.refused.join(" ")}`);
293
+ if (did.workflows?.suggested?.length) options.log(`suggested workflow ${did.workflows.suggested.join(" ")}`);
179
294
  if (did.workflows?.reported?.length) options.log(`reported workflow ${did.workflows.reported.join(" ")}`);
180
295
  if (did.workflows?.updated?.length) options.log(`updated workflow ${did.workflows.updated.join(" ")}`);
181
296
  if (did.workflows?.why) options.log(`failed workflow ${did.workflows.why}`);
@@ -658,6 +773,8 @@ tasks
658
773
  tasks needs <id> <id>... | --none
659
774
  budget [<channel> <usd> | <channel> --none]
660
775
  what a channel's tasks may cost in all
776
+ report [<channel>] [--since 30d]
777
+ how tasks went and cost, by agent and workflow
661
778
  workflow list what this machine's workflows.json registers
662
779
  workflow run <name> --on <id> [--arg k=v]...
663
780
  ask for one to be run on a thread
@@ -670,6 +787,7 @@ agents
670
787
  --agent claude|codex (or a command after --) [--cwd <dir>]
671
788
  [--worktree <repo> --branch <name>] [--model <m>] [--timeout 30m]
672
789
  [--env K=V]... [--bypass-permissions] [--loop] [--budget <usd>]
790
+ [--estimate] say what the ready tasks may cost; start none
673
791
  An agent that worked the task before resumes its session; --fresh won't.
674
792
  To pick one up by its ID: --resume <session>.
675
793
  Claude Code starts lean (a shell and files); --full loads your whole setup.
@@ -678,6 +796,7 @@ agents
678
796
  [--safe] keep the agent's permission prompts on there
679
797
  [--detach] return once started, not when it ends
680
798
  [--no-install] with --repo: don't install its dependencies
799
+ [--template <name>] e2b: in place of MUSTER_E2B_TEMPLATE
681
800
  [--push] push what it changed and open a pull request
682
801
  The agent is told where its task is, not what it says.
683
802
  It settles the task itself; one left unsettled is failed or released.
@@ -725,6 +844,9 @@ serve
725
844
  token list | token revoke <id>
726
845
  token exchange [-] a CI job's own OIDC token for a board token:
727
846
  on stdin with -, or in MUSTER_OIDC_TOKEN
847
+ token rotate-key sign new tokens with a new key; tokens the
848
+ old one signed still work
849
+ token drop-old-keys stop every token an old key signed
728
850
  join <board url> --as <name> ask a served board for a token, and wait
729
851
  [--note <text>] [--timeout 10m]
730
852
  join list | join deny <code>
@@ -734,7 +856,8 @@ serve
734
856
  MUSTER_INSECURE_HTTP=1: for a network that is private some other way.
735
857
 
736
858
  states: waiting, ready, claimed, blocked, completed, failed, canceled
737
- exit: 0 ok, 1 failed or timed out, 2 misuse, 130 interrupted, 143 terminated`;
859
+ exit: 0 ok, 1 failed or timed out, 2 misuse, 130 interrupted, 143 terminated
860
+ update: MUSTER_UPDATE_CHECK=1 says, once a day, when a newer muster is out`;
738
861
  const GLOBAL_LINE = "global: [--as <profile>] [--board <name>] [--dir <path>] [--url <board url>] [--json]";
739
862
  /**
740
863
  * One command's part of the help: its lines as the whole help has them, under the section they are in,
@@ -860,6 +983,7 @@ function inspect(options) {
860
983
  if (req.method !== "POST") throw new Failure("not_found", "No such route.");
861
984
  if (req.headers.origin !== origin) throw new Failure("forbidden", "Writes come from the inspector page.");
862
985
  const route = url.pathname.slice(7);
986
+ if (route === "whoami") return send(res, 200, { ok: actorId(await options.backend.self(null)) });
863
987
  const answering = route === "joinList" || route === "joinApprove" || route === "joinDeny";
864
988
  if (!ALLOWED.has(route) && !answering) throw new Failure("not_found", "No such route.");
865
989
  const chunks = [];
@@ -1100,6 +1224,42 @@ async function checkWatcher(run, parsed, mode, guardAt) {
1100
1224
  }
1101
1225
  }
1102
1226
  const stopCode = (signal) => signal.reason === "SIGTERM" ? 143 : 130;
1227
+ /**
1228
+ * Rides out a board that is out of reach for now, for a command that waits: a gateway's 502 or a dropped
1229
+ * connection isn't an answer, so the poll goes again after a pause that doubles, as the daemon's does.
1230
+ * Only once the command has reached the board (`ok`): a board out of reach from the start is said at
1231
+ * once, as any command says it. `failed` rethrows what isn't an outage, and an outage whose next try
1232
+ * would come after the deadline, so the command says what went wrong rather than that nothing came.
1233
+ * With no deadline it waits for as long as the command runs. A stop ends the pause at once, and
1234
+ * `failed` returns: the caller checks the stop and exits as stopped.
1235
+ */
1236
+ /**
1237
+ * Refuses a cursor past the board's last event: one this board never gave out, most likely because it was
1238
+ * restored from a backup since. Read on from it, and everything written until the board caught up would be
1239
+ * skipped without a word.
1240
+ */
1241
+ async function notAhead(team, after) {
1242
+ const head = await team.head();
1243
+ if (after > head) throw cursorAhead(after, head);
1244
+ }
1245
+ function outages(run, deadline) {
1246
+ let failing = 0;
1247
+ let reached = false;
1248
+ return {
1249
+ ok() {
1250
+ reached = true;
1251
+ failing = 0;
1252
+ },
1253
+ async failed(error$1) {
1254
+ if (run.io.stop.aborted) return;
1255
+ if (!reached || !(error$1 instanceof Failure) || !UNREACHABLE.has(error$1.reason)) throw error$1;
1256
+ const pause = Math.min(FAILING_PAUSE, 500 * 2 ** failing++);
1257
+ if (deadline !== void 0 && Date.now() + pause >= deadline) throw error$1;
1258
+ if (!run.json && (failing & failing - 1) === 0) run.io.err(`error ${error$1.message} Trying again.${failing > 1 ? ` (${failing} tries in a row)` : ""}`);
1259
+ await sleep(pause, run.io.stop);
1260
+ }
1261
+ };
1262
+ }
1103
1263
  /** An argument as a shell takes it, quoted only when it has to be. */
1104
1264
  const shell = (arg) => /^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", `'\\''`)}'`;
1105
1265
  function textOf(parsed, at, io) {
@@ -1337,13 +1497,24 @@ const commands = {
1337
1497
  if (limit !== void 0 && !/^[1-9][0-9]*$/.test(limit)) throw misuse("invalid_limit", "--limit takes a whole number of at least 1.");
1338
1498
  const deadline = wait === void 0 ? 0 : Date.now() + duration(wait, "wait") * 1e3;
1339
1499
  let after = await run.team.cursorGet("inbox") ?? 0;
1500
+ const outage = wait === void 0 ? null : outages(run, deadline);
1501
+ outage?.ok();
1340
1502
  let pause = 100;
1341
1503
  for (;;) {
1342
- const page = await run.team.events({
1343
- after,
1344
- filter: { for: mine },
1345
- limit: limit === void 0 ? 50 : Number(limit)
1346
- });
1504
+ let page;
1505
+ try {
1506
+ page = await run.team.events({
1507
+ after,
1508
+ filter: { for: mine },
1509
+ limit: limit === void 0 ? 50 : Number(limit)
1510
+ });
1511
+ outage?.ok();
1512
+ } catch (error$1) {
1513
+ if (outage === null) throw error$1;
1514
+ await outage.failed(error$1);
1515
+ if (run.io.stop.aborted) return stopCode(run.io.stop);
1516
+ continue;
1517
+ }
1347
1518
  after = page.cursor;
1348
1519
  if (page.events.length > 0 || Date.now() >= deadline || run.io.stop.aborted) {
1349
1520
  if (!peek) await run.team.cursorSet("inbox", page.cursor);
@@ -1460,7 +1631,7 @@ const commands = {
1460
1631
  const verb = parsed.positionals[0];
1461
1632
  if (verb === "list") {
1462
1633
  const workflows = loadWorkflows();
1463
- return print(run, { workflows }, () => workflows.length === 0 ? `no workflows in ${workflowsPath()}` : workflows.map((workflow) => `${workflow.name.padEnd(20)} ${workflow.description} who: ${workflow.who.join(", ")} channels: ${workflow.channels.join(", ")}`).join("\n"));
1634
+ return print(run, { workflows }, () => workflows.length === 0 ? `no workflows in ${workflowsPath()}` : workflows.map((workflow) => `${workflow.name.padEnd(20)} ${workflow.description} who: ${workflow.who.join(", ")} channels: ${workflow.channels.join(", ")}${workflow.mode === "suggest" ? " suggest only" : ""}`).join("\n"));
1464
1635
  }
1465
1636
  if (verb === "run") {
1466
1637
  const name = parsed.positionals[1];
@@ -1551,6 +1722,18 @@ const commands = {
1551
1722
  print(run, set, () => set.usd === null ? `no budget #${set.channel}` : `budget #${set.channel} $${set.spent.toFixed(2)} of $${set.usd.toFixed(2)}`);
1552
1723
  }
1553
1724
  },
1725
+ report: {
1726
+ spec: { value: ["since"] },
1727
+ async run(run, parsed) {
1728
+ const channel = parsed.positionals[0];
1729
+ const since = (/* @__PURE__ */ new Date(Date.now() - duration(str(parsed.flags, "since") ?? "30d", "since") * 1e3)).toISOString();
1730
+ const found = await run.team.taskReport({
1731
+ ...channel !== void 0 ? { channel } : {},
1732
+ since
1733
+ });
1734
+ print(run, found, () => reportText(found));
1735
+ }
1736
+ },
1554
1737
  schemas: {
1555
1738
  spec: { value: ["file"] },
1556
1739
  async run(run, parsed) {
@@ -1636,16 +1819,29 @@ const commands = {
1636
1819
  async run(run, parsed) {
1637
1820
  const filter = filterOf(parsed, 0);
1638
1821
  const given = str(parsed.flags, "after");
1639
- let after = given !== void 0 ? cursor(given, "after") : await run.team.head();
1640
1822
  const timeout = duration(str(parsed.flags, "timeout") ?? "30m", "timeout") * 1e3;
1641
1823
  const deadline = Date.now() + timeout;
1824
+ const outage = outages(run, deadline);
1825
+ let after = given !== void 0 ? cursor(given, "after") : await run.team.head();
1826
+ if (given === void 0) outage.ok();
1827
+ let checked = false;
1642
1828
  let pause = 100;
1643
1829
  for (;;) {
1644
- const page = await run.team.events({
1645
- after,
1646
- filter,
1647
- limit: 1
1648
- });
1830
+ let page;
1831
+ try {
1832
+ if (given !== void 0 && !checked) await notAhead(run.team, after);
1833
+ checked = true;
1834
+ page = await run.team.events({
1835
+ after,
1836
+ filter,
1837
+ limit: 1
1838
+ });
1839
+ outage.ok();
1840
+ } catch (error$1) {
1841
+ await outage.failed(error$1);
1842
+ if (run.io.stop.aborted) return stopCode(run.io.stop);
1843
+ continue;
1844
+ }
1649
1845
  after = page.cursor;
1650
1846
  const event = page.events[0];
1651
1847
  if (event) {
@@ -1684,12 +1880,24 @@ const commands = {
1684
1880
  });
1685
1881
  for (const event of all.events.slice(-count)) run.io.out(run.json ? JSON.stringify(event) : eventLine(event, run.now()));
1686
1882
  }
1883
+ const outage = outages(run);
1884
+ if (given === void 0) outage.ok();
1885
+ let checked = false;
1687
1886
  let pause = 100;
1688
1887
  while (!run.io.stop.aborted) {
1689
- const page = await run.team.events({
1690
- after,
1691
- filter
1692
- });
1888
+ let page;
1889
+ try {
1890
+ if (given !== void 0 && !checked) await notAhead(run.team, after);
1891
+ checked = true;
1892
+ page = await run.team.events({
1893
+ after,
1894
+ filter
1895
+ });
1896
+ outage.ok();
1897
+ } catch (error$1) {
1898
+ await outage.failed(error$1);
1899
+ continue;
1900
+ }
1693
1901
  after = page.cursor;
1694
1902
  for (const event of page.events) run.io.out(run.json ? JSON.stringify(event) : eventLine(event, run.now()));
1695
1903
  pause = page.events.length ? 100 : Math.min(pause * 2, 1e3);
@@ -1749,7 +1957,8 @@ const commands = {
1749
1957
  "budget",
1750
1958
  "runner",
1751
1959
  "repo",
1752
- "by"
1960
+ "by",
1961
+ "template"
1753
1962
  ],
1754
1963
  many: [
1755
1964
  "label",
@@ -1764,11 +1973,24 @@ const commands = {
1764
1973
  "full",
1765
1974
  "detach",
1766
1975
  "no-install",
1767
- "push"
1976
+ "push",
1977
+ "estimate"
1768
1978
  ]
1769
1979
  },
1770
1980
  async run(run, parsed) {
1771
1981
  refuseByWithoutReady(parsed);
1982
+ if (on(parsed.flags, "estimate")) {
1983
+ if (str(parsed.flags, "ready") === void 0) throw misuse("nothing_to_claim", "--estimate says what the ready tasks may cost: pass --ready <channel>.");
1984
+ const found = await estimate(run, parsed);
1985
+ return print(run, found, () => estimateLine(found));
1986
+ }
1987
+ if (on(parsed.flags, "loop") && str(parsed.flags, "ready") !== void 0 && !run.json) {
1988
+ const found = await estimate(run, parsed).catch((error$1) => {
1989
+ if (error$1 instanceof Failure && error$1.exit === 2) throw error$1;
1990
+ return null;
1991
+ });
1992
+ if (found) run.io.out(estimateLine(found));
1993
+ }
1772
1994
  if (!on(parsed.flags, "loop")) return runAgent(run, parsed);
1773
1995
  if (str(parsed.flags, "ready") === void 0) throw misuse("nothing_to_claim", "--loop takes the next ready task each time: pass --ready <channel>.");
1774
1996
  const runner = str(parsed.flags, "runner");
@@ -1990,7 +2212,17 @@ const commands = {
1990
2212
  }, () => made$1.token);
1991
2213
  return;
1992
2214
  }
1993
- if (verb !== "create") throw misuse("unknown_command", "Use: mu token create [--as <profile>] --can <channel>=<permissions>... | --all [--ttl 30d], mu token list, mu token revoke <id>, or mu token exchange.");
2215
+ if (verb === "rotate-key" || verb === "drop-old-keys") {
2216
+ const me$1 = await run.team.whoami();
2217
+ if (me$1.mode !== "file") throw new Failure("forbidden", `mu token ${verb} changes the keys of a board on this machine.`);
2218
+ if (verb === "rotate-key") {
2219
+ const done$1 = rotateKey(me$1.where, new Date(run.now()));
2220
+ return print(run, done$1, () => `rotated new tokens are signed with a new key; ${done$1.retired} old ${done$1.retired === 1 ? "key keeps its" : "keys keep their"} tokens good. Restart mu serve to use it.\nnext: mu token drop-old-keys, to stop every token an old key signed`);
2221
+ }
2222
+ const done = dropRetiredKeys(me$1.where);
2223
+ return print(run, done, () => `dropped ${done.dropped} old ${done.dropped === 1 ? "key" : "keys"}: every token ${done.dropped === 1 ? "it" : "they"} signed stops once mu serve restarts`);
2224
+ }
2225
+ if (verb !== "create") throw misuse("unknown_command", "Use: mu token create [--as <profile>] --can <channel>=<permissions>... | --all [--ttl 30d], mu token list, mu token revoke <id>, mu token exchange, mu token rotate-key, or mu token drop-old-keys.");
1994
2226
  const can = {};
1995
2227
  for (const [pattern, permissions] of Object.entries(pairs(list(parsed.flags, "can"), "can"))) can[pattern] = permissions.split(",").filter(Boolean);
1996
2228
  const all = on(parsed.flags, "all");
@@ -2119,6 +2351,7 @@ const commands = {
2119
2351
  serving = await listen({
2120
2352
  backend: run.team.backend,
2121
2353
  key: key$1,
2354
+ retired: retiredKeys(me.where),
2122
2355
  port,
2123
2356
  host,
2124
2357
  hosts: allowed,
@@ -2426,6 +2659,60 @@ const TASK_VERBS = [
2426
2659
  "needs",
2427
2660
  "run"
2428
2661
  ];
2662
+ /**
2663
+ * The flags each verb takes. `tasks` parses the flags of all of them, so without this a flag only another
2664
+ * verb reads was taken and dropped: `tasks complete 5 --file report.md` completed with no result.
2665
+ */
2666
+ const CLAIM_FLAGS = [
2667
+ "ready",
2668
+ "label",
2669
+ "from",
2670
+ "by",
2671
+ "lease",
2672
+ "wait"
2673
+ ];
2674
+ const TASK_FLAGS = {
2675
+ list: [
2676
+ "state",
2677
+ "limit",
2678
+ "label",
2679
+ "latest"
2680
+ ],
2681
+ create: [
2682
+ "label",
2683
+ "needs",
2684
+ "for",
2685
+ "claim",
2686
+ "lease",
2687
+ "hold",
2688
+ "reason",
2689
+ "file",
2690
+ "idempotency-key",
2691
+ "no-sync"
2692
+ ],
2693
+ claim: CLAIM_FLAGS,
2694
+ renew: ["lease"],
2695
+ release: [],
2696
+ complete: ["result"],
2697
+ fail: ["reason", "no-count"],
2698
+ block: ["reason", "kind"],
2699
+ unblock: [],
2700
+ reopen: ["round"],
2701
+ cancel: [],
2702
+ assign: ["for", "pool"],
2703
+ needs: ["none"],
2704
+ run: [...CLAIM_FLAGS, "result"]
2705
+ };
2706
+ function refuseOtherVerbsFlags(verb, flags) {
2707
+ const takes = TASK_FLAGS[verb];
2708
+ const global = new Set([...GLOBAL.value, ...GLOBAL.bool]);
2709
+ const other = Object.keys(flags).find((name) => !global.has(name) && !takes.includes(name));
2710
+ if (other === void 0) return;
2711
+ const command = verb === "list" ? "mu tasks" : `mu tasks ${verb}`;
2712
+ const what = takes.length ? `${command} takes ${takes.map((name) => `--${name}`).join(", ")}.` : `${command} takes no flags of its own.`;
2713
+ const report = (verb === "complete" || verb === "fail" || verb === "block") && other === "file" ? " A long report goes in a reply: mu reply <thread> --file <path>." : "";
2714
+ throw misuse("unknown_flag", `--${other} isn't a flag of ${command}.`, what + report);
2715
+ }
2429
2716
  const lease = (flags) => {
2430
2717
  const value = str(flags, "lease");
2431
2718
  return value === void 0 ? {} : { lease: duration(value, "lease") };
@@ -2469,6 +2756,8 @@ async function claimWith(run, parsed, target, me, pid) {
2469
2756
  };
2470
2757
  const wait = str(parsed.flags, "wait");
2471
2758
  const deadline = wait === void 0 ? 0 : Date.now() + duration(wait, "wait") * 1e3;
2759
+ const outage = ready !== void 0 && wait !== void 0 ? outages(run, deadline) : null;
2760
+ outage?.ok();
2472
2761
  let pause = 100;
2473
2762
  for (;;) try {
2474
2763
  const claimed = await run.team.taskClaim(request);
@@ -2478,6 +2767,11 @@ async function claimWith(run, parsed, target, me, pid) {
2478
2767
  });
2479
2768
  return claimed;
2480
2769
  } catch (error$1) {
2770
+ if (outage !== null && error$1 instanceof Failure && UNREACHABLE.has(error$1.reason)) {
2771
+ await outage.failed(error$1);
2772
+ if (run.io.stop.aborted) throw error$1;
2773
+ continue;
2774
+ }
2481
2775
  if (!(error$1 instanceof Failure) || error$1.reason !== "nothing_ready" || ready === void 0 || wait === void 0) throw error$1;
2482
2776
  if (run.io.stop.aborted) throw error$1;
2483
2777
  if (Date.now() >= deadline) throw new Failure("timeout", `Nothing was ready in ${ready} within ${wait}.`, { hint: "That isn't a failure of the work: there is nothing to take." });
@@ -2488,6 +2782,7 @@ async function claimWith(run, parsed, target, me, pid) {
2488
2782
  async function tasks(run, parsed) {
2489
2783
  const verb = parsed.positionals[0];
2490
2784
  const now = () => run.now();
2785
+ refuseOtherVerbsFlags(verb !== void 0 && TASK_VERBS.includes(verb) ? verb : "list", parsed.flags);
2491
2786
  if (verb === void 0 || !TASK_VERBS.includes(verb)) {
2492
2787
  const state = str(parsed.flags, "state");
2493
2788
  const labels = list(parsed.flags, "label");
@@ -2882,6 +3177,51 @@ async function filled(run, task, owner, token, team = run.team) {
2882
3177
  return reason;
2883
3178
  }
2884
3179
  }
3180
+ /** How far back an estimate looks for what a task cost. */
3181
+ const ESTIMATE_SINCE = "30d";
3182
+ /**
3183
+ * What a worker would start on, and what that may cost: the tasks ready in its channel that it may take
3184
+ * (its owners, `--by`, `--label`, assigned to it or to nobody), times what a task under that channel
3185
+ * cost this agent on average over the last 30 days. With no cost on record it says so, never a guess.
3186
+ */
3187
+ async function estimate(run, parsed) {
3188
+ const channel = str(parsed.flags, "ready");
3189
+ const me = await run.team.whoami();
3190
+ const owners = new Set([me.principal, ...list(parsed.flags, "from")]);
3191
+ const by = str(parsed.flags, "by");
3192
+ const labels = list(parsed.flags, "label");
3193
+ const found = await run.team.taskList({
3194
+ channel,
3195
+ state: "ready",
3196
+ limit: 1e3,
3197
+ ...labels.length ? { labels } : {}
3198
+ });
3199
+ const ready = found.tasks.filter((task) => owners.has(task.owner.principal) && (by === void 0 || actorId(task.owner) === by) && (task.for === null || task.for === me.profile)).length;
3200
+ const agent = str(parsed.flags, "agent") ?? (parsed.rest.length ? generic(parsed.rest[0], parsed.rest.slice(1)).name : null);
3201
+ const since = (/* @__PURE__ */ new Date(Date.now() - duration(ESTIMATE_SINCE, "since") * 1e3)).toISOString();
3202
+ const history = await run.team.taskReport({
3203
+ channel: channel.replace(/^#/, "").replace(/\/$/, ""),
3204
+ since
3205
+ });
3206
+ const rows = agent === null ? history.agents : history.agents.filter((row) => row.key === agent);
3207
+ const costed = rows.reduce((sum, row) => sum + row.costed, 0);
3208
+ const perTask = costed ? Math.round(rows.reduce((sum, row) => sum + row.cost, 0) / costed * 1e4) / 1e4 : null;
3209
+ return {
3210
+ channel,
3211
+ ready,
3212
+ more: found.more,
3213
+ agent,
3214
+ perTask,
3215
+ usd: perTask === null ? null : Math.round(perTask * ready * 100) / 100,
3216
+ since
3217
+ };
3218
+ }
3219
+ const estimateLine = (e) => {
3220
+ const ready = `${e.ready}${e.more ? "+" : ""} ready`;
3221
+ if (e.ready === 0) return `${ready} in #${e.channel.replace(/^#/, "")}`;
3222
+ if (e.perTask === null) return `${ready}, no cost history${e.agent ? ` for ${e.agent}` : ""} in #${e.channel.replace(/^#/, "")}`;
3223
+ return `${ready}, about $${e.usd.toFixed(2)} at $${e.perTask.toFixed(2)} a task`;
3224
+ };
2885
3225
  /** What the board says when it couldn't answer, rather than answering no: a task claimed meanwhile is given back, not failed. */
2886
3226
  const RELEASE_ON = new Set([
2887
3227
  "network_error",
@@ -2899,10 +3239,11 @@ async function runAgent(run, parsed, onKind, onCost) {
2899
3239
  if (where !== "local") return runInCloud(run, parsed, where, agent);
2900
3240
  const cloudOnly = [
2901
3241
  "repo",
3242
+ "template",
2902
3243
  "push",
2903
3244
  "detach",
2904
3245
  "no-install"
2905
- ].find((flag) => flag === "repo" ? str(parsed.flags, flag) !== void 0 : on(parsed.flags, flag));
3246
+ ].find((flag) => flag === "repo" || flag === "template" ? str(parsed.flags, flag) !== void 0 : on(parsed.flags, flag));
2906
3247
  if (cloudOnly) throw misuse(cloudOnly === "push" ? "push_unsupported" : "unknown_flag", `--${cloudOnly} is for a cloud runner, and this run is on this machine.`, "Add --runner vercel, --runner cloudflare or --runner e2b, or leave it out.");
2907
3248
  const me = await run.team.whoami();
2908
3249
  const cwd = resolve(str(parsed.flags, "cwd") ?? process.cwd());
@@ -3075,6 +3416,20 @@ function repoUrl(value) {
3075
3416
  * itself, through the board at MUSTER_URL, which the sandbox must be able to reach.
3076
3417
  */
3077
3418
  async function runInCloud(run, parsed, where, agent) {
3419
+ const template = str(parsed.flags, "template");
3420
+ if (template !== void 0) {
3421
+ if (where !== "e2b") throw misuse("unknown_flag", `--template names an E2B template, and this run is on ${where}.`, "Use it with --runner e2b, or leave it out.");
3422
+ run = {
3423
+ ...run,
3424
+ io: {
3425
+ ...run.io,
3426
+ env: {
3427
+ ...run.io.env,
3428
+ MUSTER_E2B_TEMPLATE: template
3429
+ }
3430
+ }
3431
+ };
3432
+ }
3078
3433
  if (str(parsed.flags, "ready") !== void 0 && on(parsed.flags, "loop")) return cloudWorker(run, parsed, where, agent);
3079
3434
  return cloudTask(run, parsed, where, agent);
3080
3435
  }
@@ -3731,12 +4086,28 @@ async function main(argv, io) {
3731
4086
  const command = commands[name];
3732
4087
  try {
3733
4088
  const parsed = parse(argv.slice(1), command.spec);
3734
- if (name === "daemon" && parsed.positionals[0] === "run" && !runsModule(parsed.flags, io.env)) return await counted(guardOf(parsed.flags, io.env).path, io, () => dispatch(name, command, parsed, io, json));
3735
- return await dispatch(name, command, parsed, io, json);
4089
+ const code = name === "daemon" && parsed.positionals[0] === "run" && !runsModule(parsed.flags, io.env) ? await counted(guardOf(parsed.flags, io.env).path, io, () => dispatch(name, command, parsed, io, json)) : await dispatch(name, command, parsed, io, json);
4090
+ newerRelease(io, json);
4091
+ return code;
3736
4092
  } catch (error$1) {
3737
4093
  return fail(io, json, error$1);
3738
4094
  }
3739
4095
  }
4096
+ /** For whoever opted in with MUSTER_UPDATE_CHECK=1: one line when a newer release is out (update.ts). */
4097
+ function newerRelease(io, json) {
4098
+ if (io.env.MUSTER_UPDATE_CHECK !== "1") return;
4099
+ const checked = readChecked(checkPath(io.env));
4100
+ const { notice, ask: again } = updateNotice({
4101
+ version: VERSION,
4102
+ env: io.env,
4103
+ tty: io.tty === true,
4104
+ json,
4105
+ now: Date.now(),
4106
+ checked
4107
+ });
4108
+ if (notice) io.err(notice);
4109
+ if (again) ask(io.env, checked);
4110
+ }
3740
4111
  /** How often a stopped daemon reads its record again, to see whether it may start. */
3741
4112
  const GUARD_POLL = 2e3;
3742
4113
  /** Whether this command line runs a board module. A choice that is misuse is dispatch's to say. */
@@ -0,0 +1,6 @@
1
+ import { D as VERSION } from "./args-CaFBa2IP.js";
2
+ import "./steps-FNDWY1P_.js";
3
+ import { a as main, i as attend, n as agentPrompt, o as meantCommand, r as agentToken, s as repoUrl, t as SPECS } from "./main-BeEB08iI.js";
4
+ import "./module-D9KdbEpS.js";
5
+
6
+ export { SPECS, VERSION, agentPrompt, agentToken, attend, main, meantCommand, repoUrl };
@@ -0,0 +1,6 @@
1
+ import "./args-CaFBa2IP.js";
2
+ import "./steps-FNDWY1P_.js";
3
+ import { c as answer, l as mcp, u as refusal } from "./main-BeEB08iI.js";
4
+ import "./module-D9KdbEpS.js";
5
+
6
+ export { answer, mcp, refusal };
@@ -1,4 +1,4 @@
1
- import "./args-DX9QSK1f.js";
2
- import { _ as prepare, a as REEXEC_DEPTH, c as chooseModule, d as invokedAs, f as launchGuard, g as plan, h as musterFor, i as REEXEC, l as defaultModule, m as loadsModule, n as LAUNCH, o as REEXEC_FROM, p as loadBoard, r as MODULE_PROTOCOL, s as SERVE_SPEC, t as DAEMON_SPEC, u as endLaunch, v as refusal, y as self } from "./module-CxoN1MOe.js";
1
+ import "./args-CaFBa2IP.js";
2
+ import { _ as prepare, a as REEXEC_DEPTH, c as chooseModule, d as invokedAs, f as launchGuard, g as plan, h as musterFor, i as REEXEC, l as defaultModule, m as loadsModule, n as LAUNCH, o as REEXEC_FROM, p as loadBoard, r as MODULE_PROTOCOL, s as SERVE_SPEC, t as DAEMON_SPEC, u as endLaunch, v as refusal, y as self } from "./module-D9KdbEpS.js";
3
3
 
4
4
  export { DAEMON_SPEC, LAUNCH, MODULE_PROTOCOL, REEXEC, REEXEC_DEPTH, REEXEC_FROM, SERVE_SPEC, chooseModule, defaultModule, endLaunch, invokedAs, launchGuard, loadBoard, loadsModule, musterFor, plan, prepare, refusal, self };
@@ -1,4 +1,4 @@
1
- import { E as VERSION, P as configDir, it as misuse, l as COPY, rt as Failure, s as parse } from "./args-DX9QSK1f.js";
1
+ import { D as VERSION, R as configDir, c as parse, lt as misuse, st as Failure, u as COPY } from "./args-CaFBa2IP.js";
2
2
  import { registerHooks } from "node:module";
3
3
  import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { constants } from "node:os";