@openmuster/muster 0.3.1-alpha.6 → 0.3.1-alpha.7

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.
@@ -1,6 +1,6 @@
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 { B as isSessionId, C as branchState, E as openPullRequest, F as runLocal, H as conformance, I as AGENTS, M as installationToken, N as KEEP_LOGS_MS, O as pushBundle, S as BUNDLE_MAX, T as githubRepo, V as http, _ as e2b, a as imagePaths, b as vercel, c as pullTitle, f as openRuns, g as workflowsPath, h as loadWorkflows, i as fillResults, j as githubApp, l as pushesTask, m as spawnWorker, n as FillRefused, o as pullDescription, p as runWorkflows, r as descriptionFile, s as pullRefs, t as DESCRIPTION_READ_MAX, v as SANDBOX_ENV, w as commentOnPullRequest, x as BUNDLE, y as cloudflare, z as generic } from "./steps-cnWo2Wvx.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";
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, Q as processStart, R as configDir, S as isLoopback, V as keepClaim, _ as ping, a as list, c as parse, d as ROOT, dt as labelFilter, f as board, ft as profileName, g as armHooks, h as HOOKS_LEASE, ht as misuse, i as id, j as file, k as loadOidc, l as str, lt as fileName, m as DROPPED, mt as cursorAhead, n as cursor, nt as INVISIBLE, o as on, ot as actorId, p as syncLoop, pt as Failure, r as duration, s as pairs, t as GLOBAL, v as why, w as ROUTES, y as holdLease, z as dropClaim } from "./args-C_XaUVTS.js";
2
+ import { B as isSessionId, C as branchState, E as openPullRequest, F as runLocal, H as conformance, I as AGENTS, M as installationToken, N as KEEP_LOGS_MS, O as pushBundle, S as BUNDLE_MAX, T as githubRepo, V as http, _ as e2b, a as imagePaths, b as vercel, c as pullTitle, f as openRuns, g as workflowsPath, h as loadWorkflows, i as fillResults, j as githubApp, l as pushesTask, m as spawnWorker, n as FillRefused, o as pullDescription, p as runWorkflows, r as descriptionFile, s as pullRefs, t as DESCRIPTION_READ_MAX, v as SANDBOX_ENV, w as commentOnPullRequest, x as BUNDLE, y as cloudflare, z as generic } from "./steps-DVxqtI61.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-DkA_1NkG.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";
@@ -203,6 +203,23 @@ function reportText(report) {
203
203
  if (report.workflows.length) lines.push(head("workflow"), ...report.workflows.map(row));
204
204
  return lines.join("\n");
205
205
  }
206
+ /**
207
+ * Text for a terminal. What boards and platforms say can carry control characters, ESC among them, which
208
+ * starts the sequences that clear the screen, move the cursor or retitle the window: each but tab and newline
209
+ * shows as its picture (\u241b for ESC), a C1 control as \ufffd, and a Windows line end as a newline. `--json`
210
+ * prints what the board said, as it said it. Follows `terminalText` in @vercel/board's `cli/format.ts`
211
+ * (Apache-2.0, Copyright Vercel, Inc.).
212
+ */
213
+ const terminalText = (text) => text.replace(/\r\n/g, "\n").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, (char) => {
214
+ const code = char.charCodeAt(0);
215
+ return code < 32 ? String.fromCharCode(9216 + code) : code === 127 ? "␡" : "�";
216
+ });
217
+ /**
218
+ * JSON for a terminal: `JSON.stringify` escapes C0 controls but writes DEL and C1 (CSI among them) as they are.
219
+ * Each is written as its `\\u` escape, which a JSON string reads back as the same character; outside a string,
220
+ * where valid JSON holds none, it shows as text.
221
+ */
222
+ const jsonText = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
206
223
 
207
224
  //#endregion
208
225
  //#region src/daemon/daemon.ts
@@ -211,7 +228,7 @@ function reportText(report) {
211
228
  * and its lease, and `mu daemon check` takes a watcher or a hook by name: one name is one thing.
212
229
  */
213
230
  function clashWithWorkflows(code, workflows) {
214
- for (const [mine, names] of [["watcher", code.names], ["hook", code.hooks ?? []]]) for (const name of names) if (workflows.some((workflow) => workflow.name === name)) return new Failure("invalid_config", `A ${mine} in ${code.path} and a workflow in ${workflowsPath()} are both named "${name}".`, { hint: "Rename one: a name is one watcher, hook or workflow." });
231
+ for (const [mine$1, names] of [["watcher", code.names], ["hook", code.hooks ?? []]]) for (const name of names) if (workflows.some((workflow) => workflow.name === name)) return new Failure("invalid_config", `A ${mine$1} in ${code.path} and a workflow in ${workflowsPath()} are both named "${name}".`, { hint: "Rename one: a name is one watcher, hook or workflow." });
215
232
  return null;
216
233
  }
217
234
  /** The registered workflows the daemon starts, refused when one is named like something the module declares. */
@@ -250,7 +267,7 @@ async function runDaemon(options) {
250
267
  runs: openRuns()
251
268
  }
252
269
  } : void 0;
253
- const sleep$1 = options.sleep ?? ((ms) => new Promise((resolve$1) => {
270
+ const sleep$2 = options.sleep ?? ((ms) => new Promise((resolve$1) => {
254
271
  const timer = setTimeout(done, ms);
255
272
  function done() {
256
273
  clearTimeout(timer);
@@ -261,7 +278,7 @@ async function runDaemon(options) {
261
278
  }));
262
279
  const lease$1 = await holdLease(leases, "tick", {
263
280
  ...options.lease,
264
- sleep: sleep$1,
281
+ sleep: sleep$2,
265
282
  stop: options.stop
266
283
  });
267
284
  if (!lease$1) return options.stop.aborted ? "stopped" : "held";
@@ -302,7 +319,7 @@ async function runDaemon(options) {
302
319
  said = message;
303
320
  }
304
321
  const interval = options.interval ?? 1e3;
305
- await sleep$1(failing ? Math.min(FAILING_PAUSE, Math.max(interval, interval * 2 ** failing)) : interval);
322
+ await sleep$2(failing ? Math.min(FAILING_PAUSE, Math.max(interval, interval * 2 ** failing)) : interval);
306
323
  }
307
324
  return "stopped";
308
325
  } finally {
@@ -439,6 +456,557 @@ function checkWrite(watcher, options = {}) {
439
456
  };
440
457
  }
441
458
 
459
+ //#endregion
460
+ //#region src/cli/mcp-events.ts
461
+ /**
462
+ * The MCP Events extension (`io.modelcontextprotocol/events`, SEP-3415) over the board's log.
463
+ *
464
+ * Every change on a board is already one event in one ordered log, with its place as a cursor, so the extension
465
+ * is a view of what `mu tail` and `mu wait` read: the same filters, through the same handle, under the same
466
+ * token. A client polls (`events/poll`) or keeps a stream open (`events/stream`). Webhook delivery is not
467
+ * offered: the board's own outgoing webhooks, declared in a board module, do that job.
468
+ */
469
+ const EXT_EVENTS = "io.modelcontextprotocol/events";
470
+ /** Error codes the extension defines. */
471
+ const EventError = {
472
+ NotFound: -32023,
473
+ Forbidden: -32024,
474
+ ResourceExhausted: -32025,
475
+ InvalidParams: -32602,
476
+ Internal: -32603
477
+ };
478
+ /** Thrown for a request the extension refuses, with its code. */
479
+ var EventsRefusal = class extends Error {
480
+ code;
481
+ constructor(code, message) {
482
+ super(message);
483
+ this.code = code;
484
+ }
485
+ };
486
+ const FILTERS = {
487
+ channel: {
488
+ type: "string",
489
+ description: "A channel, or every channel under one when it ends in \"/\" (db/)."
490
+ },
491
+ re: {
492
+ type: "integer",
493
+ minimum: 1,
494
+ description: "One thread, by the ID of its first message."
495
+ },
496
+ by: {
497
+ type: "string",
498
+ description: "Only what one actor did, by its ID as `mu actors` prints it."
499
+ },
500
+ mentions: {
501
+ type: "string",
502
+ description: "Only messages that mention this handle."
503
+ },
504
+ text: {
505
+ type: "string",
506
+ description: "Only messages whose text contains these words."
507
+ },
508
+ labels: {
509
+ type: "array",
510
+ items: { type: "string" },
511
+ description: "Labels the thread must have: a key, key=value, or key=a|b."
512
+ },
513
+ root: {
514
+ type: "boolean",
515
+ description: "Only what is about a thread's first message: replies are left out."
516
+ },
517
+ kinds: {
518
+ type: "array",
519
+ items: { type: "string" },
520
+ description: "For task.blocked: hold kinds to keep (needs_input), or to drop (!backlog)."
521
+ }
522
+ };
523
+ const PAYLOAD = {
524
+ type: "object",
525
+ description: "The board event as `mu tail --json` prints it: seq, at, type, by, channel, thread and data; a message event also has the message, a task event the task.",
526
+ properties: {
527
+ seq: { type: "integer" },
528
+ at: { type: "string" },
529
+ type: { type: "string" },
530
+ by: { type: "object" },
531
+ channel: { type: ["string", "null"] },
532
+ thread: { type: ["integer", "null"] },
533
+ data: { type: "object" }
534
+ },
535
+ required: [
536
+ "seq",
537
+ "at",
538
+ "type",
539
+ "by",
540
+ "data"
541
+ ]
542
+ };
543
+ /** What a client can subscribe to. Each takes the filters `mu tail` takes. */
544
+ const TYPES$1 = [
545
+ {
546
+ name: "board.event",
547
+ description: "Every change on the board the caller may read. `types` narrows it, as `mu tail --type` does: a type ending in \".\" takes every type under it (task.).",
548
+ anyType: true
549
+ },
550
+ {
551
+ name: "message.posted",
552
+ description: "A message was posted: a new thread or a reply.",
553
+ types: ["message.posted"]
554
+ },
555
+ {
556
+ name: "task.changed",
557
+ description: "A task changed state or holder: created, claimed, blocked, completed, failed and the rest. `data.type` says which.",
558
+ types: ["task."]
559
+ }
560
+ ];
561
+ function eventCatalog() {
562
+ return TYPES$1.map((type) => ({
563
+ name: type.name,
564
+ description: type.description,
565
+ delivery: ["poll", "push"],
566
+ inputSchema: {
567
+ type: "object",
568
+ properties: type.anyType ? {
569
+ ...FILTERS,
570
+ types: {
571
+ type: "array",
572
+ items: { type: "string" },
573
+ description: "Event types to keep: task.completed, or task. for every task event."
574
+ }
575
+ } : FILTERS,
576
+ additionalProperties: false
577
+ },
578
+ payloadSchema: PAYLOAD
579
+ }));
580
+ }
581
+ /** A subscription's filter, from its event name and arguments, refused when either isn't one the board knows. */
582
+ function filterFor(name, args) {
583
+ const type = TYPES$1.find((each) => each.name === name);
584
+ if (!type) throw new EventsRefusal(EventError.NotFound, `No event "${String(name)}". events/list names those there are.`);
585
+ const given = args === void 0 || args === null ? {} : args;
586
+ if (typeof given !== "object" || Array.isArray(given)) throw new EventsRefusal(EventError.InvalidParams, "\"arguments\" is an object.");
587
+ const filter = {};
588
+ for (const [key$1, value] of Object.entries(given)) {
589
+ const bad = (what) => new EventsRefusal(EventError.InvalidParams, `"${key$1}" is ${what}.`);
590
+ if (key$1 === "channel" || key$1 === "by" || key$1 === "mentions" || key$1 === "text") {
591
+ if (typeof value !== "string" || !value) throw bad("a string");
592
+ filter[key$1] = value;
593
+ } else if (key$1 === "re") {
594
+ if (!Number.isInteger(value) || value < 1) throw bad("a message ID, a whole number");
595
+ filter.re = value;
596
+ } else if (key$1 === "root") {
597
+ if (typeof value !== "boolean") throw bad("true or false");
598
+ if (value) filter.root = true;
599
+ } else if (key$1 === "labels" || key$1 === "kinds" || key$1 === "types" && type.anyType) {
600
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item)) throw bad("a list of strings");
601
+ if (value.length) filter[key$1] = value;
602
+ } else throw new EventsRefusal(EventError.InvalidParams, `"${key$1}" isn't an argument of ${type.name}.`);
603
+ }
604
+ if (type.types) filter.types = type.types;
605
+ return filter;
606
+ }
607
+ /** A cursor as the client holds it: the board's place in its log, as a string. `null` means from now. */
608
+ function cursorOf(value) {
609
+ if (value === void 0 || value === null) return null;
610
+ if (typeof value === "string" && /^(0|[1-9][0-9]*)$/.test(value)) return Number(value);
611
+ throw new EventsRefusal(EventError.InvalidParams, "\"cursor\" is one this server gave, or null for from now.");
612
+ }
613
+ /** A board event as an occurrence of the event a client subscribed to. */
614
+ function occurrence(name, event) {
615
+ return {
616
+ eventId: String(event.seq),
617
+ name,
618
+ timestamp: event.at,
619
+ data: event
620
+ };
621
+ }
622
+ /** A refusal from the board, as the code the extension gives it. */
623
+ function refusalOf(error$1) {
624
+ if (error$1 instanceof EventsRefusal) return error$1;
625
+ if (error$1 instanceof Failure) {
626
+ if (error$1.reason === "forbidden" || error$1.reason === "unauthorized") return new EventsRefusal(EventError.Forbidden, error$1.message);
627
+ if (error$1.exit === 2 || error$1.reason === "not_found") return new EventsRefusal(EventError.InvalidParams, error$1.message);
628
+ return new EventsRefusal(EventError.Internal, error$1.message);
629
+ }
630
+ return new EventsRefusal(EventError.Internal, error$1 instanceof Error ? error$1.message : String(error$1));
631
+ }
632
+ /**
633
+ * One read of the log for a subscription: what matched after its cursor, and where to read on from. A cursor
634
+ * past the end of the log is one this board never gave (the board was restored from a backup, or is another),
635
+ * so the read starts again from now and says events may have been missed.
636
+ */
637
+ async function readPage(team, request, now) {
638
+ const filter = filterFor(request.name, request.arguments);
639
+ const name = request.name;
640
+ const asked = cursorOf(request.cursor);
641
+ const maxEvents = request.maxEvents === void 0 ? 100 : request.maxEvents;
642
+ if (!Number.isInteger(maxEvents) || maxEvents < 1) throw new EventsRefusal(EventError.InvalidParams, "\"maxEvents\" is a whole number of at least 1.");
643
+ const limit = Math.min(maxEvents, 200);
644
+ if (request.maxAgeMs !== void 0 && (!Number.isInteger(request.maxAgeMs) || request.maxAgeMs < 0)) throw new EventsRefusal(EventError.InvalidParams, "\"maxAgeMs\" is a whole number of milliseconds.");
645
+ const head = await team.head();
646
+ if (asked === null) return {
647
+ events: [],
648
+ cursor: String(head),
649
+ truncated: false,
650
+ hasMore: false
651
+ };
652
+ if (asked > head) return {
653
+ events: [],
654
+ cursor: String(head),
655
+ truncated: true,
656
+ hasMore: false
657
+ };
658
+ const page = await team.events({
659
+ after: asked,
660
+ filter,
661
+ limit
662
+ });
663
+ const floor = request.maxAgeMs === void 0 ? null : now - request.maxAgeMs;
664
+ return {
665
+ events: (floor === null ? page.events : page.events.filter((event) => Date.parse(event.at) >= floor)).map((event) => occurrence(name, event)),
666
+ cursor: String(page.cursor),
667
+ truncated: false,
668
+ hasMore: page.events.length === limit
669
+ };
670
+ }
671
+ const SUBSCRIPTION = "io.modelcontextprotocol/subscriptionId";
672
+ /** The heartbeat a stream is granted: what the client asked for, within 5 seconds and a minute, 30 seconds if it asked nothing. */
673
+ function heartbeatOf(asked) {
674
+ if (asked === void 0) return 3e4;
675
+ if (!Number.isInteger(asked) || asked < 1) throw new EventsRefusal(EventError.InvalidParams, "\"heartbeatMs\" is a whole number of milliseconds.");
676
+ return Math.min(Math.max(asked, 5e3), 6e4);
677
+ }
678
+ const sleep$1 = (ms, signal) => new Promise((resolve$1) => {
679
+ if (signal.aborted) return resolve$1();
680
+ const timer = setTimeout(done, ms);
681
+ function done() {
682
+ clearTimeout(timer);
683
+ signal.removeEventListener("abort", done);
684
+ resolve$1();
685
+ }
686
+ signal.addEventListener("abort", done);
687
+ });
688
+ /**
689
+ * `events/stream`: a subscription held open, pushing each matching event as it is written, as `mu tail` follows
690
+ * the log. It reads at most a second apart, and says it is still there when nothing happened for a heartbeat.
691
+ * It ends when the client gives up (`signal`), or when the board refuses it a read: a token revoked, a channel it
692
+ * may no longer read. A read that fails for any other reason is said and tried again.
693
+ *
694
+ * A request the stream can't start for is refused as an error before anything is sent. Otherwise the answer is
695
+ * the stream's final frame, or null when the client gave up, since nobody is left to read it.
696
+ */
697
+ async function streamEvents(team, request, subscription, notify, signal, now = Date.now) {
698
+ const name = request.name;
699
+ filterFor(request.name, request.arguments);
700
+ const heartbeatMs = heartbeatOf(request.heartbeatMs);
701
+ const meta = { [SUBSCRIPTION]: subscription };
702
+ const send = (method, params) => notify({
703
+ jsonrpc: "2.0",
704
+ method,
705
+ params: {
706
+ ...params,
707
+ _meta: meta
708
+ }
709
+ });
710
+ const opening = await readPage(team, {
711
+ ...request,
712
+ cursor: request.cursor ?? null,
713
+ maxEvents: 200
714
+ }, now());
715
+ let cursor$1 = opening.cursor;
716
+ send("notifications/events/active", {
717
+ cursor: request.cursor === void 0 || request.cursor === null ? cursor$1 : opening.truncated ? cursor$1 : String(request.cursor),
718
+ truncated: opening.truncated,
719
+ heartbeatMs
720
+ });
721
+ let pending = opening.events;
722
+ let more = opening.hasMore;
723
+ let quietSince = now();
724
+ let pause = 100;
725
+ for (;;) {
726
+ for (const event of pending) send("notifications/events/event", {
727
+ ...event,
728
+ cursor: event.eventId
729
+ });
730
+ if (pending.length) quietSince = now();
731
+ if (signal.aborted) return null;
732
+ if (now() - quietSince >= heartbeatMs) {
733
+ send("notifications/events/heartbeat", { cursor: cursor$1 });
734
+ quietSince = now();
735
+ }
736
+ pause = pending.length || more ? 0 : Math.min(Math.max(pause * 2, 100), 1e3);
737
+ await sleep$1(pause, signal);
738
+ if (signal.aborted) return null;
739
+ try {
740
+ const page = await readPage(team, {
741
+ name,
742
+ arguments: request.arguments,
743
+ cursor: cursor$1,
744
+ maxAgeMs: request.maxAgeMs,
745
+ maxEvents: 200
746
+ }, now());
747
+ pending = page.events;
748
+ more = page.hasMore;
749
+ cursor$1 = page.cursor;
750
+ } catch (failure) {
751
+ const refused = refusalOf(failure);
752
+ if (refused.code !== EventError.Internal) {
753
+ send("notifications/events/terminated", { error: {
754
+ code: refused.code,
755
+ message: refused.message
756
+ } });
757
+ return { _meta: meta };
758
+ }
759
+ send("notifications/events/error", { error: {
760
+ code: refused.code,
761
+ message: refused.message
762
+ } });
763
+ pending = [];
764
+ more = false;
765
+ pause = 1e3;
766
+ }
767
+ }
768
+ }
769
+
770
+ //#endregion
771
+ //#region src/cli/open.ts
772
+ /** The board at a URL, with a token, or the file board in a folder: how the CLI opens one no board module chose. */
773
+ function openBoard(where) {
774
+ if (where.url) {
775
+ if (!where.token) throw new Failure("unauthorized", `The board at ${where.url} needs a token.`, { hint: "Set MUSTER_TOKEN to one from mu token create." });
776
+ return board({
777
+ backend: http({
778
+ url: where.url,
779
+ token: where.token,
780
+ ...where.insecure ? { insecure: true } : {}
781
+ }),
782
+ as: where.as ?? null
783
+ });
784
+ }
785
+ return board({
786
+ backend: file({
787
+ ...where.dir ? { dir: where.dir } : {},
788
+ ...where.name ? { name: where.name } : {}
789
+ }),
790
+ as: where.as ?? null
791
+ });
792
+ }
793
+ /** The board the environment names, opened as its profile: what `mu` with no flags opens. */
794
+ const boardFromEnv = (env) => openBoard({
795
+ url: env.MUSTER_URL,
796
+ token: env.MUSTER_TOKEN,
797
+ insecure: env.MUSTER_INSECURE_HTTP === "1",
798
+ dir: env.MUSTER_DIR,
799
+ name: env.MUSTER_BOARD,
800
+ as: env.MUSTER_PROFILE || void 0
801
+ });
802
+
803
+ //#endregion
804
+ //#region src/cli/mcp-tasks.ts
805
+ /**
806
+ * The MCP Tasks extension (`io.modelcontextprotocol/tasks`, SEP-2663) for the calls that wait.
807
+ *
808
+ * A `wait`, or a claim or inbox with `--wait`, would hold a tool call open until something happens. To a client
809
+ * that declares the extension, the call answers at once with a task handle instead, and the command runs on
810
+ * with the whole wait it asked for. The client follows the task with `tasks/get`, or has its changes pushed
811
+ * with `subscriptions/listen`, and gives up with `tasks/cancel`.
812
+ *
813
+ * These are MCP tasks, handles on one tool call, kept in this process's memory. A board task is a different
814
+ * thing; the two share only a name. A restart forgets every MCP task, which the extension allows: a lost one
815
+ * is answered like one that never was.
816
+ *
817
+ * A claim must not end up held for a client that has stopped listening. So when a task that claimed a board
818
+ * task is cancelled, or expires before anyone read its result, or the server stops first, the claim is
819
+ * released.
820
+ */
821
+ const EXT_TASKS = "io.modelcontextprotocol/tasks";
822
+ /** How long a task's handle lasts, from its creation. Longer than the longest wait a call may ask for. */
823
+ const TTL_MS = 1440 * 60 * 1e3;
824
+ const POLL_INTERVAL_MS = 2e3;
825
+ /** Tasks one token may have running at once. Past it, a call waits inside itself, as without the extension. */
826
+ const RUNNING_PER_CALLER = 16;
827
+ const tasks$1 = /* @__PURE__ */ new Map();
828
+ /** Who a request comes from, as far as owning a task goes: the token it brought and the profile it writes as. */
829
+ function ownerOf(env) {
830
+ return createHash("sha256").update(`${env.MUSTER_TOKEN ?? ""}\n${env.MUSTER_PROFILE ?? ""}`).digest("base64url");
831
+ }
832
+ /** The token alone. A token that may write as any profile is still one caller to the cap on running tasks. */
833
+ function callerOf(env) {
834
+ return createHash("sha256").update(env.MUSTER_TOKEN ?? "").digest("base64url");
835
+ }
836
+ const terminal = (status) => status === "completed" || status === "failed" || status === "cancelled";
837
+ /** A task as the extension shows it, with what its status carries: a result, or an error. */
838
+ function detailed(entry) {
839
+ return {
840
+ taskId: entry.taskId,
841
+ status: entry.status,
842
+ statusMessage: entry.statusMessage,
843
+ createdAt: entry.createdAt,
844
+ lastUpdatedAt: entry.lastUpdatedAt,
845
+ ttlMs: TTL_MS,
846
+ pollIntervalMs: POLL_INTERVAL_MS,
847
+ ...entry.status === "completed" && entry.result ? { result: entry.result } : {},
848
+ ...entry.status === "failed" && entry.error ? { error: entry.error } : {}
849
+ };
850
+ }
851
+ function changed(entry, to) {
852
+ Object.assign(entry, to, { lastUpdatedAt: (/* @__PURE__ */ new Date()).toISOString() });
853
+ const shown = detailed(entry);
854
+ if (entry.status === "completed" && entry.watchers.size) entry.delivered = true;
855
+ for (const watcher of [...entry.watchers]) watcher(shown);
856
+ }
857
+ /** Lets go of a claim nobody collected. Once: after that the claim is the board's business again. */
858
+ async function letGo(entry) {
859
+ const claim = entry.claimed;
860
+ if (!claim || entry.delivered) return;
861
+ entry.claimed = void 0;
862
+ await claim.release().catch(() => {});
863
+ }
864
+ /** Ends a task nobody will collect: stops it, waits for it to stop, and gives back what it claimed. */
865
+ async function end(entry) {
866
+ if (!terminal(entry.status)) changed(entry, {
867
+ status: "cancelled",
868
+ statusMessage: "Cancelled."
869
+ });
870
+ entry.stop.abort();
871
+ await entry.finished;
872
+ await letGo(entry);
873
+ }
874
+ /** Forgets tasks past their time, letting go of any claim whose result nobody read. */
875
+ async function sweep(now = Date.now()) {
876
+ for (const [id$1, entry] of tasks$1) {
877
+ if (entry.expires > now) continue;
878
+ tasks$1.delete(id$1);
879
+ await end(entry);
880
+ }
881
+ }
882
+ /** The board task a claim's output names, if it claimed one: `#12 yours for 15m`, or the --json document. */
883
+ function claimedIn(text) {
884
+ const line = /^#([1-9][0-9]*) {2}yours for /m.exec(text);
885
+ if (line) return Number(line[1]);
886
+ try {
887
+ const parsed = JSON.parse(text);
888
+ if (parsed.outcome === "claimed" && typeof parsed.task?.id === "number") return parsed.task.id;
889
+ } catch {}
890
+ return null;
891
+ }
892
+ /** Starts a call as a task and answers with its handle, or null when the caller already has as many as it may. */
893
+ async function start$1(work) {
894
+ await sweep();
895
+ if ([...tasks$1.values()].filter((entry$1) => entry$1.caller === work.caller && !terminal(entry$1.status)).length >= RUNNING_PER_CALLER) return null;
896
+ const at = /* @__PURE__ */ new Date();
897
+ const entry = {
898
+ taskId: randomBytes(24).toString("base64url"),
899
+ owner: work.owner,
900
+ caller: work.caller,
901
+ status: "working",
902
+ statusMessage: `Waiting: mu ${work.describe}`,
903
+ createdAt: at.toISOString(),
904
+ lastUpdatedAt: at.toISOString(),
905
+ expires: at.getTime() + TTL_MS,
906
+ delivered: false,
907
+ stop: new AbortController(),
908
+ finished: Promise.resolve(),
909
+ watchers: /* @__PURE__ */ new Set()
910
+ };
911
+ tasks$1.set(entry.taskId, entry);
912
+ entry.finished = work.run(entry.stop.signal).then(async (result$1) => {
913
+ const id$1 = work.release ? claimedIn(result$1.content.map((part) => part.text).join("\n")) : null;
914
+ if (id$1 !== null) entry.claimed = {
915
+ id: id$1,
916
+ release: () => work.release(id$1)
917
+ };
918
+ if (entry.status === "cancelled") return letGo(entry);
919
+ changed(entry, {
920
+ status: "completed",
921
+ statusMessage: result$1.isError ? "Ended with an error." : "Done.",
922
+ result: result$1
923
+ });
924
+ }, (failure) => {
925
+ if (entry.status === "cancelled") return;
926
+ changed(entry, {
927
+ status: "failed",
928
+ statusMessage: "The call failed.",
929
+ error: {
930
+ code: -32603,
931
+ message: failure instanceof Error ? failure.message : String(failure)
932
+ }
933
+ });
934
+ });
935
+ return detailed(entry);
936
+ }
937
+ /** The extension's refusals: an ID that names no task of this caller's is one that doesn't exist. */
938
+ var TaskRefusal = class extends Error {
939
+ code = -32602;
940
+ };
941
+ async function mine(owner, taskId) {
942
+ await sweep();
943
+ const entry = typeof taskId === "string" ? tasks$1.get(taskId) : void 0;
944
+ if (!entry || entry.owner !== owner) throw new TaskRefusal("Failed to retrieve task: Task not found");
945
+ return entry;
946
+ }
947
+ async function get(owner, taskId) {
948
+ const entry = await mine(owner, taskId);
949
+ if (entry.status === "completed") entry.delivered = true;
950
+ return detailed(entry);
951
+ }
952
+ async function cancel(owner, taskId) {
953
+ const entry = await mine(owner, taskId);
954
+ if (terminal(entry.status)) {
955
+ if (!entry.delivered) await letGo(entry);
956
+ return;
957
+ }
958
+ changed(entry, {
959
+ status: "cancelled",
960
+ statusMessage: "Cancelled."
961
+ });
962
+ entry.stop.abort();
963
+ }
964
+ /** `tasks/update` answers input a task asked for. These tasks never ask, so there is nothing to answer. */
965
+ async function update(owner, taskId) {
966
+ await mine(owner, taskId);
967
+ }
968
+ /**
969
+ * Follows tasks for `subscriptions/listen`: each change is sent as it happens, and the listening ends once
970
+ * every task it follows has finished and been sent, or the client gives up. Which IDs it follows is acknowledged
971
+ * before anything is sent.
972
+ */
973
+ async function listen$1(owner, taskIds, acknowledge, send, signal) {
974
+ await sweep();
975
+ const followed = (Array.isArray(taskIds) ? taskIds.filter((id$1) => typeof id$1 === "string") : []).map((id$1) => tasks$1.get(id$1)).filter((entry) => entry !== void 0 && entry.owner === owner);
976
+ acknowledge(followed.map((entry) => entry.taskId));
977
+ await new Promise((resolve$1) => {
978
+ const open$1 = new Set(followed.filter((entry) => !terminal(entry.status)));
979
+ const finish = () => {
980
+ for (const entry of followed) entry.watchers.delete(watch.get(entry));
981
+ resolve$1();
982
+ };
983
+ const watch = /* @__PURE__ */ new Map();
984
+ for (const entry of followed) {
985
+ const watcher = (task) => {
986
+ send(task);
987
+ if (terminal(entry.status)) {
988
+ open$1.delete(entry);
989
+ if (open$1.size === 0) finish();
990
+ }
991
+ };
992
+ watch.set(entry, watcher);
993
+ entry.watchers.add(watcher);
994
+ }
995
+ for (const entry of followed) if (terminal(entry.status)) {
996
+ send(detailed(entry));
997
+ if (entry.status === "completed") entry.delivered = true;
998
+ }
999
+ if (open$1.size === 0) return finish();
1000
+ signal.addEventListener("abort", finish, { once: true });
1001
+ });
1002
+ }
1003
+ /** Stops every task and lets go of what they claimed: the server is going, and nobody can collect them. */
1004
+ async function stopAll() {
1005
+ const entries = [...tasks$1.values()];
1006
+ tasks$1.clear();
1007
+ await Promise.allSettled(entries.map((entry) => end(entry)));
1008
+ }
1009
+
442
1010
  //#endregion
443
1011
  //#region src/cli/mcp.ts
444
1012
  /**
@@ -509,90 +1077,418 @@ const TOOL = {
509
1077
  additionalProperties: false
510
1078
  }
511
1079
  };
512
- const reply = (id$1, result) => ({
1080
+ /**
1081
+ * The protocol revisions the server speaks. 2026-07-28 is stateless: every request carries its own envelope in
1082
+ * `params._meta`, and there is no handshake. The earlier ones open with `initialize`.
1083
+ */
1084
+ const MODERN = "2026-07-28";
1085
+ const LEGACY = [
1086
+ "2025-11-25",
1087
+ "2025-06-18",
1088
+ "2025-03-26"
1089
+ ];
1090
+ const SUPPORTED = [MODERN, ...LEGACY];
1091
+ const META = {
1092
+ version: "io.modelcontextprotocol/protocolVersion",
1093
+ capabilities: "io.modelcontextprotocol/clientCapabilities",
1094
+ serverInfo: "io.modelcontextprotocol/serverInfo"
1095
+ };
1096
+ /** Codes 2026-07-28 defines in the -32020 range, beside the JSON-RPC ones. */
1097
+ const HEADER_MISMATCH = -32020;
1098
+ const MISSING_CAPABILITY = -32021;
1099
+ const UNSUPPORTED_VERSION = -32022;
1100
+ /** Results a 2026-07-28 client may cache: they say for how long (not at all) and for whom (this caller). */
1101
+ const CACHEABLE = new Set(["tools/list", "server/discover"]);
1102
+ /** The longest a tool call holds a wait inside it, so it returns before a client gives up on it. */
1103
+ const INLINE_WAIT_S = 50;
1104
+ /** How long a poller waits before asking again when nothing more is waiting: what `mu tail` waits at most. */
1105
+ const POLL_MS = 1e3;
1106
+ /** The board the server was started on, or why it can't be opened, as the extension words it. */
1107
+ function boardFromEnvOrRefusal(env) {
1108
+ try {
1109
+ return boardFromEnv(env);
1110
+ } catch (failure) {
1111
+ return refusalOf(failure);
1112
+ }
1113
+ }
1114
+ const reply = (id$1, result$1) => ({
513
1115
  jsonrpc: "2.0",
514
1116
  id: id$1,
515
- result
1117
+ result: result$1
516
1118
  });
517
- const error = (id$1, code, message) => ({
1119
+ const error = (id$1, code, message, data) => ({
518
1120
  jsonrpc: "2.0",
519
1121
  id: id$1 ?? null,
520
1122
  error: {
521
1123
  code,
522
- message
1124
+ message,
1125
+ ...data ? { data } : {}
523
1126
  }
524
1127
  });
525
- async function call(args, env, run) {
1128
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1129
+ /** The value of `--flag` in a command line, written as `--flag value` or `--flag=value`. */
1130
+ function flagAt(args, flag) {
1131
+ for (let at = 1; at < args.length; at++) {
1132
+ const arg = args[at];
1133
+ if (arg === `--${flag}` && at + 1 < args.length) return {
1134
+ at,
1135
+ value: args[at + 1],
1136
+ joined: false
1137
+ };
1138
+ if (arg.startsWith(`--${flag}=`)) return {
1139
+ at,
1140
+ value: arg.slice(flag.length + 3),
1141
+ joined: true
1142
+ };
1143
+ }
1144
+ return null;
1145
+ }
1146
+ /** A command that waits for something to happen: it may hold a call open, so it runs beside the others. */
1147
+ function waits(args) {
1148
+ if (args[0] === "wait") return true;
1149
+ return (args[0] === "tasks" || args[0] === "inbox") && flagAt(args, "wait") !== null;
1150
+ }
1151
+ /**
1152
+ * The command line run inside one tool call. A wait with no limit is given one, and a wait, claim or inbox read
1153
+ * that waits longer than a call should is held to it, so every call returns.
1154
+ */
1155
+ function inline(args) {
1156
+ if (args[0] === "wait") return flagAt(args, "timeout") ? capped(args, "timeout") : [
1157
+ ...args,
1158
+ "--timeout",
1159
+ `${INLINE_WAIT_S}s`
1160
+ ];
1161
+ if (args[0] === "tasks" || args[0] === "inbox") return capped(args, "wait");
1162
+ return args;
1163
+ }
1164
+ /** A command line with a duration flag held to the longest one call waits. */
1165
+ function capped(args, flag) {
1166
+ const found = flagAt(args, flag);
1167
+ if (!found) return args;
1168
+ let seconds;
1169
+ try {
1170
+ seconds = duration(found.value, flag);
1171
+ } catch {
1172
+ return args;
1173
+ }
1174
+ if (seconds <= INLINE_WAIT_S) return args;
1175
+ const out = [...args];
1176
+ if (found.joined) out[found.at] = `--${flag}=${INLINE_WAIT_S}s`;
1177
+ else out[found.at + 1] = `${INLINE_WAIT_S}s`;
1178
+ return out;
1179
+ }
1180
+ async function call(args, env, run, signal, whole = false) {
526
1181
  const why$1 = refusal$1(args);
527
1182
  if (why$1) return {
528
1183
  text: why$1,
529
1184
  failed: true
530
1185
  };
531
- const argv = args[0] === "wait" && !args.some((arg) => arg === "--timeout" || arg.startsWith("--timeout=")) ? [
532
- ...args,
533
- "--timeout",
534
- "50s"
535
- ] : args;
536
1186
  const out = [];
537
1187
  const err = [];
538
- const code = await run(argv, {
1188
+ const code = await run(whole ? args : inline(args), {
539
1189
  out: (text) => void out.push(text),
540
1190
  err: (text) => void err.push(text),
541
1191
  stdin: () => "",
542
1192
  env,
543
- stop: new AbortController().signal
1193
+ stop: signal
544
1194
  });
545
1195
  return {
546
1196
  text: [...out, ...err].join("\n") || (code === 0 ? "done" : `exit ${code}`),
547
1197
  failed: code !== 0
548
1198
  };
549
1199
  }
1200
+ function eraOf(params) {
1201
+ const meta = isObject(params?._meta) ? params._meta : void 0;
1202
+ const version = meta?.[META.version];
1203
+ if (version === void 0) return { modern: false };
1204
+ if (typeof version !== "string") return { refused: {
1205
+ code: -32602,
1206
+ message: `${META.version} is a string.`
1207
+ } };
1208
+ if (version !== MODERN) return { refused: {
1209
+ code: UNSUPPORTED_VERSION,
1210
+ message: `Unsupported protocol version: ${version}`,
1211
+ data: {
1212
+ supported: SUPPORTED,
1213
+ requested: version
1214
+ }
1215
+ } };
1216
+ const capabilities = meta[META.capabilities];
1217
+ if (!isObject(capabilities)) return { refused: {
1218
+ code: -32602,
1219
+ message: `The request's _meta needs ${META.capabilities}, an object.`
1220
+ } };
1221
+ return {
1222
+ modern: true,
1223
+ version,
1224
+ capabilities
1225
+ };
1226
+ }
1227
+ /** Whether a 2026-07-28 request declares an extension in its envelope's capabilities. */
1228
+ const declares = (era, extension) => era.modern && isObject(era.capabilities.extensions) && isObject(era.capabilities.extensions[extension]);
1229
+ /** A result as a 2026-07-28 client reads it: what kind it is, who answered, and whether it may be kept. */
1230
+ function result(era, method, body) {
1231
+ if (!era.modern) return body;
1232
+ return {
1233
+ resultType: "complete",
1234
+ ...body,
1235
+ ...CACHEABLE.has(method) ? {
1236
+ ttlMs: 0,
1237
+ cacheScope: "private"
1238
+ } : {},
1239
+ _meta: {
1240
+ ...isObject(body._meta) ? body._meta : {},
1241
+ [META.serverInfo]: {
1242
+ name: "muster",
1243
+ version: VERSION
1244
+ }
1245
+ }
1246
+ };
1247
+ }
1248
+ /** Streams one caller may hold open at once. Each reads the log about once a second. */
1249
+ const STREAMS_PER_CALLER = 8;
1250
+ const open = /* @__PURE__ */ new Map();
550
1251
  /**
551
1252
  * Answers one JSON-RPC message, whichever transport brought it: a response, or null for a notification,
552
1253
  * which gets none. `env` says which board the tool uses and as whom; nothing in the message changes it.
553
1254
  */
554
- async function answer(message, env, run) {
555
- if (!message || typeof message !== "object" || Array.isArray(message)) return error(null, -32600, "Send one JSON-RPC message, as an object.");
1255
+ async function answer(message, env, run, options = {}) {
1256
+ if (!isObject(message)) return error(null, -32600, "Send one JSON-RPC message, as an object.");
556
1257
  const { id: id$1, method, params } = message;
557
1258
  if (id$1 === void 0) return null;
558
- if (method === "initialize") return reply(id$1, {
559
- protocolVersion: typeof params?.protocolVersion === "string" ? params.protocolVersion : "2025-06-18",
560
- capabilities: { tools: {} },
561
- serverInfo: {
562
- name: "muster",
563
- version: VERSION
1259
+ const era = eraOf(params);
1260
+ if ("refused" in era) return error(id$1, era.refused.code, era.refused.message, era.refused.data);
1261
+ const signal = options.signal ?? new AbortController().signal;
1262
+ if (method === "initialize") {
1263
+ if (era.modern) return error(id$1, -32601, "No method \"initialize\" on protocol revision 2026-07-28: each request carries its own _meta.");
1264
+ const asked = typeof params?.protocolVersion === "string" ? params.protocolVersion : void 0;
1265
+ return reply(id$1, {
1266
+ protocolVersion: asked !== void 0 && LEGACY.includes(asked) ? asked : LEGACY[0],
1267
+ capabilities: { tools: {} },
1268
+ serverInfo: {
1269
+ name: "muster",
1270
+ version: VERSION
1271
+ },
1272
+ instructions: TOOL.description
1273
+ });
1274
+ }
1275
+ if (method === "server/discover") return reply(id$1, result(era, method, {
1276
+ supportedVersions: SUPPORTED,
1277
+ capabilities: {
1278
+ tools: {},
1279
+ extensions: {
1280
+ [EXT_EVENTS]: {},
1281
+ [EXT_TASKS]: {}
1282
+ }
564
1283
  },
565
1284
  instructions: TOOL.description
566
- });
567
- if (method === "ping") return reply(id$1, {});
568
- if (method === "tools/list") return reply(id$1, { tools: [TOOL] });
1285
+ }));
1286
+ if (era.modern && method === "events/list") return reply(id$1, result(era, method, { events: eventCatalog() }));
1287
+ if (era.modern && method === "events/poll") {
1288
+ const team = boardFromEnvOrRefusal(env);
1289
+ if (team instanceof EventsRefusal) return error(id$1, team.code, team.message);
1290
+ try {
1291
+ const page = await readPage(team, params ?? {}, Date.now());
1292
+ return reply(id$1, result(era, method, {
1293
+ ...page,
1294
+ nextPollMs: page.hasMore ? 0 : POLL_MS
1295
+ }));
1296
+ } catch (failure) {
1297
+ const refused = refusalOf(failure);
1298
+ return error(id$1, refused.code, refused.message);
1299
+ } finally {
1300
+ team.close();
1301
+ }
1302
+ }
1303
+ if (era.modern && method === "events/stream") {
1304
+ if (!options.notify) return error(id$1, -32601, "This transport keeps no stream open: use events/poll.");
1305
+ const caller = env.MUSTER_TOKEN ?? "";
1306
+ if ((open.get(caller) ?? 0) >= STREAMS_PER_CALLER) return error(id$1, EventError.ResourceExhausted, `A caller holds at most ${STREAMS_PER_CALLER} streams. Close one, or use events/poll.`);
1307
+ const team = boardFromEnvOrRefusal(env);
1308
+ if (team instanceof EventsRefusal) return error(id$1, team.code, team.message);
1309
+ open.set(caller, (open.get(caller) ?? 0) + 1);
1310
+ try {
1311
+ const final = await streamEvents(team, params ?? {}, id$1, options.notify, signal);
1312
+ return final === null ? null : reply(id$1, result(era, method, final));
1313
+ } catch (failure) {
1314
+ const refused = refusalOf(failure);
1315
+ return error(id$1, refused.code, refused.message);
1316
+ } finally {
1317
+ const left = (open.get(caller) ?? 1) - 1;
1318
+ if (left > 0) open.set(caller, left);
1319
+ else open.delete(caller);
1320
+ team.close();
1321
+ }
1322
+ }
1323
+ if (era.modern && (method === "tasks/get" || method === "tasks/update" || method === "tasks/cancel" || method === "subscriptions/listen")) {
1324
+ if (!declares(era, EXT_TASKS)) return error(id$1, MISSING_CAPABILITY, `${method} needs a client that declares the ${EXT_TASKS} extension on the request.`, { requiredCapabilities: { extensions: { [EXT_TASKS]: {} } } });
1325
+ const owner = ownerOf(env);
1326
+ try {
1327
+ if (method === "tasks/get") return reply(id$1, result(era, method, await get(owner, params?.taskId)));
1328
+ if (method === "tasks/update") return await update(owner, params?.taskId), reply(id$1, result(era, method, {}));
1329
+ if (method === "tasks/cancel") return await cancel(owner, params?.taskId), reply(id$1, result(era, method, {}));
1330
+ } catch (failure) {
1331
+ if (failure instanceof TaskRefusal) return error(id$1, failure.code, failure.message);
1332
+ throw failure;
1333
+ }
1334
+ if (!options.notify) return error(id$1, -32601, "This transport keeps no stream open: poll with tasks/get.");
1335
+ const notify = options.notify;
1336
+ const meta = { "io.modelcontextprotocol/subscriptionId": id$1 };
1337
+ const asked = isObject(params?.notifications) ? params.notifications.taskIds : void 0;
1338
+ await listen$1(owner, asked, (taskIds) => notify({
1339
+ jsonrpc: "2.0",
1340
+ method: "notifications/subscriptions/acknowledged",
1341
+ params: {
1342
+ notifications: { taskIds },
1343
+ _meta: meta
1344
+ }
1345
+ }), (task) => notify({
1346
+ jsonrpc: "2.0",
1347
+ method: "notifications/tasks",
1348
+ params: {
1349
+ ...task,
1350
+ _meta: meta
1351
+ }
1352
+ }), signal);
1353
+ return signal.aborted ? null : reply(id$1, result(era, method, { _meta: meta }));
1354
+ }
1355
+ if (method === "ping") return reply(id$1, result(era, method, {}));
1356
+ if (method === "tools/list") return reply(id$1, result(era, method, { tools: [TOOL] }));
569
1357
  if (method === "tools/call") {
570
1358
  const args = (params?.arguments)?.args;
571
1359
  if (params?.name !== TOOL.name) return error(id$1, -32602, `No tool "${String(params?.name)}".`);
572
1360
  if (!Array.isArray(args) || !args.every((arg) => typeof arg === "string")) return error(id$1, -32602, "\"args\" is a list of strings.");
573
1361
  try {
574
- const done = await call(args, env, run);
575
- return reply(id$1, {
1362
+ if (era.modern && declares(era, EXT_TASKS) && waits(args) && refusal$1(args) === null) {
1363
+ const own = args[0] === "tasks" && !env.MUSTER_CLAIM_TOKEN ? {
1364
+ ...env,
1365
+ MUSTER_CLAIM_TOKEN: randomBytes(32).toString("base64url")
1366
+ } : env;
1367
+ const handle = await start$1({
1368
+ owner: ownerOf(env),
1369
+ caller: callerOf(env),
1370
+ describe: args.join(" ").slice(0, 200),
1371
+ run: async (stop) => {
1372
+ const done$1 = await call(args, own, run, stop, true);
1373
+ return {
1374
+ resultType: "complete",
1375
+ content: [{
1376
+ type: "text",
1377
+ text: done$1.text
1378
+ }],
1379
+ isError: done$1.failed
1380
+ };
1381
+ },
1382
+ ...args[0] === "tasks" ? { release: async (task) => void await call([
1383
+ "tasks",
1384
+ "release",
1385
+ String(task)
1386
+ ], own, run, new AbortController().signal) } : {}
1387
+ });
1388
+ if (handle) return reply(id$1, {
1389
+ resultType: "task",
1390
+ ...handle,
1391
+ _meta: { [META.serverInfo]: {
1392
+ name: "muster",
1393
+ version: VERSION
1394
+ } }
1395
+ });
1396
+ }
1397
+ const done = await call(args, env, run, signal);
1398
+ return reply(id$1, result(era, method, {
576
1399
  content: [{
577
1400
  type: "text",
578
1401
  text: done.text
579
1402
  }],
580
1403
  isError: done.failed
581
- });
1404
+ }));
582
1405
  } catch (failure) {
583
- return reply(id$1, {
1406
+ return reply(id$1, result(era, method, {
584
1407
  content: [{
585
1408
  type: "text",
586
1409
  text: `error: ${failure instanceof Error ? failure.message : String(failure)}`
587
1410
  }],
588
1411
  isError: true
589
- });
1412
+ }));
590
1413
  }
591
1414
  }
592
1415
  return error(id$1, -32601, `No method "${String(method)}".`);
593
1416
  }
594
- /** `mu mcp`: the server on this process's standard input and output, one message per line. */
1417
+ /** Where the `Mcp-Name` header's value comes from, for the methods that need one. */
1418
+ const NAME_SOURCE = {
1419
+ "tools/call": "name",
1420
+ "events/poll": "name",
1421
+ "events/stream": "name",
1422
+ "tasks/get": "taskId",
1423
+ "tasks/update": "taskId",
1424
+ "tasks/cancel": "taskId"
1425
+ };
1426
+ /** A header value, decoded from the `=?base64?...?=` form a value that isn't plain ASCII takes. */
1427
+ function headerValue(raw) {
1428
+ const value = raw.trim();
1429
+ if (!(value.startsWith("=?base64?") && value.endsWith("?="))) return value;
1430
+ const encoded = value.slice(9, -2);
1431
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) return null;
1432
+ return Buffer.from(encoded, "base64").toString("utf8");
1433
+ }
1434
+ /**
1435
+ * Over HTTP, a 2026-07-28 request repeats what it is in headers, so whatever sits between client and server can
1436
+ * route it without reading the body. A request whose headers and body disagree is refused before it runs, with
1437
+ * 400. Earlier revisions send no such headers and are not checked.
1438
+ */
1439
+ function headerProblem(message, header) {
1440
+ if (!isObject(message) || message.id === void 0 || typeof message.method !== "string") return null;
1441
+ const params = isObject(message.params) ? message.params : void 0;
1442
+ const era = eraOf(params);
1443
+ if ("refused" in era) return {
1444
+ status: 400,
1445
+ body: error(message.id, era.refused.code, era.refused.message, era.refused.data)
1446
+ };
1447
+ if (!era.modern) return null;
1448
+ const mismatch = (what) => ({
1449
+ status: 400,
1450
+ body: error(message.id, HEADER_MISMATCH, `Bad Request: the request headers and body disagree: ${what}`)
1451
+ });
1452
+ const version = header("mcp-protocol-version")?.trim();
1453
+ if (version !== era.version) return mismatch(version === void 0 ? "the MCP-Protocol-Version header is missing" : `MCP-Protocol-Version is ${version}, the body names ${era.version}`);
1454
+ const method = header("mcp-method")?.trim();
1455
+ if (method !== message.method) return mismatch(method === void 0 ? "the Mcp-Method header is missing" : `Mcp-Method is ${method}, the body names ${message.method}`);
1456
+ const field = NAME_SOURCE[message.method];
1457
+ const bodyName = field !== void 0 && typeof params?.[field] === "string" ? params[field] : void 0;
1458
+ if (bodyName === void 0) return null;
1459
+ const sent = header("mcp-name");
1460
+ if (sent === void 0) return mismatch(`the body carries params.${field} but the Mcp-Name header is missing`);
1461
+ const name = headerValue(sent);
1462
+ if (name === null) return mismatch("the Mcp-Name header is not valid Base64 in its =?base64?...?= form");
1463
+ if (name !== bodyName) return mismatch(`Mcp-Name is "${name}", the body carries params.${field} "${bodyName}"`);
1464
+ return null;
1465
+ }
1466
+ /** A request's place in the table of those still running, so a cancellation can find it by its id. */
1467
+ const keyOf = (id$1) => `${typeof id$1}:${String(id$1)}`;
1468
+ /**
1469
+ * `mu mcp`: the server on this process's standard input and output, one message per line.
1470
+ *
1471
+ * Calls are answered in the order they came, except a call that waits for something to happen: it runs beside
1472
+ * the rest, so the connection stays usable while it waits, and a client that gives up on it says so with
1473
+ * `notifications/cancelled`. A cancelled call stops, takes nothing, and gets no answer.
1474
+ */
595
1475
  async function mcp(input, output, env, run) {
1476
+ const write = (message) => void output.write(`${JSON.stringify(message)}\n`);
1477
+ const running = /* @__PURE__ */ new Map();
1478
+ const beside = /* @__PURE__ */ new Set();
1479
+ let inOrder = Promise.resolve();
1480
+ const handle = async (message, abort) => {
1481
+ const key$1 = keyOf(message.id);
1482
+ try {
1483
+ const response = await answer(message, env, run, {
1484
+ signal: abort.signal,
1485
+ notify: (note) => void (abort.signal.aborted || write(note))
1486
+ });
1487
+ if (response && !abort.signal.aborted) write(response);
1488
+ } finally {
1489
+ if (running.get(key$1) === abort) running.delete(key$1);
1490
+ }
1491
+ };
596
1492
  for await (const line of createInterface({
597
1493
  input,
598
1494
  crlfDelay: Infinity
@@ -602,12 +1498,28 @@ async function mcp(input, output, env, run) {
602
1498
  try {
603
1499
  message = JSON.parse(line);
604
1500
  } catch {
605
- output.write(`${JSON.stringify(error(null, -32700, "That line is not JSON."))}\n`);
1501
+ write(error(null, -32700, "That line is not JSON."));
606
1502
  continue;
607
1503
  }
608
- const response = await answer(message, env, run);
609
- if (response) output.write(`${JSON.stringify(response)}\n`);
1504
+ if (!isObject(message) || message.id === void 0) {
1505
+ if (isObject(message) && message.method === "notifications/cancelled" && isObject(message.params)) running.get(keyOf(message.params.requestId))?.abort();
1506
+ if (!isObject(message)) inOrder = inOrder.then(async () => void write(await answer(message, env, run)));
1507
+ continue;
1508
+ }
1509
+ const request = message;
1510
+ const abort = new AbortController();
1511
+ running.set(keyOf(request.id), abort);
1512
+ const args = (request.params?.arguments)?.args;
1513
+ if (request.method === "events/stream" || request.method === "subscriptions/listen" || request.method === "tools/call" && Array.isArray(args) && args.every((arg) => typeof arg === "string") && waits(args)) {
1514
+ const done = handle(request, abort);
1515
+ beside.add(done);
1516
+ done.finally(() => beside.delete(done));
1517
+ } else inOrder = inOrder.then(() => handle(request, abort));
610
1518
  }
1519
+ await inOrder;
1520
+ for (const abort of running.values()) abort.abort();
1521
+ await Promise.allSettled([...beside]);
1522
+ await stopAll();
611
1523
  }
612
1524
 
613
1525
  //#endregion
@@ -756,6 +1668,7 @@ tasks
756
1668
  [--limit n] [--latest]
757
1669
  tasks create <channel> <text> [--label k=v]... [--needs <id>]...
758
1670
  [--for <profile>] [--claim] [--hold <kind> [--reason <text>]]
1671
+ [--attach <path>]...
759
1672
  tasks create <id> make a thread a task
760
1673
  tasks create <channel> --file plan.json
761
1674
  tasks claim <id> | --ready <channel> [--label k=v]... [--from <owner>]...
@@ -803,7 +1716,7 @@ agents
803
1716
 
804
1717
  schedules and the daemon
805
1718
  schedule <channel|id> <text> --in 30m | --at <time> | --every 30m
806
- [--times n] [--until <time>]
1719
+ [--times n] [--until <time>] [--no-sync]
807
1720
  schedule list | schedule cancel <id>
808
1721
  daemon run send what is due; run watchers and hooks
809
1722
  daemon check <watcher> write what it listens for; wait for a reply
@@ -995,8 +1908,8 @@ function inspect(options) {
995
1908
  return send(res, 200, { ok: route === "joinList" ? await joins.list() : route === "joinDeny" ? await joins.deny(request) : await joins.approve(request) });
996
1909
  }
997
1910
  const caller = await options.backend.self(body.as ? profileName(body.as) : null);
998
- const result = await options.backend[route](caller, ...body.args ?? []);
999
- return send(res, 200, { ok: result === void 0 ? null : result });
1911
+ const result$1 = await options.backend[route](caller, ...body.args ?? []);
1912
+ return send(res, 200, { ok: result$1 === void 0 ? null : result$1 });
1000
1913
  }
1001
1914
  if (req.method === "GET") {
1002
1915
  res.writeHead(200, {
@@ -1490,7 +2403,7 @@ const commands = {
1490
2403
  },
1491
2404
  async run(run, parsed) {
1492
2405
  const profile = str(parsed.flags, "as") ?? (run.io.env.MUSTER_PROFILE || void 0);
1493
- const mine = actorId(await run.team.backend.self(profile ?? null));
2406
+ const mine$1 = actorId(await run.team.backend.self(profile ?? null));
1494
2407
  const limit = str(parsed.flags, "limit");
1495
2408
  const wait = str(parsed.flags, "wait");
1496
2409
  const peek = on(parsed.flags, "peek");
@@ -1505,7 +2418,7 @@ const commands = {
1505
2418
  try {
1506
2419
  page = await run.team.events({
1507
2420
  after,
1508
- filter: { for: mine },
2421
+ filter: { for: mine$1 },
1509
2422
  limit: limit === void 0 ? 50 : Number(limit)
1510
2423
  });
1511
2424
  outage?.ok();
@@ -1686,7 +2599,7 @@ const commands = {
1686
2599
  message: wanted,
1687
2600
  id: file$1.id
1688
2601
  });
1689
- const path = join(to, basename(file$1.name));
2602
+ const path = join(to, basename(fileName(file$1.name).replace(INVISIBLE, "").replace(/^[.\s]+/, "") || (/^[0-9a-f]{64}$/.test(file$1.id) ? file$1.id : "file")));
1690
2603
  try {
1691
2604
  writeFileSync(path, Buffer.from(got.data, "base64"), { flag: "wx" });
1692
2605
  } catch (error$1) {
@@ -1907,14 +2820,17 @@ const commands = {
1907
2820
  }
1908
2821
  },
1909
2822
  schedule: {
1910
- spec: { value: [
1911
- "in",
1912
- "at",
1913
- "every",
1914
- "times",
1915
- "until",
1916
- "file"
1917
- ] },
2823
+ spec: {
2824
+ value: [
2825
+ "in",
2826
+ "at",
2827
+ "every",
2828
+ "times",
2829
+ "until",
2830
+ "file"
2831
+ ],
2832
+ bool: ["no-sync"]
2833
+ },
1918
2834
  async run(run, parsed) {
1919
2835
  const verb = parsed.positionals[0];
1920
2836
  if (verb === "list" || verb === void 0) {
@@ -1936,7 +2852,8 @@ const commands = {
1936
2852
  ...at !== void 0 ? { at } : {},
1937
2853
  ...every !== void 0 ? { every: duration(every, "every") } : {},
1938
2854
  ...flag("times") !== void 0 ? { times: Number(flag("times")) } : {},
1939
- ...flag("until") !== void 0 ? { until: flag("until") } : {}
2855
+ ...flag("until") !== void 0 ? { until: flag("until") } : {},
2856
+ ...on(parsed.flags, "no-sync") ? { noSync: true } : {}
1940
2857
  });
1941
2858
  print(run, { schedule }, () => `scheduled ${schedule.id} next ${schedule.next}`);
1942
2859
  }
@@ -2140,8 +3057,8 @@ const commands = {
2140
3057
  result: "recovers from a torn write"
2141
3058
  });
2142
3059
  });
2143
- const end = await demo.task(ship);
2144
- run.io.out(`ship task #${ship} is ${end?.state}`);
3060
+ const end$1 = await demo.task(ship);
3061
+ run.io.out(`ship task #${ship} is ${end$1?.state}`);
2145
3062
  if (!on(parsed.flags, "once")) await new Promise((resolve$1) => run.io.stop.aborted ? resolve$1() : run.io.stop.addEventListener("abort", () => resolve$1()));
2146
3063
  await serving.close();
2147
3064
  demo.close();
@@ -2340,13 +3257,18 @@ const commands = {
2340
3257
  let serving;
2341
3258
  let self$1 = "";
2342
3259
  const allowJoins = on(parsed.flags, "allow-joins") || run.io.env.MUSTER_ALLOW_JOINS === "1";
2343
- const mcp$1 = (message, as) => answer(message, {
3260
+ const mcp$1 = (message, as, signal, notify) => answer(message, {
2344
3261
  MUSTER_URL: self$1,
2345
3262
  MUSTER_TOKEN: as.token,
2346
3263
  MUSTER_INSECURE_HTTP: "1",
2347
3264
  ...as.profile ? { MUSTER_PROFILE: as.profile } : {}
2348
- }, main);
3265
+ }, main, {
3266
+ signal,
3267
+ notify
3268
+ });
2349
3269
  const oidc = loadOidc();
3270
+ const authenticate = run.module && !run.module.error ? run.team[Symbol.for("muster.authenticate")] : void 0;
3271
+ if (authenticate) run.io.err("sign-in requests with no token are named by the module's authenticate");
2350
3272
  try {
2351
3273
  serving = await listen({
2352
3274
  backend: run.team.backend,
@@ -2356,9 +3278,11 @@ const commands = {
2356
3278
  host,
2357
3279
  hosts: allowed,
2358
3280
  mcp: mcp$1,
3281
+ mcpHeaders: headerProblem,
2359
3282
  allowJoins,
2360
3283
  oidc,
2361
- log: (line) => run.io.err(line)
3284
+ log: (line) => run.io.err(line),
3285
+ ...authenticate ? { authenticate } : {}
2362
3286
  });
2363
3287
  self$1 = serving.url;
2364
3288
  } catch (error$1) {
@@ -2428,6 +3352,7 @@ const commands = {
2428
3352
  } finally {
2429
3353
  watching?.stop();
2430
3354
  await watching?.done;
3355
+ await stopAll();
2431
3356
  await serving.close();
2432
3357
  }
2433
3358
  return 0;
@@ -2629,7 +3554,8 @@ const commands = {
2629
3554
  many: [
2630
3555
  "label",
2631
3556
  "needs",
2632
- "from"
3557
+ "from",
3558
+ "attach"
2633
3559
  ],
2634
3560
  bool: [
2635
3561
  "claim",
@@ -2688,7 +3614,8 @@ const TASK_FLAGS = {
2688
3614
  "reason",
2689
3615
  "file",
2690
3616
  "idempotency-key",
2691
- "no-sync"
3617
+ "no-sync",
3618
+ "attach"
2692
3619
  ],
2693
3620
  claim: CLAIM_FLAGS,
2694
3621
  renew: ["lease"],
@@ -2836,7 +3763,8 @@ async function tasks(run, parsed) {
2836
3763
  ...assignee !== void 0 ? ["--for", assignee] : [],
2837
3764
  ...on(parsed.flags, "claim") ? ["--claim"] : [],
2838
3765
  ...holdKind !== void 0 ? ["--hold", holdKind] : [],
2839
- ...on(parsed.flags, "no-sync") ? ["--no-sync"] : []
3766
+ ...on(parsed.flags, "no-sync") ? ["--no-sync"] : [],
3767
+ ...list(parsed.flags, "attach").flatMap((path) => ["--attach", path])
2840
3768
  ];
2841
3769
  let plan;
2842
3770
  try {
@@ -2873,7 +3801,9 @@ async function tasks(run, parsed) {
2873
3801
  }
2874
3802
  if (target === void 0) throw misuse("invalid_channel", "Name a channel and the task, or a thread to make a task of.");
2875
3803
  const labels = pairs(list(parsed.flags, "label"), "label");
2876
- const made = /^#?[1-9][0-9]*$/.test(target) ? await run.team.taskCreate({
3804
+ const ofThread = /^#?[1-9][0-9]*$/.test(target);
3805
+ if (ofThread && list(parsed.flags, "attach").length) throw misuse("invalid_args", `--attach starts a task with files, and #${id(target)} has started.`, `Attach them in a reply: mu reply ${id(target)} "<text>" --attach <path>.`);
3806
+ const made = ofThread ? await run.team.taskCreate({
2877
3807
  thread: id(target),
2878
3808
  ...common
2879
3809
  }) : await run.team.taskCreate({
@@ -2887,6 +3817,7 @@ async function tasks(run, parsed) {
2887
3817
  }, 2, run.io),
2888
3818
  ...Object.keys(labels).length ? { labels } : {},
2889
3819
  ...on(parsed.flags, "no-sync") ? { noSync: true } : {},
3820
+ ...await attach(run, list(parsed.flags, "attach")),
2890
3821
  ...common
2891
3822
  });
2892
3823
  if (made.token) keep(run, me, made.task.id, {
@@ -2932,10 +3863,10 @@ async function tasks(run, parsed) {
2932
3863
  }
2933
3864
  case "complete": {
2934
3865
  const task = id(target, "a task");
2935
- const result = parsed.positionals[2] ?? str(parsed.flags, "result");
3866
+ const result$1 = parsed.positionals[2] ?? str(parsed.flags, "result");
2936
3867
  const done = await run.team.taskComplete({
2937
3868
  ...held(task),
2938
- ...result !== void 0 ? { result } : {}
3869
+ ...result$1 !== void 0 ? { result: result$1 } : {}
2939
3870
  });
2940
3871
  dropClaim(me, task);
2941
3872
  return print(run, {
@@ -3108,11 +4039,11 @@ async function runTask(run, parsed, target, me) {
3108
4039
  return stopCode(run.io.stop);
3109
4040
  }
3110
4041
  if (exit.code === 0) {
3111
- const result = str(parsed.flags, "result");
4042
+ const result$1 = str(parsed.flags, "result");
3112
4043
  await run.team.taskComplete({
3113
4044
  id: task,
3114
4045
  token,
3115
- ...result !== void 0 ? { result } : {}
4046
+ ...result$1 !== void 0 ? { result: result$1 } : {}
3116
4047
  });
3117
4048
  done("completed");
3118
4049
  return 0;
@@ -3276,7 +4207,7 @@ async function runAgent(run, parsed, onKind, onCost) {
3276
4207
  const asked = str(parsed.flags, "resume");
3277
4208
  if (asked !== void 0 && !isSessionId(asked)) throw misuse("invalid_session", `"${asked}" isn't a session ID.`);
3278
4209
  const remembered = on(parsed.flags, "fresh") || before.agent !== agent.name || !isSessionId(before.session) ? void 0 : before.session;
3279
- const start$1 = (resume) => runLocal({
4210
+ const start$2 = (resume) => runLocal({
3280
4211
  agent,
3281
4212
  prompt: agentPrompt(task, me.profile, claimed.task.rounds),
3282
4213
  cwd,
@@ -3296,7 +4227,7 @@ async function runAgent(run, parsed, onKind, onCost) {
3296
4227
  ...timeout ? { timeoutMs: duration(timeout, "timeout") * 1e3 } : {},
3297
4228
  signal: run.io.stop
3298
4229
  });
3299
- const started = start$1(asked ?? remembered);
4230
+ const started = start$2(asked ?? remembered);
3300
4231
  let lost = false;
3301
4232
  const renewing = setInterval(() => {
3302
4233
  run.team.taskRenew({
@@ -3307,38 +4238,38 @@ async function runAgent(run, parsed, onKind, onCost) {
3307
4238
  if (error$1 instanceof Failure && error$1.reason === "claim_lost") lost = true;
3308
4239
  });
3309
4240
  }, Math.max(1e4, leaseS * 1e3 / 3));
3310
- let result = await started.done;
3311
- if (result.kind === "bad_resume" && asked === void 0 && remembered !== void 0 && !run.io.stop.aborted) {
4241
+ let result$1 = await started.done;
4242
+ if (result$1.kind === "bad_resume" && asked === void 0 && remembered !== void 0 && !run.io.stop.aborted) {
3312
4243
  await run.team.label({
3313
4244
  id: task,
3314
4245
  unset: ["session", "agent"]
3315
4246
  }).catch(() => {});
3316
- if (result.parsed.costUsd !== void 0) onCost?.(result.parsed.costUsd);
3317
- result = await start$1(void 0).done;
4247
+ if (result$1.parsed.costUsd !== void 0) onCost?.(result$1.parsed.costUsd);
4248
+ result$1 = await start$2(void 0).done;
3318
4249
  }
3319
4250
  clearInterval(renewing);
3320
- onKind?.(result.kind);
3321
- if (result.parsed.costUsd !== void 0) onCost?.(result.parsed.costUsd);
4251
+ onKind?.(result$1.kind);
4252
+ if (result$1.parsed.costUsd !== void 0) onCost?.(result$1.parsed.costUsd);
3322
4253
  const after = await run.team.task(task);
3323
4254
  const stillOurs = after?.state === "claimed" && after.claim?.epoch === claimed.task.claim.epoch;
3324
4255
  let outcome = after?.state ?? "gone";
3325
4256
  if (stillOurs) {
3326
4257
  const settle = async () => {
3327
- if (result.notStarted) return run.team.taskRelease({
4258
+ if (result$1.notStarted) return run.team.taskRelease({
3328
4259
  id: task,
3329
4260
  token
3330
4261
  }).then(() => "released");
3331
- if (result.kind === "stopped") return run.team.taskRelease({
4262
+ if (result$1.kind === "stopped") return run.team.taskRelease({
3332
4263
  id: task,
3333
4264
  token
3334
4265
  }).then(() => "released");
3335
- if (result.kind === "quota" || result.kind === "auth") return run.team.taskFail({
4266
+ if (result$1.kind === "quota" || result$1.kind === "auth") return run.team.taskFail({
3336
4267
  id: task,
3337
4268
  token,
3338
- reason: `the agent stopped on ${result.kind === "quota" ? "a usage limit" : "a sign-in error"}: ${result.parsed.error ?? "see its log"}`.slice(0, 900),
4269
+ reason: `the agent stopped on ${result$1.kind === "quota" ? "a usage limit" : "a sign-in error"}: ${result$1.parsed.error ?? "see its log"}`.slice(0, 900),
3339
4270
  counts: false
3340
4271
  }).then(() => "failed");
3341
- const why$1 = result.kind === "timeout" ? "the agent ran out of time" : result.kind === "ok" ? "the agent ended without settling the task" : `the agent ended early (${result.kind}${result.code !== null ? `, exit ${result.code}` : ""})`;
4272
+ const why$1 = result$1.kind === "timeout" ? "the agent ran out of time" : result$1.kind === "ok" ? "the agent ended without settling the task" : `the agent ended early (${result$1.kind}${result$1.code !== null ? `, exit ${result$1.code}` : ""})`;
3342
4273
  return run.team.taskFail({
3343
4274
  id: task,
3344
4275
  token,
@@ -3349,13 +4280,13 @@ async function runAgent(run, parsed, onKind, onCost) {
3349
4280
  }
3350
4281
  dropClaim(me, task);
3351
4282
  const labels = {};
3352
- if (result.parsed.costUsd !== void 0) labels.cost = result.parsed.costUsd.toFixed(4);
3353
- if (result.parsed.usage) labels.tokens = String(result.parsed.usage.input + result.parsed.usage.output);
3354
- if (result.parsed.sessionId && result.kind !== "bad_resume") {
3355
- labels.session = result.parsed.sessionId;
4283
+ if (result$1.parsed.costUsd !== void 0) labels.cost = result$1.parsed.costUsd.toFixed(4);
4284
+ if (result$1.parsed.usage) labels.tokens = String(result$1.parsed.usage.input + result$1.parsed.usage.output);
4285
+ if (result$1.parsed.sessionId && result$1.kind !== "bad_resume") {
4286
+ labels.session = result$1.parsed.sessionId;
3356
4287
  labels.agent = agent.name;
3357
4288
  }
3358
- if (result.kind === "bad_resume") await run.team.label({
4289
+ if (result$1.kind === "bad_resume") await run.team.label({
3359
4290
  id: task,
3360
4291
  unset: ["session", "agent"]
3361
4292
  }).catch(() => {});
@@ -3366,19 +4297,19 @@ async function runAgent(run, parsed, onKind, onCost) {
3366
4297
  print(run, {
3367
4298
  task,
3368
4299
  outcome,
3369
- kind: result.kind,
3370
- code: result.code,
3371
- ...result.parsed.sessionId ? { session: result.parsed.sessionId } : {},
3372
- ...result.parsed.costUsd !== void 0 ? { cost: result.parsed.costUsd } : {},
3373
- ...result.parsed.usage ? { tokens: result.parsed.usage } : {},
3374
- log: result.stdoutPath,
4300
+ kind: result$1.kind,
4301
+ code: result$1.code,
4302
+ ...result$1.parsed.sessionId ? { session: result$1.parsed.sessionId } : {},
4303
+ ...result$1.parsed.costUsd !== void 0 ? { cost: result$1.parsed.costUsd } : {},
4304
+ ...result$1.parsed.usage ? { tokens: result$1.parsed.usage } : {},
4305
+ log: result$1.stdoutPath,
3375
4306
  ...lost ? { lost: true } : {}
3376
4307
  }, () => [
3377
- `${outcome} #${task} ${agent.name} ${result.kind}`,
4308
+ `${outcome} #${task} ${agent.name} ${result$1.kind}`,
3378
4309
  ...labels.cost ? [`cost $${labels.cost}`] : [],
3379
- `log ${result.stdoutPath}`
4310
+ `log ${result$1.stdoutPath}`
3380
4311
  ].join("\n"));
3381
- if (result.kind === "stopped") return stopCode(run.io.stop);
4312
+ if (result$1.kind === "stopped") return stopCode(run.io.stop);
3382
4313
  return outcome === "completed" ? 0 : 1;
3383
4314
  }
3384
4315
  /**
@@ -3841,12 +4772,12 @@ async function heldUnpushed(run, task, failure) {
3841
4772
  }).catch(() => {});
3842
4773
  const channel = (await run.team.readThread({ id: task }).catch(() => null))?.message.channel;
3843
4774
  if (!channel) return;
3844
- const { tasks: tasks$1 } = await run.team.taskList({
4775
+ const { tasks: tasks$2 } = await run.team.taskList({
3845
4776
  channel,
3846
4777
  state: "open",
3847
4778
  limit: 1e3
3848
4779
  }).catch(() => ({ tasks: [] }));
3849
- for (const next of tasks$1) {
4780
+ for (const next of tasks$2) {
3850
4781
  if (!next.needs.includes(task) || next.state !== "ready" && next.state !== "waiting") continue;
3851
4782
  await run.team.as(null).taskBlock({
3852
4783
  id: next.id,
@@ -4042,6 +4973,7 @@ function fail(io, json, error$1) {
4042
4973
  if (json) io.err(JSON.stringify({ error: error$1.toJSON() }, null, 2));
4043
4974
  else {
4044
4975
  const lines = [`error: ${error$1.message}`];
4976
+ if (error$1.cause instanceof Error) lines.push(`why: ${error$1.cause.message}`);
4045
4977
  const ways = [...error$1.hint ? [error$1.hint] : [], ...error$1.next].slice(0, 2);
4046
4978
  if (ways.length) lines.push("", ...ways.map((way) => ` ${way}`));
4047
4979
  io.err(lines.join("\n"));
@@ -4085,9 +5017,15 @@ function meantCommand(name, names) {
4085
5017
  return near && near[1] <= Math.min(2, Math.floor(name.length / 2)) ? near[0] : void 0;
4086
5018
  }
4087
5019
  /** Runs one command and returns its exit code. Everything goes through a handle from `board()`. */
4088
- async function main(argv, io) {
5020
+ async function main(argv, given) {
4089
5021
  const own = argv.includes("--") ? argv.slice(0, argv.indexOf("--")) : argv;
4090
5022
  const json = own.includes("--json");
5023
+ const shown = json ? jsonText : terminalText;
5024
+ const io = {
5025
+ ...given,
5026
+ out: (text) => given.out(shown(text)),
5027
+ err: (text) => given.err(shown(text))
5028
+ };
4091
5029
  const name = argv[0];
4092
5030
  if (name === void 0 || name === "--help") {
4093
5031
  io.out(HELP);
@@ -4299,23 +5237,13 @@ async function dispatch(name, command, parsed, io, json) {
4299
5237
  }),
4300
5238
  as: null
4301
5239
  });
4302
- else if (url) {
4303
- const token = io.env.MUSTER_TOKEN;
4304
- if (!token) throw new Failure("unauthorized", `The board at ${url} needs a token.`, { hint: "Set MUSTER_TOKEN to one from mu token create." });
4305
- team = board({
4306
- backend: http({
4307
- url,
4308
- token,
4309
- ...insecure ? { insecure } : {}
4310
- }),
4311
- as: as ?? null
4312
- });
4313
- } else team = board({
4314
- backend: file({
4315
- ...dir ? { dir } : {},
4316
- ...boardName ? { name: boardName } : {}
4317
- }),
4318
- as: as ?? null
5240
+ else team = openBoard({
5241
+ url,
5242
+ token: io.env.MUSTER_TOKEN,
5243
+ insecure,
5244
+ dir,
5245
+ name: boardName,
5246
+ as
4319
5247
  });
4320
5248
  const go = async () => {
4321
5249
  const code = await command.run({
@@ -4342,4 +5270,4 @@ const SPECS = {
4342
5270
  };
4343
5271
 
4344
5272
  //#endregion
4345
- export { main as a, answer as c, attend as i, mcp as l, agentPrompt as n, meantCommand as o, agentToken as r, repoUrl as s, SPECS as t, refusal$1 as u };
5273
+ export { main as a, MODERN as c, mcp as d, refusal$1 as f, attend as i, answer as l, agentPrompt as n, meantCommand as o, waits as p, agentToken as r, repoUrl as s, SPECS as t, headerProblem as u };