@tablation/crew 0.149.5 → 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 +168 -36
  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.5" : 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
  `);
@@ -31576,6 +31704,7 @@ ${f.tail.trimEnd()}
31576
31704
  }
31577
31705
  },
31578
31706
  periscopeMcp: controlRoutes.some((r) => r.enabled && r.hostPeriscopes) ? (req, res, ticket) => handlePeriscopeMcp(periscopeMcpDeps(), req, res, ticket) : void 0,
31707
+ route: primary.route,
31579
31708
  status: () => crewJson(["status", primary.route, "--json"]),
31580
31709
  doctor: () => crewJson(["doctor", primary.route, "--json", "--offline"]),
31581
31710
  diagnostics: () => collectDiagnostics({
@@ -31584,7 +31713,10 @@ ${f.tail.trimEnd()}
31584
31713
  runner: cfg.ship.runner ?? "host",
31585
31714
  unitStems: detectSystemd() ? ["run", "release", "passengers"].map((j) => labelFor(CREW_HOME, j)) : [],
31586
31715
  userScope: process.getuid?.() !== 0,
31587
- 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
+ }
31588
31720
  }),
31589
31721
  scheduler: schedulerHandler(planDaemonControl(CREW_HOME, hostPlatform(), detectSystemd())),
31590
31722
  log: (m) => emit.warn(m)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tablation/crew",
3
- "version": "0.149.5",
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",