@tablation/crew 0.149.4 → 0.149.6

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 (2) hide show
  1. package/dist/cli.js +214 -143
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -15993,6 +15993,56 @@ function doctorSelftestLines(stored, toolchains) {
15993
15993
  });
15994
15994
  }
15995
15995
 
15996
+ // src/self-launch-check.ts
15997
+ import { spawn as spawn8 } from "child_process";
15998
+ var SELF_LAUNCH_TIMEOUT_MS = 15e3;
15999
+ function selfLaunchVerdict(child, own) {
16000
+ const printed = `${child.stdout}${child.stderr}`.trim();
16001
+ const fail2 = (why) => ({ ok: false, message: `self-launch failed: ${why}${printed ? `
16002
+ child printed:
16003
+ ${printed}` : ""}` });
16004
+ if (child.timedOut) return fail2("the child did not finish in time");
16005
+ if (child.code !== 0) return fail2(`the child exited ${child.code === null ? "on a signal" : child.code}`);
16006
+ let parsed;
16007
+ try {
16008
+ parsed = JSON.parse(child.stdout);
16009
+ } catch {
16010
+ return fail2("the child did not print a JSON object");
16011
+ }
16012
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return fail2("the child did not print a JSON object");
16013
+ const obj = parsed;
16014
+ if (obj.version !== own.version) return fail2(`the child reports version ${JSON.stringify(obj.version)}, this process is ${own.version}`);
16015
+ if (obj.compiled !== own.compiled) return fail2(`the child reports compiled ${JSON.stringify(obj.compiled)}, this process is ${own.compiled}`);
16016
+ return { ok: true, message: `self-launch ok: ${own.version}${own.compiled ? " (compiled)" : ""}` };
16017
+ }
16018
+ var spawnChild = (launch, args, timeoutMs) => new Promise((resolve8) => {
16019
+ const child = spawn8(launch.command, [...launch.args, ...args], { stdio: ["ignore", "pipe", "pipe"] });
16020
+ let stdout = "";
16021
+ let stderr = "";
16022
+ let timedOut = false;
16023
+ const timer = setTimeout(() => {
16024
+ timedOut = true;
16025
+ child.kill("SIGKILL");
16026
+ }, timeoutMs);
16027
+ child.stdout.on("data", (d) => {
16028
+ stdout += d.toString("utf8");
16029
+ });
16030
+ child.stderr.on("data", (d) => {
16031
+ stderr += d.toString("utf8");
16032
+ });
16033
+ child.on("error", (e) => {
16034
+ clearTimeout(timer);
16035
+ resolve8({ code: null, stdout, stderr: `${stderr}${e.message}`, timedOut });
16036
+ });
16037
+ child.on("close", (code) => {
16038
+ clearTimeout(timer);
16039
+ resolve8({ code, stdout, stderr, timedOut });
16040
+ });
16041
+ });
16042
+ async function runSelfLaunchCheck(own, spawnFn = spawnChild, launch = selfLaunch(), timeoutMs = SELF_LAUNCH_TIMEOUT_MS) {
16043
+ return selfLaunchVerdict(await spawnFn(launch, ["--version", "--json"], timeoutMs), own);
16044
+ }
16045
+
15996
16046
  // src/cli.ts
15997
16047
  import { resolve as resolve7, dirname as dirname37, join as join64, basename as basename17 } from "path";
15998
16048
  import { fileURLToPath as fileURLToPath2 } from "url";
@@ -23504,7 +23554,7 @@ async function runFleetPass(o) {
23504
23554
  }
23505
23555
  }
23506
23556
  async function fillSlots(o, routes, first) {
23507
- const spawn13 = o.spawnRoleAgent ?? runRoleAgent;
23557
+ const spawn14 = o.spawnRoleAgent ?? runRoleAgent;
23508
23558
  const breaker = o.spawnBreaker ?? new SpawnBreaker();
23509
23559
  const fleet = routes.length > 1;
23510
23560
  const rankOf = (c) => c.decision.selection.ranks[c.role] ?? Number.POSITIVE_INFINITY;
@@ -23548,7 +23598,7 @@ async function fillSlots(o, routes, first) {
23548
23598
  settle = resolve8;
23549
23599
  });
23550
23600
  const ready = (tookTicket2) => settle(tookTicket2);
23551
- const run4 = spawn13(role, decision, ctx, { ready }).then(() => {
23601
+ const run4 = spawn14(role, decision, ctx, { ready }).then(() => {
23552
23602
  breaker.recordSuccess(role);
23553
23603
  clearShipAttention(state, `role_parked:${role}`);
23554
23604
  clearShipAttention(state, workspaceAuthKey(role));
@@ -26181,7 +26231,7 @@ function existingRepoConfig(f) {
26181
26231
  }
26182
26232
 
26183
26233
  // src/repos-hooks-agent.ts
26184
- import { spawn as spawn8, execFileSync as execFileSync15 } from "child_process";
26234
+ import { spawn as spawn9, execFileSync as execFileSync15 } from "child_process";
26185
26235
  import { realpathSync as realpathSync2 } from "fs";
26186
26236
  import { isAbsolute as isAbsolute3, relative } from "path";
26187
26237
  var AgentSuggestError = class extends Error {
@@ -26302,7 +26352,7 @@ async function runAgentSuggest(o) {
26302
26352
  const run4 = await new Promise((resolve8) => {
26303
26353
  let out = "";
26304
26354
  let err3 = "";
26305
- const child = spawn8(bin, args, { cwd: o.dir, env, detached: true, stdio: ["pipe", "pipe", "pipe"] });
26355
+ const child = spawn9(bin, args, { cwd: o.dir, env, detached: true, stdio: ["pipe", "pipe", "pipe"] });
26306
26356
  let settled = false;
26307
26357
  const settle = (r) => {
26308
26358
  if (settled) return;
@@ -26855,7 +26905,7 @@ import { dirname as dirOf2, resolve as resolvePath } from "path";
26855
26905
  import { existsSync as existsSync56, readdirSync as readdirSync18, statSync as statSync17 } from "fs";
26856
26906
  import { join as join58 } from "path";
26857
26907
  function builtVersion() {
26858
- return true ? "0.149.4" : null;
26908
+ return true ? "0.149.6" : null;
26859
26909
  }
26860
26910
  var REBUILD_HINT = "rebuild with npm run build";
26861
26911
  function newestMtime(path) {
@@ -26894,23 +26944,74 @@ function statSafe(p) {
26894
26944
  }
26895
26945
 
26896
26946
  // src/relay-probe.ts
26897
- async function probeRelayControl(relayUrl, apiKey, userAgent, fetchFn = fetch, timeoutMs = 1e4) {
26898
- const started = Date.now();
26947
+ var LIVENESS_TIMEOUT_MS = 1e4;
26948
+ var STATUS_TIMEOUT_MS = 75e3;
26949
+ var BODY_LIMIT = 4096;
26950
+ async function boundedText(res) {
26899
26951
  try {
26900
- const res = await fetchFn(`${relayUrl.replace(/\/+$/, "")}/control/status`, {
26901
- headers: { Authorization: `Bearer ${apiKey}`, "User-Agent": userAgent },
26902
- signal: AbortSignal.timeout(timeoutMs)
26903
- });
26904
- const latencyMs = Date.now() - started;
26905
- await res.arrayBuffer().catch(() => void 0);
26906
- if (res.ok) return { ok: true, status: res.status, latencyMs };
26907
- return { ok: false, status: res.status, error: `HTTP ${res.status}` };
26908
- } catch (e) {
26909
- return { ok: false, error: e.message };
26952
+ return (await res.text()).slice(0, BODY_LIMIT);
26953
+ } catch {
26954
+ return "";
26955
+ }
26956
+ }
26957
+ function parseObject(text2) {
26958
+ try {
26959
+ const v = JSON.parse(text2);
26960
+ return v && typeof v === "object" && !Array.isArray(v) ? v : null;
26961
+ } catch {
26962
+ return null;
26910
26963
  }
26911
26964
  }
26965
+ var oneLine2 = (s, max = 200) => s.replace(/\s+/g, " ").trim().slice(0, max);
26966
+ function classify2(res, text2, step) {
26967
+ const status2 = res.status;
26968
+ if (status2 === 401 || status2 === 403) {
26969
+ return { ok: false, kind: "key_refused", status: status2, error: `the ship's control API refused this route's key (HTTP ${status2})`, remedy: "run `crew connect <route>` to mint and store a key the ship accepts" };
26970
+ }
26971
+ const body = parseObject(text2);
26972
+ if (body && typeof body.reason === "string") {
26973
+ const detail = typeof body.detail === "string" ? `: ${oneLine2(body.detail, 400)}` : "";
26974
+ return { ok: false, kind: "status_failed", status: status2, error: `the ship could not build its status document (${body.reason}${detail})`, remedy: "run `crew status <route> --json` on the ship to see the error" };
26975
+ }
26976
+ if (status2 >= 500 && !body) {
26977
+ const said = oneLine2(text2, 80);
26978
+ return { ok: false, kind: "tunnel_down", status: status2, error: `the relay could not reach the ship's tunnel (HTTP ${status2}${said ? `, "${said}"` : ""})`, remedy: "run `crew passengers` and check the tunnel state doctor prints above" };
26979
+ }
26980
+ return { ok: false, kind: "http", status: status2, error: `HTTP ${status2}${step === "status" ? " from /control/status" : ""}` };
26981
+ }
26982
+ async function probeRelayControl(relayUrl, apiKey, userAgent, fetchFn = fetch, livenessTimeoutMs = LIVENESS_TIMEOUT_MS, statusTimeoutMs = STATUS_TIMEOUT_MS) {
26983
+ const base = relayUrl.replace(/\/+$/, "");
26984
+ const headers = { Authorization: `Bearer ${apiKey}`, "User-Agent": userAgent };
26985
+ const step = async (path, timeoutMs, which) => {
26986
+ const started = Date.now();
26987
+ try {
26988
+ const res = await fetchFn(`${base}${path}`, { headers, signal: AbortSignal.timeout(timeoutMs) });
26989
+ const text2 = await boundedText(res);
26990
+ const latencyMs = Date.now() - started;
26991
+ if (res.ok) {
26992
+ const route2 = parseObject(text2)?.route;
26993
+ return { ok: true, status: res.status, latencyMs, route: typeof route2 === "string" ? route2 : void 0 };
26994
+ }
26995
+ return classify2(res, text2, which);
26996
+ } catch (e) {
26997
+ const name = e.name;
26998
+ if (name === "TimeoutError" || name === "AbortError") {
26999
+ return { ok: false, kind: "timed_out", error: `no answer from ${path} after ${Math.round((Date.now() - started) / 1e3)}s` };
27000
+ }
27001
+ return { ok: false, kind: "network", error: e.message };
27002
+ }
27003
+ };
27004
+ const live2 = await step("/control/streams", livenessTimeoutMs, "liveness");
27005
+ if (!live2.ok) return live2;
27006
+ const status2 = await step("/control/status", statusTimeoutMs, "status");
27007
+ return status2.ok ? { ...status2, latencyMs: live2.latencyMs + status2.latencyMs } : status2;
27008
+ }
26912
27009
  function describeRelayProbe(url, p) {
26913
- return p.ok ? `relay control: OK ${url}/control/status (${p.status}, ${p.latencyMs} ms)` : `relay control: FAILED ${url}/control/status \u2014 ${p.error}`;
27010
+ if (p.ok) {
27011
+ return `relay control: OK ${url}/control/status (${p.status}, ${p.latencyMs} ms${p.route ? `, route ${p.route}` : ""})`;
27012
+ }
27013
+ return `relay control: FAILED ${url}/control/status \u2014 ${p.error}${p.remedy ? `
27014
+ fix: ${p.remedy}` : ""}`;
26914
27015
  }
26915
27016
 
26916
27017
  // src/ship-status.ts
@@ -27043,7 +27144,7 @@ async function unregisterEndpoint(workspaceId, info, d) {
27043
27144
 
27044
27145
  // src/passenger-sync-daemon.ts
27045
27146
  import { createServer as createHttpServer } from "http";
27046
- import { spawn as spawn9 } from "child_process";
27147
+ import { spawn as spawn10 } from "child_process";
27047
27148
  import { randomBytes as randomBytes2 } from "crypto";
27048
27149
  import { existsSync as existsSync57, mkdirSync as mkdirSync40, readFileSync as readFileSync54, writeFileSync as writeFileSync42, unlinkSync as unlinkSync5, readdirSync as readdirSync19 } from "fs";
27049
27150
  import { join as join59 } from "path";
@@ -27134,7 +27235,7 @@ function runSyncDaemonFromEnv(env = process.env) {
27134
27235
  return server;
27135
27236
  }
27136
27237
  var defaultSpawn2 = (cmd, args, env) => {
27137
- const child = spawn9(cmd, args, { detached: true, stdio: "ignore", env });
27238
+ const child = spawn10(cmd, args, { detached: true, stdio: "ignore", env });
27138
27239
  child.unref();
27139
27240
  return child;
27140
27241
  };
@@ -27232,7 +27333,7 @@ function syncPassengerSyncDaemons(plans, cfg, stateDir, deps = {}) {
27232
27333
  }
27233
27334
 
27234
27335
  // src/periscope-proxy.ts
27235
- import { spawn as spawn10 } from "child_process";
27336
+ import { spawn as spawn11 } from "child_process";
27236
27337
  import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync41 } from "fs";
27237
27338
  import { createServer, request as httpRequest } from "http";
27238
27339
  import { request as httpsRequest } from "https";
@@ -27587,7 +27688,7 @@ async function launchProxy(invocation, worktree, previewUrl, number, o) {
27587
27688
  if (stale.length) await killGently(stale);
27588
27689
  const launch = { worktree, target: previewUrl, host: o.host, port, inject: o.inject };
27589
27690
  const [cmd, ...args] = invocation;
27590
- const child = spawn10(cmd, [...args, "periscope-proxy", pointedAtFile(worktree)], {
27691
+ const child = spawn11(cmd, [...args, "periscope-proxy", pointedAtFile(worktree)], {
27591
27692
  detached: true,
27592
27693
  stdio: "ignore",
27593
27694
  cwd: worktree,
@@ -27680,10 +27781,10 @@ import {
27680
27781
  import { createConnection } from "net";
27681
27782
  import { createServer as createServer2 } from "http";
27682
27783
  import { basename as basename15, dirname as dirname35, join as join61 } from "path";
27683
- import { execFile as execFile6, spawn as spawn12 } from "child_process";
27784
+ import { execFile as execFile6, spawn as spawn13 } from "child_process";
27684
27785
 
27685
27786
  // src/periscope-control.ts
27686
- import { spawn as spawn11 } from "child_process";
27787
+ import { spawn as spawn12 } from "child_process";
27687
27788
  var reply = (status2, body) => ({ status: status2, body });
27688
27789
  var err = (status2, message) => reply(status2, { error: message });
27689
27790
  var TICKET_RE = /^(?:[A-Za-z]+-)?\d+$/;
@@ -27883,7 +27984,7 @@ async function handlePeriscopes(h, q2) {
27883
27984
  function runCrew(args, onLine, timeoutMs = 20 * 6e4) {
27884
27985
  return new Promise((resolve8) => {
27885
27986
  const self = selfLaunch();
27886
- const child = spawn11(self.command, [...self.args, ...args], { stdio: ["ignore", "pipe", "pipe"] });
27987
+ const child = spawn12(self.command, [...self.args, ...args], { stdio: ["ignore", "pipe", "pipe"] });
27887
27988
  let stdout = "";
27888
27989
  let stderr = "";
27889
27990
  let pending = "";
@@ -28118,6 +28219,14 @@ function waitForChange(dir, ms3, signal) {
28118
28219
  }
28119
28220
  var reply2 = (status2, body) => ({ status: status2, body });
28120
28221
  var err2 = (status2, message) => reply2(status2, { error: message });
28222
+ function failureReply(what, f, log) {
28223
+ log?.(`control API: could not produce the ${what} document: ${f.reason}: ${f.detail}`);
28224
+ return reply2(502, {
28225
+ error: `could not produce the ${what === "status" ? "status document" : "doctor report"}`,
28226
+ reason: f.reason,
28227
+ detail: f.detail
28228
+ });
28229
+ }
28121
28230
  function pauseDoc(state) {
28122
28231
  return {
28123
28232
  crew: state.isPaused(),
@@ -28236,10 +28345,11 @@ async function route(deps, method, url, req, abort) {
28236
28345
  });
28237
28346
  }
28238
28347
  if (p === "/status" && get2) {
28239
- const doc = await deps.status();
28240
- if (!doc) return err2(502, "could not produce the status document");
28348
+ const out = await deps.status();
28349
+ if (!out.ok) return failureReply("status", out, deps.log);
28241
28350
  return reply2(200, {
28242
- ...doc,
28351
+ ...out.doc,
28352
+ ...deps.route ? { route: deps.route } : {},
28243
28353
  daemon: {
28244
28354
  alive: true,
28245
28355
  pid: process.pid,
@@ -28281,8 +28391,8 @@ async function route(deps, method, url, req, abort) {
28281
28391
  return r.accepted ? reply2(202, { accepted: true, detail: r.detail }) : err2(409, r.detail);
28282
28392
  }
28283
28393
  if (p === "/doctor" && get2) {
28284
- const doc = await deps.doctor();
28285
- return doc ? reply2(200, doc) : err2(502, "could not produce the doctor report");
28394
+ const out = await deps.doctor();
28395
+ return out.ok ? reply2(200, out.doc) : failureReply("doctor", out, deps.log);
28286
28396
  }
28287
28397
  if (p === "/diagnostics" && get2 && deps.diagnostics) return reply2(200, await deps.diagnostics());
28288
28398
  const known = ["/status", "/events", "/streams", "/pause", "/resume", "/release/pause", "/release/resume", "/doctor", ...deps.diagnostics ? ["/diagnostics"] : []];
@@ -28378,7 +28488,7 @@ async function startControlServer(deps) {
28378
28488
  });
28379
28489
  }
28380
28490
  var shq2 = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
28381
- function runDetached(commands, spawnFn = spawn12) {
28491
+ function runDetached(commands, spawnFn = spawn13) {
28382
28492
  const script = `sleep 1; ${commands.map((c) => c.map(shq2).join(" ")).join("; ")}`;
28383
28493
  const child = spawnFn("/bin/sh", ["-c", script], { detached: true, stdio: "ignore" });
28384
28494
  child.on("error", () => {
@@ -28394,16 +28504,28 @@ function schedulerHandler(control, run4 = runDetached) {
28394
28504
  return { accepted: true, detail: `${action} requested` };
28395
28505
  };
28396
28506
  }
28397
- function crewJson(args, timeoutMs = 6e4) {
28507
+ var CREW_JSON_TIMEOUT_MS = 6e4;
28508
+ function stderrTail(stderr, lines2 = 5, maxChars = 600) {
28509
+ const tail3 = stderr.trim().split("\n").slice(-lines2).join("\n").replace(/\bsk_[A-Za-z0-9_-]+/g, "sk_***").replace(/(Bearer\s+)\S+/gi, "$1***");
28510
+ return tail3.length > maxChars ? `\u2026${tail3.slice(-maxChars)}` : tail3;
28511
+ }
28512
+ function crewJson(args, timeoutMs = CREW_JSON_TIMEOUT_MS) {
28398
28513
  return new Promise((resolve8) => {
28399
28514
  const self = selfLaunch();
28400
- execFile6(self.command, [...self.args, ...args], { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 }, (_e, stdout) => {
28515
+ execFile6(self.command, [...self.args, ...args], { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 }, (e, stdout, stderr) => {
28401
28516
  try {
28402
28517
  const v = JSON.parse(String(stdout));
28403
- resolve8(v && typeof v === "object" && !Array.isArray(v) ? v : null);
28518
+ if (v && typeof v === "object" && !Array.isArray(v)) return resolve8({ ok: true, doc: v });
28404
28519
  } catch {
28405
- resolve8(null);
28406
28520
  }
28521
+ const ex = e;
28522
+ const tail3 = stderrTail(String(stderr ?? ""));
28523
+ if (ex?.killed || ex?.code === "ETIMEDOUT") return resolve8({ ok: false, reason: "timed_out", detail: `no JSON within ${Math.round(timeoutMs / 1e3)}s${tail3 ? `; stderr: ${tail3}` : ""}` });
28524
+ if (ex) {
28525
+ const how = typeof ex.code === "number" ? `exit code ${ex.code}` : ex.signal ? `signal ${ex.signal}` : `error ${String(ex.code ?? ex.message)}`;
28526
+ return resolve8({ ok: false, reason: "exited", detail: `${how}${tail3 ? `; stderr: ${tail3}` : ""}` });
28527
+ }
28528
+ resolve8({ ok: false, reason: "bad_output", detail: `exit 0 but stdout is not a JSON object (${String(stdout).length} bytes)${tail3 ? `; stderr: ${tail3}` : ""}` });
28407
28529
  });
28408
28530
  });
28409
28531
  }
@@ -29076,6 +29198,12 @@ if (versionReq) {
29076
29198
  `);
29077
29199
  process.exit(0);
29078
29200
  }
29201
+ if (argv[0] === "self-launch-check") {
29202
+ const verdict = await runSelfLaunchCheck({ version: crewVersion(CREW_HOME), compiled: isCompiledBinary(import.meta.url) });
29203
+ (verdict.ok ? process.stdout : process.stderr).write(`${verdict.message}
29204
+ `);
29205
+ process.exit(verdict.ok ? 0 : 1);
29206
+ }
29079
29207
  var staleBundle = bundleStaleness({ built: builtVersion(), current: crewVersion(CREW_HOME), home: CREW_HOME, compiled: isCompiledBinary(import.meta.url) });
29080
29208
  if (staleBundle) process.stderr.write(`crew: warning: ${staleBundle.message}
29081
29209
  `);
@@ -29249,7 +29377,10 @@ if (command === "passenger-sync-daemon") {
29249
29377
  }
29250
29378
  await runBridge(stateDir, bridgeRoute, bridgeTicket);
29251
29379
  } else {
29252
- let die = function(command2, message, fix, code = 2) {
29380
+ let routineLine = function(line) {
29381
+ if (flag("verbose")) process.stderr.write(`${line}
29382
+ `);
29383
+ }, die = function(command2, message, fix, code = 2) {
29253
29384
  emit.error(withFix(`${command2}: ${message}`, fix));
29254
29385
  return process.exit(code);
29255
29386
  }, requireArmed = function(what) {
@@ -29451,7 +29582,7 @@ if (command === "passenger-sync-daemon") {
29451
29582
  }
29452
29583
  };
29453
29584
  };
29454
- die2 = die, requireArmed2 = requireArmed, parseTicketNumber2 = parseTicketNumber, routeRelayUrl2 = routeRelayUrl, previewRelayFor2 = previewRelayFor, passengerApiKeys2 = passengerApiKeys, endpointApiFor2 = endpointApiFor, periscopeEndpointDeps2 = periscopeEndpointDeps, periscopeMcpDeps2 = periscopeMcpDeps, endpointReconcileDeps2 = endpointReconcileDeps, releaseRefused2 = releaseRefused, doctorMachineId2 = doctorMachineId, baseHealth2 = baseHealth, sandboxCacheRepos2 = sandboxCacheRepos, buildSandboxCachePass2 = buildSandboxCachePass, sandboxTickDeps2 = sandboxTickDeps;
29585
+ routineLine2 = routineLine, die2 = die, requireArmed2 = requireArmed, parseTicketNumber2 = parseTicketNumber, routeRelayUrl2 = routeRelayUrl, previewRelayFor2 = previewRelayFor, passengerApiKeys2 = passengerApiKeys, endpointApiFor2 = endpointApiFor, periscopeEndpointDeps2 = periscopeEndpointDeps, periscopeMcpDeps2 = periscopeMcpDeps, endpointReconcileDeps2 = endpointReconcileDeps, releaseRefused2 = releaseRefused, doctorMachineId2 = doctorMachineId, baseHealth2 = baseHealth, sandboxCacheRepos2 = sandboxCacheRepos, buildSandboxCachePass2 = buildSandboxCachePass, sandboxTickDeps2 = sandboxTickDeps;
29455
29586
  async function failDaemonStart(o) {
29456
29587
  const failEmit = new Emitter({
29457
29588
  route: "",
@@ -29823,11 +29954,7 @@ if (command === "passenger-sync-daemon") {
29823
29954
  const targets = reposOf(route2);
29824
29955
  const chosen = only ? targets.filter((t) => t.name === only) : targets;
29825
29956
  if (only && chosen.length === 0) {
29826
- process.stderr.write(
29827
- `crew: no repo named "${only}" on route "${route2.route}" (have: ${targets.map((t) => t.name).join(", ")})
29828
- `
29829
- );
29830
- process.exit(2);
29957
+ die("crew", `no repo named "${only}" on route "${route2.route}" (have: ${targets.map((t) => t.name).join(", ")})`, `\`crew repos\` to list or add one`);
29831
29958
  }
29832
29959
  const summaries = [];
29833
29960
  if (!dryRun) state.releaseHeartbeat().touch();
@@ -30824,10 +30951,7 @@ ${f.tail.trimEnd()}
30824
30951
  if (EXCLUSIVE[command] && !dryRun) {
30825
30952
  const got = state.acquire(EXCLUSIVE[command]);
30826
30953
  if (!got.ok) {
30827
- process.stderr.write(
30828
- `crew: a previous ${command} (pid ${got.heldBy}) is still running \u2014 skipping this cycle
30829
- `
30830
- );
30954
+ emit.note(`a previous ${command} (pid ${got.heldBy}) is still running \u2014 skipping this cycle`);
30831
30955
  process.exit(0);
30832
30956
  }
30833
30957
  lock = got;
@@ -31580,6 +31704,7 @@ ${f.tail.trimEnd()}
31580
31704
  }
31581
31705
  },
31582
31706
  periscopeMcp: controlRoutes.some((r) => r.enabled && r.hostPeriscopes) ? (req, res, ticket) => handlePeriscopeMcp(periscopeMcpDeps(), req, res, ticket) : void 0,
31707
+ route: primary.route,
31583
31708
  status: () => crewJson(["status", primary.route, "--json"]),
31584
31709
  doctor: () => crewJson(["doctor", primary.route, "--json", "--offline"]),
31585
31710
  diagnostics: () => collectDiagnostics({
@@ -31588,7 +31713,10 @@ ${f.tail.trimEnd()}
31588
31713
  runner: cfg.ship.runner ?? "host",
31589
31714
  unitStems: detectSystemd() ? ["run", "release", "passengers"].map((j) => labelFor(CREW_HOME, j)) : [],
31590
31715
  userScope: process.getuid?.() !== 0,
31591
- doctor: () => crewJson(["doctor", primary.route, "--json", "--offline"])
31716
+ doctor: async () => {
31717
+ const o = await crewJson(["doctor", primary.route, "--json", "--offline"]);
31718
+ return o.ok ? o.doc : null;
31719
+ }
31592
31720
  }),
31593
31721
  scheduler: schedulerHandler(planDaemonControl(CREW_HOME, hostPlatform(), detectSystemd())),
31594
31722
  log: (m) => emit.warn(m)
@@ -31743,9 +31871,7 @@ ${f.tail.trimEnd()}
31743
31871
  process.stdout.write(prompt + (role === "pair" ? harnessPromptNote(value("harness")) : ""));
31744
31872
  } catch (e) {
31745
31873
  if (e instanceof AgentsSyncError) {
31746
- process.stderr.write(`crew agents prompt: ${e.message}
31747
- `);
31748
- process.exit(2);
31874
+ die("crew agents prompt", e.message, "`crew doctor`", 2);
31749
31875
  }
31750
31876
  throw e;
31751
31877
  }
@@ -31852,9 +31978,7 @@ ${f.tail.trimEnd()}
31852
31978
  newName = validateShipName(positional[2]);
31853
31979
  } catch (e) {
31854
31980
  if (e instanceof ShipNameError) {
31855
- process.stderr.write(`crew ship: ${e.message}
31856
- `);
31857
- process.exit(2);
31981
+ die("crew ship", e.message, "`crew doctor`", 2);
31858
31982
  }
31859
31983
  throw e;
31860
31984
  }
@@ -31926,9 +32050,7 @@ ${f.tail.trimEnd()}
31926
32050
  });
31927
32051
  } catch (e) {
31928
32052
  if (e instanceof ReposError) {
31929
- process.stderr.write(`crew repos: ${e.message}
31930
- `);
31931
- process.exit(2);
32053
+ die("crew repos", e.message, "`crew doctor`", 2);
31932
32054
  }
31933
32055
  throw e;
31934
32056
  }
@@ -32043,9 +32165,7 @@ ${f.tail.trimEnd()}
32043
32165
  if (agentError) process.exitCode = 1;
32044
32166
  } catch (e) {
32045
32167
  if (e instanceof ReposError) {
32046
- process.stderr.write(`crew repos: ${e.message}
32047
- `);
32048
- process.exit(2);
32168
+ die("crew repos", e.message, "`crew doctor`", 2);
32049
32169
  }
32050
32170
  throw e;
32051
32171
  }
@@ -32063,9 +32183,7 @@ ${f.tail.trimEnd()}
32063
32183
  addName = a.name;
32064
32184
  } catch (e) {
32065
32185
  if (e instanceof ReposError) {
32066
- process.stderr.write(`crew repos: ${e.message}
32067
- `);
32068
- process.exit(2);
32186
+ die("crew repos", e.message, "`crew doctor`", 2);
32069
32187
  }
32070
32188
  throw e;
32071
32189
  }
@@ -32077,9 +32195,7 @@ ${f.tail.trimEnd()}
32077
32195
  addName = a.name;
32078
32196
  } catch (e) {
32079
32197
  if (e instanceof ReposError) {
32080
- process.stderr.write(`crew repos: ${e.message}
32081
- `);
32082
- process.exit(2);
32198
+ die("crew repos", e.message, "`crew doctor`", 2);
32083
32199
  }
32084
32200
  throw e;
32085
32201
  }
@@ -32241,9 +32357,7 @@ ${f.tail.trimEnd()}
32241
32357
  `);
32242
32358
  } catch (e) {
32243
32359
  if (e instanceof ReposError) {
32244
- process.stderr.write(`crew repos: ${e.message}
32245
- `);
32246
- process.exit(2);
32360
+ die("crew repos", e.message, "`crew doctor`", 2);
32247
32361
  }
32248
32362
  throw e;
32249
32363
  }
@@ -32328,9 +32442,7 @@ ${reconstruction.prompt}
32328
32442
  }
32329
32443
  } catch (e) {
32330
32444
  if (e instanceof LogbookError) {
32331
- process.stderr.write(`crew logbook: ${e.message}
32332
- `);
32333
- process.exit(2);
32445
+ die("crew logbook", e.message, "`crew doctor`", 2);
32334
32446
  }
32335
32447
  throw e;
32336
32448
  }
@@ -32402,8 +32514,7 @@ ${reconstruction.prompt}
32402
32514
  apiKey = existing.apiKey;
32403
32515
  keychainBacked = true;
32404
32516
  sessionAddress = found;
32405
- process.stderr.write(`Reusing the existing keychain session for ${hostFromUrl4(baseUrl)}/${workspace}.
32406
- `);
32517
+ routineLine(`Reusing the existing keychain session for ${hostFromUrl4(baseUrl)}/${workspace}.`);
32407
32518
  }
32408
32519
  } catch {
32409
32520
  }
@@ -32437,8 +32548,7 @@ ${reconstruction.prompt}
32437
32548
  keychainBacked = true;
32438
32549
  sessionAddress = resumed.workspace;
32439
32550
  signInSource = "keychain";
32440
- process.stderr.write(`Reusing the existing keychain session for ${hostFromUrl4(baseUrl)}/${workspace}.
32441
- `);
32551
+ routineLine(`Reusing the existing keychain session for ${hostFromUrl4(baseUrl)}/${workspace}.`);
32442
32552
  }
32443
32553
  }
32444
32554
  let mintedFromDevice = false;
@@ -32839,8 +32949,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
32839
32949
  mkdirSync43(dirname37(apiKeyFile), { recursive: true });
32840
32950
  writeFileSync44(apiKeyFile, `${apiKeyVar}=${apiKey}
32841
32951
  `, { mode: 384 });
32842
- process.stderr.write(`API key written to ${apiKeyFile}
32843
- `);
32952
+ routineLine(`API key written to ${apiKeyFile}`);
32844
32953
  }
32845
32954
  }
32846
32955
  const keyPersisted = keychainBacked || apiKeyFile !== void 0;
@@ -32889,14 +32998,12 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
32889
32998
  const mcpOpts = { bin: tc.bin, url: mcpUrl, key: apiKey, replace, dryRun, stateDir: cfg.ship.stateDir };
32890
32999
  const { line, action } = adapter.ensureMcpResult ? adapter.ensureMcpResult(mcpOpts) : { line: adapter.ensureMcp(mcpOpts), action: void 0 };
32891
33000
  connectEvents.emit("mcp_registered", line, { harness: tc.harness, bin: tc.bin, url: mcpUrl, ...action ? { action } : {} });
32892
- process.stderr.write(`${line}
32893
- `);
33001
+ routineLine(line);
32894
33002
  }
32895
33003
  for (const h of shipPair(cfg.ship).filter((x) => x !== "claude")) {
32896
33004
  const line = pairInstallerFor(h).installPair({ url: mcpUrlFor(baseUrl), replace, dryRun });
32897
33005
  connectEvents.emit("pair_installed", line, { harness: h });
32898
- process.stderr.write(`${line}
32899
- `);
33006
+ routineLine(line);
32900
33007
  }
32901
33008
  }
32902
33009
  if (found.holds.length) {
@@ -33046,8 +33153,8 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
33046
33153
  if (defaulted) {
33047
33154
  await runConnect(defaulted.slug, project);
33048
33155
  } else if (workspaces.length === 0) {
33049
- process.stderr.write("crew connect: this key's identity has no workspace memberships.\n");
33050
- stopWithProblem("this key's identity has no workspace memberships", "workspace");
33156
+ connectEvents.emit("problem", "this key's identity has no workspace memberships", { stage: "workspace" });
33157
+ die("crew connect", "this key's identity has no workspace memberships", "mint a key inside a workspace and re-run with `--key K`");
33051
33158
  } else if (workspaces.length === 1) {
33052
33159
  await runConnect(workspaces[0].slug, project);
33053
33160
  } else {
@@ -33072,18 +33179,13 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
33072
33179
  if (e instanceof ConnectHttpError) {
33073
33180
  connectEvents.emit("problem", e.message, { stage: "http", status: e.status, path: e.path });
33074
33181
  if (e.status === 401 || e.status === 403) {
33075
- process.stderr.write(
33076
- `crew connect: ${e.path} \u2014 ${e.status} ${e.status === 401 ? "(bad or expired key)" : "(this key is not a member of that workspace)"}
33077
- A key only sees the workspace it was minted in, whatever role it holds there
33078
- (platform admin included) \u2014 pass one minted inside the target workspace: --key K
33079
- (or CREW_CONNECT_KEY).
33080
- `
33182
+ die(
33183
+ "crew connect",
33184
+ `${e.path} \u2014 ${e.status} ${e.status === 401 ? "(bad or expired key)" : "(this key is not a member of that workspace)"}. A key only sees the workspace it was minted in, whatever role it holds there (platform admin included)`,
33185
+ "pass a key minted inside the target workspace: `--key K` (or CREW_CONNECT_KEY)"
33081
33186
  );
33082
- } else {
33083
- process.stderr.write(`crew connect: ${e.message}
33084
- `);
33085
33187
  }
33086
- process.exit(2);
33188
+ die("crew connect", e.message, "`crew doctor`");
33087
33189
  }
33088
33190
  throw e;
33089
33191
  }
@@ -33142,15 +33244,11 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
33142
33244
  const only = value("route");
33143
33245
  const wanted = only ? cfg.routes.filter((r2) => r2.route === only) : cfg.routes;
33144
33246
  if (wanted.length !== 1) {
33145
- process.stderr.write(`crew sandbox policy: ${only ? `no route "${only}"` : "name the route with --route"} (have: ${cfg.routes.map((r2) => r2.route).join(", ")})
33146
- `);
33147
- process.exit(2);
33247
+ die("crew sandbox policy", `${only ? `no route "${only}"` : "no route given"} (have: ${cfg.routes.map((r2) => r2.route).join(", ")})`, "`--route ROUTE`");
33148
33248
  }
33149
33249
  const role = value("role") ?? "dev";
33150
33250
  if (!ROLE_NAMES.includes(role)) {
33151
- process.stderr.write(`crew sandbox policy: --role must be one of ${ROLE_NAMES.join(", ")}
33152
- `);
33153
- process.exit(2);
33251
+ die("crew sandbox policy", `--role must be one of ${ROLE_NAMES.join(", ")}`, `\`--role ${ROLE_NAMES[0]}\``);
33154
33252
  }
33155
33253
  const r = wanted[0];
33156
33254
  const repoName = value("repo");
@@ -33161,9 +33259,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
33161
33259
  process.stdout.write(flag("json") ? `${JSON.stringify({ route: r.route, role, input, groups: policy.groups, yaml: policy.yaml }, null, 2)}
33162
33260
  ` : policy.yaml);
33163
33261
  } catch (e) {
33164
- process.stderr.write(`crew sandbox policy: ${e.message}
33165
- `);
33166
- process.exit(1);
33262
+ die("crew sandbox policy", e.message, "`crew doctor`", 1);
33167
33263
  }
33168
33264
  break;
33169
33265
  }
@@ -33369,18 +33465,10 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
33369
33465
  const repos = await resolvedRepos(route2);
33370
33466
  const candidates2 = repos.map((r) => ({ repo: r, found: worktreeForNumber(r.dir, n) })).filter((c) => c.found !== null);
33371
33467
  if (candidates2.length === 0) {
33372
- process.stderr.write(
33373
- `drop: no worktree for ISSUE-${n} in any of this route's repositories (looked in: ${repos.map((r) => r.dir).join(", ")})
33374
- `
33375
- );
33376
- process.exit(2);
33468
+ die("crew drop", `no worktree for ISSUE-${n} in any of this route's repositories (looked in: ${repos.map((r) => r.dir).join(", ")})`, "`git worktree list` in the repository");
33377
33469
  }
33378
33470
  if (candidates2.length > 1) {
33379
- process.stderr.write(
33380
- `drop: ISSUE-${n} has a worktree in more than one repository (${candidates2.map((c) => c.repo.name).join(", ")}) \u2014 remove them one at a time by path
33381
- `
33382
- );
33383
- process.exit(2);
33471
+ die("crew drop", `ISSUE-${n} has a worktree in more than one repository (${candidates2.map((c) => c.repo.name).join(", ")})`, "remove them one at a time by path");
33384
33472
  }
33385
33473
  const { repo: target, found } = candidates2[0];
33386
33474
  const wt = found.path;
@@ -33388,9 +33476,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
33388
33476
  const trD = new Tracker(route2, cfg.ship);
33389
33477
  const tD = (await trD.ticketsByNumbers([n])).find((t) => t.issue_id.replace(/^\D+/, "") === String(num2));
33390
33478
  if (tD && tD[trD.contract.columns.status] === trD.contract.statuses.draft) {
33391
- process.stderr.write(`drop: ${tD.issue_tag ?? tD.issue_id} is a draft ticket \u2014 its worktree belongs to a periscope; end it with \`crew periscope down ${num2} --keep\` or \`--discard\`
33392
- `);
33393
- process.exit(2);
33479
+ die("crew drop", `${tD.issue_tag ?? tD.issue_id} is a draft ticket \u2014 its worktree belongs to a periscope`, `\`crew periscope down ${num2} --keep\` or \`--discard\``);
33394
33480
  }
33395
33481
  } catch {
33396
33482
  }
@@ -33425,29 +33511,18 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
33425
33511
  case "rotate-passenger-url": {
33426
33512
  emit.enter("passengers");
33427
33513
  if (!route2.hostPassengers) {
33428
- process.stderr.write(
33429
- `crew rotate-passenger-url: route "${route2.route}" does not have hostPassengers enabled
33430
- `
33431
- );
33432
- process.exit(2);
33514
+ die("crew rotate-passenger-url", `route "${route2.route}" does not have hostPassengers enabled`, `set hostPassengers on the route in ${cfg.configFile}`);
33433
33515
  }
33434
33516
  if (!cfg.ship.relayHost) {
33435
- process.stderr.write("crew rotate-passenger-url: this ship has no relayHost configured \u2014 nothing to rotate\n");
33436
- process.exit(2);
33517
+ die("crew rotate-passenger-url", "this ship has no relayHost configured \u2014 nothing to rotate", `set ship.relayHost in ${cfg.configFile}`);
33437
33518
  }
33438
33519
  const workspaceId = route2.resolved?.workspaceId;
33439
33520
  if (!workspaceId) {
33440
- process.stderr.write(`crew rotate-passenger-url: route "${route2.route}" has no resolved ids \u2014 run \`crew connect\`
33441
- `);
33442
- process.exit(2);
33521
+ die("crew rotate-passenger-url", `route "${route2.route}" has no resolved ids`, "`crew connect`");
33443
33522
  }
33444
33523
  const plans = planContainers(cfg).filter((p) => p.workspaceId === workspaceId);
33445
33524
  if (!plans.length) {
33446
- process.stderr.write(
33447
- `crew rotate-passenger-url: no Host Passengers container is planned for "${route2.route}" right now
33448
- `
33449
- );
33450
- process.exit(2);
33525
+ die("crew rotate-passenger-url", `no Host Passengers container is planned for "${route2.route}" right now`, "`crew doctor`");
33451
33526
  }
33452
33527
  const existing = readPersistedTunnel(cfg.ship.stateDir, workspaceId);
33453
33528
  const hasLiveTunnel = existing !== void 0 && isPidAlive(existing.pid);
@@ -33746,9 +33821,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
33746
33821
  `);
33747
33822
  } catch (e) {
33748
33823
  if (e instanceof PeriscopeError || e instanceof ConfigError) {
33749
- process.stderr.write(`crew periscope: ${e.message}
33750
- `);
33751
- process.exit(1);
33824
+ die("crew periscope", e.message, "`crew doctor`", 1);
33752
33825
  }
33753
33826
  throw e;
33754
33827
  }
@@ -34024,9 +34097,7 @@ ${where.join("\n")}`);
34024
34097
  const open = await tracker3.openTickets();
34025
34098
  const ticket = open.find((t) => t[c.columns.key] === key);
34026
34099
  if (!ticket) {
34027
- process.stderr.write(`unassign: no open ticket ${key} on ${route2.route} (already resolved, or not this route's)
34028
- `);
34029
- process.exit(2);
34100
+ die("crew unassign", `no open ticket ${key} on ${route2.route} (already resolved, or not this route's)`, "`crew inbox` to list open tickets");
34030
34101
  }
34031
34102
  const label = displayKey(ticket);
34032
34103
  if (!ticket[c.columns.assignee]) {
@@ -34043,9 +34114,7 @@ ${where.join("\n")}`);
34043
34114
  emit.emit(`cleared assignee on ${label} \u2014 back up for grabs next cycle`);
34044
34115
  } catch (e) {
34045
34116
  if (e instanceof StaleWriteError9) {
34046
- process.stderr.write(`unassign: ${label} changed on the board since it was read \u2014 re-run to retry
34047
- `);
34048
- process.exit(2);
34117
+ die("crew unassign", `${label} changed on the board since it was read`, `\`crew unassign ${key}\` again`);
34049
34118
  }
34050
34119
  throw e;
34051
34120
  }
@@ -34351,11 +34420,12 @@ ${where.join("\n")}`);
34351
34420
  ` : `${human}
34352
34421
  `);
34353
34422
  const fail2 = (msg) => {
34354
- if (json2) process.stdout.write(`${JSON.stringify({ event: "error", message: msg })}
34423
+ if (json2) {
34424
+ process.stdout.write(`${JSON.stringify({ event: "error", message: msg })}
34355
34425
  `);
34356
- else process.stderr.write(`crew sample-ticket: ${msg}
34357
- `);
34358
- return process.exit(2);
34426
+ return process.exit(2);
34427
+ }
34428
+ return die("crew sample-ticket", msg, "`crew doctor`", 2);
34359
34429
  };
34360
34430
  if (!route2.resolved) fail2(`route ${route2.route} is not connected \u2014 run \`crew connect\` first`);
34361
34431
  const tracker = new Tracker(route2, cfg.ship);
@@ -35592,6 +35662,7 @@ ${foreign.join("\n")}
35592
35662
  }
35593
35663
  lock?.release();
35594
35664
  }
35665
+ var routineLine2;
35595
35666
  var die2;
35596
35667
  var requireArmed2;
35597
35668
  var parseTicketNumber2;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tablation/crew",
3
- "version": "0.149.4",
3
+ "version": "0.149.6",
4
4
  "description": "A standing team of headless agents that picks work off a Tablation board, does it on a machine you control, and reports back.",
5
5
  "type": "module",
6
6
  "license": "MIT",