@the-vibe-company/armada 0.2.36 → 0.2.38

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 (3) hide show
  1. package/README.md +5 -3
  2. package/dist/armada.js +935 -422
  3. package/package.json +1 -1
package/dist/armada.js CHANGED
@@ -3,12 +3,12 @@
3
3
  // src/main.ts
4
4
  import { spawn as spawn2, spawnSync } from "node:child_process";
5
5
  import { createReadStream } from "node:fs";
6
- import { open as open2, readFile as readFile4 } from "node:fs/promises";
6
+ import { open as open2, readFile as readFile4, writeFile as writeFile3 } from "node:fs/promises";
7
7
  import { hostname as hostname2 } from "node:os";
8
8
  import { isatty } from "node:tty";
9
9
 
10
10
  // src/cli.ts
11
- import { dirname as dirname8, join as join7, resolve as resolve3 } from "node:path";
11
+ import { dirname as dirname8, join as join8, resolve as resolve3 } from "node:path";
12
12
 
13
13
  // ../core/src/types.ts
14
14
  var LABEL_PHASES = [
@@ -954,7 +954,14 @@ function buildLane(m, allComments, issue, opts) {
954
954
  function inFlight(m, comments, opts) {
955
955
  const held = (i) => {
956
956
  const fresh = freshEvent(i.id, opts);
957
- return fresh ? !ENDS_WORK.includes(fresh.kind) : !!i.agentPhase || isStarted(i);
957
+ const handle = opts.live?.handles?.[i.id];
958
+ const open = !!handle && !handle.releasedAt;
959
+ if (fresh) {
960
+ if (!ENDS_WORK.includes(fresh.kind))
961
+ return true;
962
+ return open && !!handle.claimedAt && handle.claimedAt > fresh.at;
963
+ }
964
+ return open || !!i.agentPhase || isStarted(i);
958
965
  };
959
966
  return m.program.filter((i) => m.isLeaf(i) && !isClosed(i) && held(i)).map((i) => buildLane(m, comments, i, opts)).sort((a, b) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase] || a.issue.id.localeCompare(b.issue.id, "en", { numeric: true }));
960
967
  }
@@ -998,56 +1005,6 @@ function waitingPullRequests(m, prs) {
998
1005
  return prs.filter((p) => p.state === "open").map((pr) => ({ pr, ticket: ticketOf.get(pr.url) ?? null })).sort((a, b) => a.pr.number - b.pr.number);
999
1006
  }
1000
1007
 
1001
- // ../core/src/herdr-profile.ts
1002
- function herdrChoice(choice) {
1003
- return {
1004
- ...choice,
1005
- profile: {
1006
- runtime: "herdr",
1007
- agent: choice.profile.harness,
1008
- model: choice.profile.model,
1009
- effort: choice.profile.effort,
1010
- fastMode: false
1011
- }
1012
- };
1013
- }
1014
- var herdrClaimHandle = (handle) => JSON.stringify({ workspace: handle.workspace, pane: handle.pane, agent: handle.agent });
1015
-
1016
- // ../core/src/npm.ts
1017
- var ARMADA_PACKAGE = CLI_PACKAGE;
1018
- var NPM_REGISTRY_URL = `https://registry.npmjs.org/${ARMADA_PACKAGE.replace("/", "%2f")}`;
1019
- var NPM_CHECK_MS = 3000;
1020
- async function checkPublished(version, fetch2, timeoutMs = NPM_CHECK_MS) {
1021
- try {
1022
- const signal = AbortSignal.timeout(timeoutMs);
1023
- const res = await fetch2(NPM_REGISTRY_URL, {
1024
- headers: { accept: "application/vnd.npm.install-v1+json" },
1025
- cache: "no-store",
1026
- signal
1027
- });
1028
- if (!res.ok)
1029
- return { state: "unknown", reason: `npm answered HTTP ${res.status}` };
1030
- const body = await res.json();
1031
- const versions = body?.versions;
1032
- if (!versions || typeof versions !== "object" || Array.isArray(versions) || !Object.keys(versions).length)
1033
- return { state: "unknown", reason: "npm listed no version" };
1034
- const candidates = Object.keys(versions).filter((candidate) => /^\d+\.\d+\.\d+$/.test(candidate) && compareVersions(candidate, version) <= 0).sort((first, second) => compareVersions(second, first));
1035
- for (const candidate of candidates) {
1036
- const tarball = versions[candidate]?.dist?.tarball;
1037
- if (typeof tarball !== "string" || !tarball)
1038
- continue;
1039
- const download = await fetch2(tarball, { method: "HEAD", cache: "no-store", signal });
1040
- if (download.status === 200)
1041
- return candidate === version ? { state: "published" } : { state: "missing", newest: candidate };
1042
- if (download.status !== 404)
1043
- return { state: "unknown", reason: `npm tarball answered HTTP ${download.status}` };
1044
- }
1045
- return { state: "missing", newest: null };
1046
- } catch (err) {
1047
- return { state: "unknown", reason: networkReason(err, timeoutMs) };
1048
- }
1049
- }
1050
-
1051
1008
  // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/error.js
1052
1009
  /*!
1053
1010
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -2016,12 +1973,124 @@ var HAS_WELLFORMED = !!"".isWellFormed;
2016
1973
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2017
1974
  */
2018
1975
 
1976
+ // ../core/src/herdr-profile.ts
1977
+ var herdrHarnessKind = (harness) => harness === "deepseek" ? "opencode" : harness;
1978
+ var herdrHarnessLabel = (harness) => harness === "deepseek" ? "deepseek (OpenCode + DeepSeek model)" : harness;
1979
+ function herdrChoice(choice) {
1980
+ return {
1981
+ ...choice,
1982
+ profile: {
1983
+ runtime: "herdr",
1984
+ agent: herdrHarnessLabel(choice.profile.harness),
1985
+ model: choice.profile.model,
1986
+ effort: choice.profile.effort,
1987
+ fastMode: false
1988
+ }
1989
+ };
1990
+ }
1991
+ var herdrClaimHandle = (handle) => JSON.stringify({ workspace: handle.workspace, pane: handle.pane, agent: handle.agent });
1992
+ function isDeepseekModel(model) {
1993
+ const [provider, ...parts] = model.split("/");
1994
+ return !!parts.length && (provider === "deepseek" || /(?:^|[/-])deepseek(?:$|[/-])/i.test(parts.join("/")));
1995
+ }
1996
+ function setHerdrModel(text, name, model) {
1997
+ const raw = parse(text);
1998
+ const profiles = raw.herdr?.profiles;
1999
+ if (!profiles?.[name])
2000
+ throw new Error("profile is no longer present");
2001
+ const lines = text.split(/(?<=\n)/);
2002
+ let section = -1;
2003
+ let end = lines.length;
2004
+ for (let i = 0;i < lines.length; i++) {
2005
+ const header = lines[i]?.match(/^\s*\[herdr\s*\.\s*profiles\s*\.\s*(.+?)\]\s*(?:#.*)?(?:\r?\n)?$/);
2006
+ if (header) {
2007
+ const key = header[1]?.trim();
2008
+ if (key && Object.hasOwn(parse(`[${key}]
2009
+ `), name)) {
2010
+ section = i;
2011
+ break;
2012
+ }
2013
+ }
2014
+ }
2015
+ if (section < 0)
2016
+ throw new Error("use an explicit [herdr.profiles.<name>] section to save the model");
2017
+ for (let i = section + 1;i < lines.length; i++) {
2018
+ if (/^\s*\[/.test(lines[i] ?? "")) {
2019
+ end = i;
2020
+ break;
2021
+ }
2022
+ }
2023
+ let replaced = false;
2024
+ for (let i = section + 1;i < end; i++) {
2025
+ const match = lines[i]?.match(/^(\s*(?:model|"model"|'model')\s*=\s*)("(?:[^"\\]|\\.)*"|'[^']*')(.*?)(\r?\n)?$/);
2026
+ if (match) {
2027
+ const value = match[2]?.startsWith("'") && !model.includes("'") ? `'${model}'` : JSON.stringify(model);
2028
+ lines[i] = `${match[1]}${value}${match[3]}${match[4] ?? ""}`;
2029
+ replaced = true;
2030
+ break;
2031
+ }
2032
+ }
2033
+ if (!replaced) {
2034
+ const newline = text.includes(`\r
2035
+ `) ? `\r
2036
+ ` : `
2037
+ `;
2038
+ if (!(lines[section] ?? "").endsWith(`
2039
+ `))
2040
+ lines[section] += newline;
2041
+ lines.splice(section + 1, 0, `model = ${JSON.stringify(model)}${newline}`);
2042
+ }
2043
+ const next = lines.join("");
2044
+ profiles[name].model = model;
2045
+ if (JSON.stringify(parse(next)) !== JSON.stringify(raw)) {
2046
+ const canonical = (value) => JSON.stringify(value, (_, v) => typeof v === "object" && v !== null && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((key) => [key, v[key]])) : v);
2047
+ if (canonical(parse(next)) !== canonical(raw))
2048
+ throw new Error("could not safely edit the profile model");
2049
+ }
2050
+ return next;
2051
+ }
2052
+
2053
+ // ../core/src/npm.ts
2054
+ var ARMADA_PACKAGE = CLI_PACKAGE;
2055
+ var NPM_REGISTRY_URL = `https://registry.npmjs.org/${ARMADA_PACKAGE.replace("/", "%2f")}`;
2056
+ var NPM_CHECK_MS = 3000;
2057
+ async function checkPublished(version, fetch2, timeoutMs = NPM_CHECK_MS) {
2058
+ try {
2059
+ const signal = AbortSignal.timeout(timeoutMs);
2060
+ const res = await fetch2(NPM_REGISTRY_URL, {
2061
+ headers: { accept: "application/vnd.npm.install-v1+json" },
2062
+ cache: "no-store",
2063
+ signal
2064
+ });
2065
+ if (!res.ok)
2066
+ return { state: "unknown", reason: `npm answered HTTP ${res.status}` };
2067
+ const body = await res.json();
2068
+ const versions = body?.versions;
2069
+ if (!versions || typeof versions !== "object" || Array.isArray(versions) || !Object.keys(versions).length)
2070
+ return { state: "unknown", reason: "npm listed no version" };
2071
+ const candidates = Object.keys(versions).filter((candidate) => /^\d+\.\d+\.\d+$/.test(candidate) && compareVersions(candidate, version) <= 0).sort((first, second) => compareVersions(second, first));
2072
+ for (const candidate of candidates) {
2073
+ const tarball = versions[candidate]?.dist?.tarball;
2074
+ if (typeof tarball !== "string" || !tarball)
2075
+ continue;
2076
+ const download = await fetch2(tarball, { method: "HEAD", cache: "no-store", signal });
2077
+ if (download.status === 200)
2078
+ return candidate === version ? { state: "published" } : { state: "missing", newest: candidate };
2079
+ if (download.status !== 404)
2080
+ return { state: "unknown", reason: `npm tarball answered HTTP ${download.status}` };
2081
+ }
2082
+ return { state: "missing", newest: null };
2083
+ } catch (err) {
2084
+ return { state: "unknown", reason: networkReason(err, timeoutMs) };
2085
+ }
2086
+ }
2087
+
2019
2088
  // ../core/src/config.ts
2020
2089
  var CONFIG_FILE = "armada.toml";
2021
2090
  var PLAN_POLICIES = ["approve", "pre-approved"];
2022
2091
  var routingLabelKey = (name) => name.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]/gu, "");
2023
2092
  var PROFILE_RUNTIMES = ["conductor", "claude-code"];
2024
- var HERDR_HARNESSES = ["claude", "codex", "opencode"];
2093
+ var HERDR_HARNESSES = ["claude", "codex", "opencode", "deepseek"];
2025
2094
  var CONFIG_DEFAULTS = {
2026
2095
  language: "en",
2027
2096
  readyLabel: "ready-for-agent",
@@ -2258,10 +2327,13 @@ function parseConfig(text, source = CONFIG_FILE) {
2258
2327
  else
2259
2328
  problems.push(`"${path}.extra_args" must be a list of non-empty argument strings`);
2260
2329
  }
2330
+ if (harness === "deepseek" && extraArgs.some((arg) => /^(?:--model(?:=|$)|-m)/.test(arg.trim())))
2331
+ problems.push(`"${path}.extra_args" must not override the DeepSeek model; use "${path}.model"`);
2332
+ const model = (harness === "opencode" || harness === "deepseek") && (p.model === undefined || typeof p.model === "string" && !p.model.trim()) ? "" : str(p, path, "model");
2261
2333
  herdrProfiles[name] = {
2262
2334
  ...p.when !== undefined ? { when: str(p, path, "when") } : {},
2263
2335
  harness,
2264
- model: str(p, path, "model"),
2336
+ model,
2265
2337
  effort: str(p, path, "effort"),
2266
2338
  extraArgs
2267
2339
  };
@@ -2567,7 +2639,7 @@ profile = "debug"
2567
2639
  # default_profile = "claude"
2568
2640
 
2569
2641
  # [herdr.profiles.claude]
2570
- # harness = "claude" # "claude", "codex" or "opencode"
2642
+ # harness = "claude" # "claude", "codex", "opencode" or "deepseek" (OpenCode + DeepSeek model)
2571
2643
  # model = "sonnet"
2572
2644
  # effort = "high"
2573
2645
  # extra_args = ["--verbose"]
@@ -3008,7 +3080,7 @@ ${validation}` : ""}`;
3008
3080
  await linear.deleteComment(mine.id);
3009
3081
  throw new Refusal(`${ticket.id} was claimed first by ${winner.claim?.runtime ?? "another worker"} · ${winner.claim?.session ?? "unknown session"}; your claim was withdrawn`, "armada status, to pick another ticket ready to start");
3010
3082
  }
3011
- lines.push(`Claimed ${ticket.id} for ${runtime.name} (${input.handle})${profile ? ` on profile ${profile.name}` : ""}.`);
3083
+ lines.push(`Claimed ${ticket.id} for ${runtime.name} (${input.handle})${profile ? ` on profile ${profile.name}${profile.profile.runtime === "herdr" ? ` (${profile.profile.agent})` : ""}` : ""}.`);
3012
3084
  } else {
3013
3085
  lines.push(`${ticket.id} is already claimed by this session (${input.handle}); labels and state repaired.`);
3014
3086
  if (input.profile && (holder?.profile ?? null) !== input.profile)
@@ -3448,6 +3520,8 @@ function renderPrompt(b) {
3448
3520
  ""
3449
3521
  ] : []
3450
3522
  ];
3523
+ if (b.runtime === "herdr" && b.profile)
3524
+ out.push("## Harness", "", `Profile ${b.profile.name}: ${b.profile.agent}, model ${b.profile.model}, effort ${b.profile.effort}.`, "");
3451
3525
  if (t.description)
3452
3526
  out.push("## Ticket", "", quote(t.description), "");
3453
3527
  if (b.parent)
@@ -3822,6 +3896,12 @@ function notStartedBody(l, now) {
3822
3896
  return `launched ${minutes} min ago and never claimed; ${why}${l.handle ? ` (session ${l.handle})` : ""}. Check its session with the runtime guide's status section; launch it again with armada brief ${l.ticket} --prompt, or revoke it with armada launch revoke ${l.ticket}`;
3823
3897
  }
3824
3898
  var notStartedLaunches = (launches, now, minutes) => followedLaunches(launches, now).filter((l) => now.getTime() - Date.parse(l.launchedAt) > minutes * MIN2);
3899
+ function freshRuntimeState(observation, now, minutes, claimedAt) {
3900
+ if (!observation || claimedAt && (observation.at < claimedAt || (observation.since ?? observation.at) < claimedAt))
3901
+ return null;
3902
+ const age = now.getTime() - Date.parse(observation.at);
3903
+ return observation.state !== "unknown" && Number.isFinite(age) && age >= 0 && age <= minutes * MIN2 ? observation.state : null;
3904
+ }
3825
3905
 
3826
3906
  // ../core/src/fleet-api.ts
3827
3907
  var WORKER_FLEET_OPS = ["claim", "report", "ask", "release", "heartbeat", "validate"];
@@ -3832,6 +3912,10 @@ var FLEET_OPS = [
3832
3912
  "request",
3833
3913
  "events/latest",
3834
3914
  "heartbeats/latest",
3915
+ "runtime/handles",
3916
+ "runtime/handle",
3917
+ "runtime/observe",
3918
+ "runtime/stop",
3835
3919
  "launches",
3836
3920
  "inbox",
3837
3921
  "inbox/item",
@@ -3861,6 +3945,10 @@ function fleetClient(o) {
3861
3945
  lastEventTimes: () => call("events/latest", {}),
3862
3946
  heartbeatTimes: () => call("heartbeats/latest", {}),
3863
3947
  heartbeat: (input) => call("heartbeat", input),
3948
+ runtimeHandles: () => call("runtime/handles", {}),
3949
+ runtimeHandle: (ticket) => call("runtime/handle", { ticket }),
3950
+ observeRuntime: (input) => call("runtime/observe", input),
3951
+ stopRuntime: (input) => call("runtime/stop", input),
3864
3952
  pendingLaunches: () => call("launches", {}),
3865
3953
  claim: (c) => call("claim", c),
3866
3954
  report: (r) => call("report", r),
@@ -4323,7 +4411,10 @@ async function answerItem(ctx, input) {
4323
4411
  ticketId = input.target.trim().toUpperCase();
4324
4412
  if (!input.note) {
4325
4413
  const open = await live(ctx, warnings, `read the open questions of ${ticketId}`, (fleet) => fleet.ticketItems(ticketId ?? ""));
4326
- if (open && !open.some((i) => i.kind === "question" || i.kind === "plan"))
4414
+ const handle = open && !open.some((i) => i.kind === "question" || i.kind === "plan") ? await live(ctx, warnings, `read the runtime of ${ticketId}`, (fleet) => fleet.runtimeHandle(ticketId ?? "")) : null;
4415
+ const observation = handle?.runtimeState;
4416
+ const runtimeBlocked = ctx.deliverAnswer && handle?.runtime.toLowerCase() === "herdr" && !handle.releasedAt && observation?.state === "blocked" && Date.parse(observation.at) <= ctx.now().getTime() && ctx.now().getTime() - Date.parse(observation.at) <= config.policy.silentAfterMinutes * 60000;
4417
+ if (open && !open.some((i) => i.kind === "question" || i.kind === "plan") && !runtimeBlocked)
4327
4418
  throw new Refusal(`${ticketId} has no open question or plan in the inbox`, `armada answer --note ${ticketId} "<message>", for an unsolicited message`);
4328
4419
  }
4329
4420
  }
@@ -4336,6 +4427,11 @@ async function answerItem(ctx, input) {
4336
4427
  const question = item?.kind === "answer-request" ? item.request?.question ?? null : null;
4337
4428
  const answered = question === null ? item : await live(ctx, warnings, `read the item answered by #${item?.id}`, (fleet) => fleet.inboxItem(question));
4338
4429
  const answerKind = answered?.kind === "plan" ? "plan" : "question";
4430
+ const claim = ticketId && ctx.deliverAnswer ? await live(ctx, warnings, `read the claim of ${ticketId}`, (fleet) => fleet.runtimeHandle(ticketId)) : null;
4431
+ if (claim?.runtime.toLowerCase() === "herdr" && claim.releasedAt)
4432
+ throw new Refusal("the herdr worker has ended; no answer was delivered", "armada inbox");
4433
+ if (claim?.runtime.toLowerCase() === "herdr" && answered && answered.createdAt < claim.claimedAt)
4434
+ throw new Refusal("the question belongs to an earlier worker claim; no answer was delivered", "armada inbox");
4339
4435
  let url = "";
4340
4436
  if (ticketId) {
4341
4437
  const ticket = await linear.readTicket(ticketId);
@@ -4343,14 +4439,20 @@ async function answerItem(ctx, input) {
4343
4439
  throw new Refusal(`ticket ${ticketId} not found in Linear`, "armada inbox");
4344
4440
  url = ticket.url;
4345
4441
  warnings.push(...ticket.warnings);
4346
- if (!ticket.agentPhase) {
4442
+ const herdrClaim = claim?.runtime.toLowerCase() === "herdr" && !claim.releasedAt;
4443
+ if (!ticket.agentPhase && !herdrClaim) {
4347
4444
  if (input.note)
4348
4445
  throw new Refusal(`${ticket.id} has no agent phase: no worker holds it, so there is no one to tell`, "armada status, to see which tickets are in flight");
4349
4446
  warnings.push(`${ticket.id} has no agent phase (no worker holds it); the answer was not posted on the ticket`);
4350
4447
  } else {
4351
4448
  const ref = item?.kind === "answer-request" ? `Answers ${question === null ? "the open question or plan" : `${answerKind} #${question}`}, as ${item.author ?? "the owner"} asked from the dashboard (request #${item.id}).` : itemId === null ? null : `Answers ${answerKind} #${itemId}.`;
4352
- await linear.comment(ticket.uuid, statusComment(ticket.agentPhase, input.note ? "note" : "answer", text, ref));
4353
- lines.push(`${input.note ? "Note" : "Answer"} posted on ${ticket.id} (${ticket.agentPhase}).`);
4449
+ if (ctx.deliverAnswer && await ctx.deliverAnswer(ticket.id, text, claim?.runtime ?? ticket.agentRuntime, claim))
4450
+ lines.push(`Delivered to ${ticket.id}'s herdr pane.`);
4451
+ if (ticket.agentPhase) {
4452
+ await linear.comment(ticket.uuid, statusComment(ticket.agentPhase, input.note ? "note" : "answer", text, ref));
4453
+ lines.push(`${input.note ? "Note" : "Answer"} posted on ${ticket.id} (${ticket.agentPhase}).`);
4454
+ } else
4455
+ warnings.push(`${ticket.id} has no tracker phase; the delivered answer is recorded in Armada`);
4354
4456
  }
4355
4457
  }
4356
4458
  const recorded = await live(ctx, warnings, `record the ${input.note ? "note" : "answer"}`, (fleet) => fleet.answer({ text, note: !!input.note, ticket: ticketId, item: itemId }));
@@ -5880,7 +5982,7 @@ The coordinator turns the owner's intent into merged pull requests. Each worker
5880
5982
 
5881
5983
  **Standing authority.** Unless the owner said otherwise, they delegate reversible technical decisions, plan approval and merging to you: act, then report. Escalate only product decisions, irreversible or outward-facing actions, and anything that spends money.
5882
5984
 
5883
- **Armada never drives a runtime.** Launching, messaging, checking and stopping a worker go through the runtime guide skill for the worker's runtime: \`armada-runtime-conductor\` for a Conductor workspace, \`armada-runtime-claude-code\` for a subagent of your own Claude Code session (the \`Runtime:\` line of \`armada brief\` names it). Armada records what happened.
5985
+ **Use the worker's runtime guide.** Launching, messaging, checking and stopping a worker go through the runtime guide skill for the worker's runtime: \`armada-runtime-conductor\` for a Conductor workspace, \`armada-runtime-claude-code\` for a subagent of your own Claude Code session (the \`Runtime:\` line of \`armada brief\` names it). For persistent local workers, \`armada-runtime-herdr\` uses Armada's integrated launch, state, answer and safe stop commands. Other runtimes are delivered separately and Armada records what happened.
5884
5986
 
5885
5987
  ## Take over a run
5886
5988
 
@@ -5897,7 +5999,7 @@ A coordinator may start cold, on a laptop or in a fresh cloud session, with noth
5897
5999
  ## Loop
5898
6000
 
5899
6001
  1. **Read the fleet** with \`armada status\` and \`armada inbox\`, never from memory. Done when you can name every ticket in flight and its phase, every ready ticket, every pull request waiting, every silent worker and every pending question, plan or request.
5900
- 2. **Answer what waits for you first.** For each question in \`armada inbox\`: decide it, or escalate it to the owner when it is a product decision: \`armada ask-owner <ticket> "<question>" --choices "<a> | <b>"\` puts it on the owner's Validations page and prints the link to send them; their pick arrives as a \`decision\` item. For each \`plan\` item: read the full plan, approve it or give concrete amendments. Deliver the decision in the worker's session with the runtime guide's *message* section, then record it with \`armada answer <item> "approved"\` or \`armada answer <item> "<amendments and reason>"\`. The worker resumes with \`implementing\` on approval, or returns to \`planning\` and submits a revised plan. \`armada answer\` only records; it never reaches the worker. Decide reversible choices yourself and prefer the option that keeps behaviour observable. When two workers need the same shared resource (a migration slot, a generated file, a version number), set the rule once and tell both. A message the worker did not ask for (main moved, bring it in) takes the same path: deliver it with the runtime guide, then \`armada answer --note <ticket> "<message>"\`. Done when the inbox shows no open question or plan.
6002
+ 2. **Answer what waits for you first.** For each question in \`armada inbox\`: decide it, or escalate it to the owner when it is a product decision: \`armada ask-owner <ticket> "<question>" --choices "<a> | <b>"\` puts it on the owner's Validations page and prints the link to send them; their pick arrives as a \`decision\` item. For each \`plan\` item: read the full plan, approve it or give concrete amendments. Deliver the decision in the worker's session with the runtime guide's *message* section, then record it with \`armada answer <item> "approved"\` or \`armada answer <item> "<amendments and reason>"\`. The worker resumes with \`implementing\` on approval, or returns to \`planning\` and submits a revised plan. \`armada answer\` delivers herdr answers automatically; omit the separate delivery step for herdr. Decide reversible choices yourself and prefer the option that keeps behaviour observable. When two workers need the same shared resource (a migration slot, a generated file, a version number), set the rule once and tell both. A message the worker did not ask for (main moved, bring it in) takes the same path: deliver it with the runtime guide, then \`armada answer --note <ticket> "<message>"\`. A live herdr \`runtime-blocked\` entry has no item id: read the pane and answer by ticket. Done when the inbox shows no open question or plan.
5901
6003
  3. **Carry out the owner's dashboard requests.** They are the owner's word, signed with their name; they never reached a worker.
5902
6004
  - \`answer-request\` (it names the question or plan it answers, \`answers #<id>\`): deliver its text in the worker's session with the runtime guide's *message* section, as the owner's answer or plan approval, then \`armada answer <request id> "<the text you delivered>"\`. That resolves the request and its question or plan, and the ticket names who answered. If the item is gone (the worker was released or changed phase), \`armada answer <request id> "<why>"\` closes it.
5903
6005
  - \`launch-request\`: launch the ticket as in step 5. A request may name a label-routed profile or one the owner chose; otherwise choose from the profiles' \`when\` rules. Pass \`--profile\` and \`--reason\` when a choice or override is needed. The worker's \`armada claim\` resolves the request and posts who asked. If the ticket must not start (it collides with work in flight, or its plan changed), decline it: \`armada answer <request id> "<why>"\`, and tell the owner in your report.
@@ -5952,7 +6054,7 @@ name: armada-runtime-claude-code
5952
6054
  description: Runtime guide for running Armada workers as local subagents of a Claude Code coordinator. Use when an Armada coordinator running in Claude Code must launch a worker on a ticket with the Agent tool, send it a message, check whether a silent worker is still alive, or stop it and clean up its worktree. Four fixed sections, each with the exact tool call and how to read its result.
5953
6055
  ---
5954
6056
 
5955
- Armada never calls a runtime. This guide tells a coordinator running inside Claude Code how to launch, message, check and stop a worker as one of its own subagents (the Agent tool), and what to record in Armada afterwards. It was checked against Claude Code's Agent, SendMessage, TaskStop and EnterWorktree tools as of October 2026; if a parameter below is refused, read the tool's own description and adapt.
6057
+ Armada records Conductor and Claude Code runtime actions separately; persistent herdr workers use integrated commands. This guide tells a coordinator running inside Claude Code how to launch, message, check and stop a worker as one of its own subagents (the Agent tool), and what to record in Armada afterwards. It was checked against Claude Code's Agent, SendMessage, TaskStop and EnterWorktree tools as of October 2026; if a parameter below is refused, read the tool's own description and adapt.
5956
6058
 
5957
6059
  - **A subagent lives inside your session.** It dies when your session ends: closing the terminal, a crash or the end of a cloud machine stops every worker you launched this way, mid-turn. Use this runtime for short tickets you will see through in one sitting. Long runs, and anything that must survive you, go to Conductor (the \`armada-runtime-conductor\` skill).
5958
6060
  - **Always in its own worktree.** A subagent launched without \`isolation: "worktree"\` works in your own checkout: it edits your files and switches your branch under you, and two such workers overwrite each other. Never launch one without it.
@@ -6064,7 +6166,16 @@ A subagent launched without \`isolation: "worktree"\` runs in your checkout. The
6064
6166
  files: [
6065
6167
  {
6066
6168
  path: "SKILL.md",
6067
- content: "---\nname: armada-runtime-conductor\ndescription: Runtime guide for running Armada workers on Conductor Cloud. Use when an Armada coordinator must launch a worker on a ticket, send it a message, check whether a silent worker is still alive, or stop and archive it. Four fixed sections, each with the exact conductor command and how to read its output.\n---\n\nArmada never calls a runtime. This guide tells the coordinator how to launch, message, check and stop a worker with the `conductor` command line tool, and what to record in Armada afterwards. It was checked against `conductor` 0.89.x (the desktop app's CLI, macOS) and 0.1.x (the CLI inside a Conductor Cloud workspace, Linux); every command below works in both. `conductor --version` prints yours; if a flag is refused, compare with `conductor <command> --help`.\n\n- On a Mac, the app ships the CLI at `/Applications/Conductor.app/Contents/Resources/bin/conductor`, which is not on PATH. `armada doctor` looks for it and prints the fix: a link from a directory already on PATH (`ln -s \"/Applications/Conductor.app/Contents/Resources/bin/conductor\" ~/.local/bin/conductor`), or a PATH line for your shell profile.\n- Always pass `--json` and read fields with `jq`. Exit codes: 0 ok, 1 runtime error, 2 usage error, 3 authentication, 4 server error.\n- On exit code 3, `conductor auth whoami` checks the token the CLI uses (it exits 0 when the token works). Do not rely on `conductor auth status`: it only looks for a macOS Keychain entry and fails on Linux (\"Keychain storage is only supported on macOS\"). In a Conductor Cloud workspace the CLI reads `CONDUCTOR_API_KEY` from the environment and needs no login; on a Mac, `conductor auth login` stores a token in the Keychain.\n- A worker is one workspace with one session. Its Armada handle is `<workspaceId>/<sessionId>`; the worker's claim comment carries it, so `armada status` and the ticket always lead back to the session.\n- A worker needs no key in its workspace: the prompt of `armada brief` carries a one-time launch token, and the worker's first command exchanges it for a session limited to its ticket, through which Armada gives each command its keys. The token works once, within the hour, so a copy left in a transcript is useless once used.\n- Never type a secret value into a command, a file or a message: name the variable and let your shell expand it. The expanded value is still in the `conductor` process's arguments while it runs, so launch from a machine only you use.\n\n## Launch\n\nThe brief starts `armada heartbeat --every 5m --parent \"$PPID\" --background` immediately after claim. It creates a detached process group (like `nohup` + `setsid`) with closed terminal streams and a PID file under `~/.config/armada/watch/`. Plain `&` and `nohup` alone can be killed by command-tool cleanup on Cloud; detached startup survives between turns and while waiting for a message. `$PPID` in the agent's command shell must be the persistent agent process, never `$$` (the shell). The heartbeat stops with that parent or when Armada ends the current session (release, merge, revoke). If startup fails or the runtime cannot retain any background process, fall back to manual reports at least every 15 minutes and record that fallback on the ticket. Reports remain progress dots, not liveness.\n\n1. Pick a ready ticket from `armada status` that does not collide with work in flight.\n2. Read the ticket and parent, then choose its profile. A matching label rule wins; otherwise match the profiles' `when` rules by most files/work. Mixed front-end/back-end work: choose the larger part and say why with `--profile <name> --reason \"<why>\"`. An optional `armada brief ABC-12` or `--json` preview helps resolve the choice and warnings, but is read-only: neither creates a launch token nor marks a worker in flight. If the choice is still needed, `--prompt` refuses before minting anything.\n3. **Make one brief call for the launch:** `--prompt --profile-line` writes only the worker prompt to stdout and the selected profile (agent, model, effort, fast mode, runtime and reason) to stderr. Read that line to configure Conductor; no second brief is needed for the profile. Keep any `--profile` and `--reason` flags on this call. Resolve warnings before launching. Never cut a launch message from the human view or `--json`: they carry no token. Write the prompt to a file only you can read, then add what only you know (the boundary with a parallel worker, a decision not yet on the ticket). The token works once, within the hour; if you cancel or the runtime launch fails, use `armada launch revoke ABC-12`. Generate a fresh prompt if its token has expired.\n\n```sh\n(umask 077; armada brief ABC-12 --prompt --profile-line > /tmp/abc-12-brief.md)\n```\n\n4. Create the workspace with every value from the profile. Never leave the agent, model or effort to Conductor's defaults. Add `--fast-mode` when the profile says fast mode. Run the whole block as one command: shell state does not carry over between separate calls.\n\n```sh\nconductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\nrm -f /tmp/abc-12-brief.md\njq -r '\"\\(.workspaceId)/\\(.sessionId)\"' /tmp/abc-12-launch.json\n```\n\nIf the prompt has no launch token, its stderr warning says why. Not signed in: `armada login` (a headless coordinator sets `ARMADA_API_KEY`), then generate a new prompt; `armada doctor` checks the sign-in. Only on an Armada that keeps no keys yet (no accounts or no vault), pass the keys the read-only brief's environment table marks `required`, from your shell or from Armada's credentials file (`in credentials file`: the `set -a` line loads it without printing it; drop it when every variable is set in your shell). The subshell keeps the keys out of the rest of your session. Without a launch token the worker is not signed in to Armada: its claims and reports reach Linear only, with a warning. When Conductor's organization environment still holds the keys, every workspace already has them: use the first block.\n\n```sh\n(\n set -a; . \"${XDG_CONFIG_HOME:-$HOME/.config}/armada/credentials\"; set +a\n [ -n \"$LINEAR_API_KEY\" ] || { echo \"LINEAR_API_KEY is missing\" >&2; exit 1; }\n conductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n --env LINEAR_API_KEY=\"$LINEAR_API_KEY\" \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\n)\nrm -f /tmp/abc-12-brief.md\n```\n\n- `--branch` is the base branch (the default branch). Conductor creates a branch named `conductor/<slug of --name>`; the brief tells the worker to rename it to the ticket's branch.\n- The output has `workspaceId`, `sessionId`, `deepLink` and `initialMessage` (`messageId`, `state: \"queued\"`). Keep the handle the `jq` line prints, and give the owner the `deepLink` when they want to watch.\n- Conductor sets `CONDUCTOR_WORKSPACE_ID` and `CONDUCTOR_SESSION_ID` inside the workspace, and signs `gh` in for the worker's pushes. The brief's first commands install your Armada version (`npm install -g`), sign in with the launch token (`armada login --launch-token`) and claim the ticket. `--env` values are not shown back by `workspace get`.\n- Keys in Conductor's organization environment reach every workspace, workers included: once Armada keeps the organization's keys, they belong on Armada's Keys page, not there.\n- An unknown agent, model or effort fails the command. Check the ids with `conductor model` (each agent's models, efforts and defaults) and fix the profile in `armada.toml`.\n\n5. **Check the claim.** Within a few minutes, `armada status` lists the ticket in flight, phase `planning`, runtime `Conductor`, and the ticket's claim comment reads `session: <workspaceId>/<sessionId>` and `profile: <name>`. No claim after `[policy] not_started_minutes` (ten by default): `armada watch` and `armada inbox` show a `not-started` entry; status lists it under \"Pending launches\" with `armada launch revoke ABC-12`. It says whether the worker never used its launch token (it never reached its login line) or signed in and stopped before its claim. An unused token expired more than an hour ago produces one `not started (token expired)` inbox notice, then clears. Exchanged launches without a claim stop being followed after 24 hours and remain revocable. Read the transcript (Status section). A worker whose launch token was refused (already used, or more than an hour old) needs a new one: `armada brief ABC-12 --prompt --profile-line` again, and message it only the `armada login --launch-token …` line of the new `--prompt` output (Message section). A worker cut off from Armada was revoked (Organization > Workers says by whom) or left idle for three days: ask the owner before you give a revoked worker a new token. If the worker cannot claim for another reason, fix the cause and message it; as a last resort record the handle yourself with `armada claim ABC-12 --runtime conductor --handle <workspaceId>/<sessionId> --profile <name>`, adding the brief's `--reason` for an override.\n\n## Message\n\n```sh\nprintf '%s\\n' \"Plan approved. Go on.\" | conductor --json message create --session <sessionId> --message-file -\nconductor --json message create --session <sessionId> --message-file - < /tmp/abc-12-answer.md\n```\n\nThe output is `{\"messageId\": …, \"state\": \"sent\"}`. Exit code 0 means Conductor accepted the message, not that the worker read it: check that the session turns `working`, then read its reply in the transcript. Use it to deliver an answer, a plan approval, or a heads-up that the default branch moved. Then record it in Armada: `armada answer <item> \"<answer>\"` for a question from `armada inbox`, `armada answer --note ABC-12 \"<message>\"` for a message the worker did not ask for.\n\n## Status\n\n```sh\nconductor --json session status <sessionId>\n```\n\nThe output is `{\"workspaceId\", \"sessionId\", \"status\", \"updatedAt\"}`. For a worker:\n\n- `working`: a turn is running. A silent worker that is `working` is busy (a long build or test run): leave it, and read the transcript if it stays silent past twice `policy.silence_minutes`.\n- `idle`: no turn is running. The worker finished its turn: it handed back, it waits for an answer, or it stopped without finishing. If `armada status` does not show it `ready-to-merge`, `awaiting-approval` or `blocked`, it has stopped: read its last reply, then message it to go on, or release and relaunch the ticket.\n- `error`: the last turn failed (agent or provider failure). Read the transcript and message it to resume; if it fails again, cancel, archive, release and relaunch.\n- Right after launch the session is `idle` for a few seconds while the workspace is initializing and the first message is queued; it turns `working` when the agent starts.\n\nThe workspace itself: `conductor --json workspace status <workspaceId>` gives `status` `initializing`, `ready` or `archived`.\n\n**Read the transcript** to see what a worker did or said. Events come oldest first, 100 per page; `hasMore` tells when to fetch the next page with `--after` the last event id. Keep the last id you read and poll from it.\n\n```sh\nconductor --json session message <sessionId> --limit 100 > /tmp/abc-12-events.json\njq -r '.hasMore, .data[-1].id' /tmp/abc-12-events.json\nconductor --json session message <sessionId> --after <lastEventId> --limit 100\n```\n\nThe second line prints whether more pages exist and the id to continue from. `.content.rawPayload` is the agent's own event format, so the filters depend on the worker's agent (the `agent` of its profile in `armada.toml`).\n\nA `claude` worker: each turn's final reply, then the commands and tools it ran.\n\n```sh\njq -r '.data[] | select(.content.rawPayload.type == \"result\") | .content.rawPayload | \"error=\\(.is_error)\\n\\(.result)\"' /tmp/abc-12-events.json\njq -r '.data[] | select(.content.rawPayload.type == \"assistant\") | .content.rawPayload.message.content[] | select(.type == \"tool_use\") | .input.command // .name' /tmp/abc-12-events.json\n```\n\nA `codex` worker: its events are `.content.rawPayload.event`, each item once as `item.started` and once as `item.completed`; read the completed ones. Its messages (`phase` is `commentary` along the way, `final_answer` at the end of a turn), then each command with its exit code, and its tool calls (Linear and other MCP servers).\n\n```sh\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"agentMessage\") | \"[\\(.phase)] \\(.text)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"commandExecution\") | \"exit=\\(.exitCode) \\(.command)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"mcpToolCall\") | \"\\(.server) \\(.tool)\"' /tmp/abc-12-events.json\n```\n\nAnother agent, or a filter that prints nothing: count the event types, look at one event of the type you need, and adapt the filter.\n\n```sh\njq -r '.data[].content.rawPayload | .type // .event.type // \"(no payload)\"' /tmp/abc-12-events.json | sort | uniq -c\n```\n\n## Stop and archive\n\n```sh\nconductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n\n- `session cancel` stops the running turn: `{\"status\", \"canceledQueuedMessages\"}`, and the session is `idle` within seconds. The workspace stays; a message starts a new turn. Use it on a worker that runs the wrong thing.\n- `workspace archive` answers `{\"status\": \"archived\"}`. Archive a worker's workspace after its pull request is merged, or after `armada release --ticket ABC-12 --reason \"<why>\"` for a worker that stops without handing back. The branch and the pull request stay on GitHub.\n- **Wait for `idle` before archiving.** A hand-back often arrives while the worker's session is still `working`: `armada report ready-to-merge` runs inside its last turn, which then writes its final reply. Archive only once `session status` answers `idle`. Poll it every 15 seconds; if it is still `working` after 10 minutes, cancel the turn and archive (the transcript keeps what it was doing). Run the whole block as one command; it can take up to 10 minutes, so run it in the background or give it a longer command timeout:\n\n```sh\nfor i in $(seq 40); do\n [ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] || break\n sleep 15\ndone\n[ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] && conductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n- After an archive, `session status` still answers `idle`; `workspace status` says `archived`.\n"
6169
+ content: "---\nname: armada-runtime-conductor\ndescription: Runtime guide for running Armada workers on Conductor Cloud. Use when an Armada coordinator must launch a worker on a ticket, send it a message, check whether a silent worker is still alive, or stop and archive it. Four fixed sections, each with the exact conductor command and how to read its output.\n---\n\nArmada records Conductor and Claude Code runtime actions separately; persistent herdr workers use integrated commands. This guide tells the coordinator how to launch, message, check and stop a worker with the `conductor` command line tool, and what to record in Armada afterwards. It was checked against `conductor` 0.89.x (the desktop app's CLI, macOS) and 0.1.x (the CLI inside a Conductor Cloud workspace, Linux); every command below works in both. `conductor --version` prints yours; if a flag is refused, compare with `conductor <command> --help`.\n\n- On a Mac, the app ships the CLI at `/Applications/Conductor.app/Contents/Resources/bin/conductor`, which is not on PATH. `armada doctor` looks for it and prints the fix: a link from a directory already on PATH (`ln -s \"/Applications/Conductor.app/Contents/Resources/bin/conductor\" ~/.local/bin/conductor`), or a PATH line for your shell profile.\n- Always pass `--json` and read fields with `jq`. Exit codes: 0 ok, 1 runtime error, 2 usage error, 3 authentication, 4 server error.\n- On exit code 3, `conductor auth whoami` checks the token the CLI uses (it exits 0 when the token works). Do not rely on `conductor auth status`: it only looks for a macOS Keychain entry and fails on Linux (\"Keychain storage is only supported on macOS\"). In a Conductor Cloud workspace the CLI reads `CONDUCTOR_API_KEY` from the environment and needs no login; on a Mac, `conductor auth login` stores a token in the Keychain.\n- A worker is one workspace with one session. Its Armada handle is `<workspaceId>/<sessionId>`; the worker's claim comment carries it, so `armada status` and the ticket always lead back to the session.\n- A worker needs no key in its workspace: the prompt of `armada brief` carries a one-time launch token, and the worker's first command exchanges it for a session limited to its ticket, through which Armada gives each command its keys. The token works once, within the hour, so a copy left in a transcript is useless once used.\n- Never type a secret value into a command, a file or a message: name the variable and let your shell expand it. The expanded value is still in the `conductor` process's arguments while it runs, so launch from a machine only you use.\n\n## Launch\n\nThe brief starts `armada heartbeat --every 5m --parent \"$PPID\" --background` immediately after claim. It creates a detached process group (like `nohup` + `setsid`) with closed terminal streams and a PID file under `~/.config/armada/watch/`. Plain `&` and `nohup` alone can be killed by command-tool cleanup on Cloud; detached startup survives between turns and while waiting for a message. `$PPID` in the agent's command shell must be the persistent agent process, never `$$` (the shell). The heartbeat stops with that parent or when Armada ends the current session (release, merge, revoke). If startup fails or the runtime cannot retain any background process, fall back to manual reports at least every 15 minutes and record that fallback on the ticket. Reports remain progress dots, not liveness.\n\n1. Pick a ready ticket from `armada status` that does not collide with work in flight.\n2. Read the ticket and parent, then choose its profile. A matching label rule wins; otherwise match the profiles' `when` rules by most files/work. Mixed front-end/back-end work: choose the larger part and say why with `--profile <name> --reason \"<why>\"`. An optional `armada brief ABC-12` or `--json` preview helps resolve the choice and warnings, but is read-only: neither creates a launch token nor marks a worker in flight. If the choice is still needed, `--prompt` refuses before minting anything.\n3. **Make one brief call for the launch:** `--prompt --profile-line` writes only the worker prompt to stdout and the selected profile (agent, model, effort, fast mode, runtime and reason) to stderr. Read that line to configure Conductor; no second brief is needed for the profile. Keep any `--profile` and `--reason` flags on this call. Resolve warnings before launching. Never cut a launch message from the human view or `--json`: they carry no token. Write the prompt to a file only you can read, then add what only you know (the boundary with a parallel worker, a decision not yet on the ticket). The token works once, within the hour; if you cancel or the runtime launch fails, use `armada launch revoke ABC-12`. Generate a fresh prompt if its token has expired.\n\n```sh\n(umask 077; armada brief ABC-12 --prompt --profile-line > /tmp/abc-12-brief.md)\n```\n\n4. Create the workspace with every value from the profile. Never leave the agent, model or effort to Conductor's defaults. Add `--fast-mode` when the profile says fast mode. Run the whole block as one command: shell state does not carry over between separate calls.\n\n```sh\nconductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\nrm -f /tmp/abc-12-brief.md\njq -r '\"\\(.workspaceId)/\\(.sessionId)\"' /tmp/abc-12-launch.json\n```\n\nIf the prompt has no launch token, its stderr warning says why. Not signed in: `armada login` (a headless coordinator sets `ARMADA_API_KEY`), then generate a new prompt; `armada doctor` checks the sign-in. Only on an Armada that keeps no keys yet (no accounts or no vault), pass the keys the read-only brief's environment table marks `required`, from your shell or from Armada's credentials file (`in credentials file`: the `set -a` line loads it without printing it; drop it when every variable is set in your shell). The subshell keeps the keys out of the rest of your session. Without a launch token the worker is not signed in to Armada: its claims and reports reach Linear only, with a warning. When Conductor's organization environment still holds the keys, every workspace already has them: use the first block.\n\n```sh\n(\n set -a; . \"${XDG_CONFIG_HOME:-$HOME/.config}/armada/credentials\"; set +a\n [ -n \"$LINEAR_API_KEY\" ] || { echo \"LINEAR_API_KEY is missing\" >&2; exit 1; }\n conductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n --env LINEAR_API_KEY=\"$LINEAR_API_KEY\" \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\n)\nrm -f /tmp/abc-12-brief.md\n```\n\n- `--branch` is the base branch (the default branch). Conductor creates a branch named `conductor/<slug of --name>`; the brief tells the worker to rename it to the ticket's branch.\n- The output has `workspaceId`, `sessionId`, `deepLink` and `initialMessage` (`messageId`, `state: \"queued\"`). Keep the handle the `jq` line prints, and give the owner the `deepLink` when they want to watch.\n- Conductor sets `CONDUCTOR_WORKSPACE_ID` and `CONDUCTOR_SESSION_ID` inside the workspace, and signs `gh` in for the worker's pushes. The brief's first commands install your Armada version (`npm install -g`), sign in with the launch token (`armada login --launch-token`) and claim the ticket. `--env` values are not shown back by `workspace get`.\n- Keys in Conductor's organization environment reach every workspace, workers included: once Armada keeps the organization's keys, they belong on Armada's Keys page, not there.\n- An unknown agent, model or effort fails the command. Check the ids with `conductor model` (each agent's models, efforts and defaults) and fix the profile in `armada.toml`.\n\n5. **Check the claim.** Within a few minutes, `armada status` lists the ticket in flight, phase `planning`, runtime `Conductor`, and the ticket's claim comment reads `session: <workspaceId>/<sessionId>` and `profile: <name>`. No claim after `[policy] not_started_minutes` (ten by default): `armada watch` and `armada inbox` show a `not-started` entry; status lists it under \"Pending launches\" with `armada launch revoke ABC-12`. It says whether the worker never used its launch token (it never reached its login line) or signed in and stopped before its claim. An unused token expired more than an hour ago produces one `not started (token expired)` inbox notice, then clears. Exchanged launches without a claim stop being followed after 24 hours and remain revocable. Read the transcript (Status section). A worker whose launch token was refused (already used, or more than an hour old) needs a new one: `armada brief ABC-12 --prompt --profile-line` again, and message it only the `armada login --launch-token …` line of the new `--prompt` output (Message section). A worker cut off from Armada was revoked (Organization > Workers says by whom) or left idle for three days: ask the owner before you give a revoked worker a new token. If the worker cannot claim for another reason, fix the cause and message it; as a last resort record the handle yourself with `armada claim ABC-12 --runtime conductor --handle <workspaceId>/<sessionId> --profile <name>`, adding the brief's `--reason` for an override.\n\n## Message\n\n```sh\nprintf '%s\\n' \"Plan approved. Go on.\" | conductor --json message create --session <sessionId> --message-file -\nconductor --json message create --session <sessionId> --message-file - < /tmp/abc-12-answer.md\n```\n\nThe output is `{\"messageId\": …, \"state\": \"sent\"}`. Exit code 0 means Conductor accepted the message, not that the worker read it: check that the session turns `working`, then read its reply in the transcript. Use it to deliver an answer, a plan approval, or a heads-up that the default branch moved. Then record it in Armada: `armada answer <item> \"<answer>\"` for a question from `armada inbox`, `armada answer --note ABC-12 \"<message>\"` for a message the worker did not ask for.\n\n## Status\n\n```sh\nconductor --json session status <sessionId>\n```\n\nThe output is `{\"workspaceId\", \"sessionId\", \"status\", \"updatedAt\"}`. For a worker:\n\n- `working`: a turn is running. A silent worker that is `working` is busy (a long build or test run): leave it, and read the transcript if it stays silent past twice `policy.silence_minutes`.\n- `idle`: no turn is running. The worker finished its turn: it handed back, it waits for an answer, or it stopped without finishing. If `armada status` does not show it `ready-to-merge`, `awaiting-approval` or `blocked`, it has stopped: read its last reply, then message it to go on, or release and relaunch the ticket.\n- `error`: the last turn failed (agent or provider failure). Read the transcript and message it to resume; if it fails again, cancel, archive, release and relaunch.\n- Right after launch the session is `idle` for a few seconds while the workspace is initializing and the first message is queued; it turns `working` when the agent starts.\n\nThe workspace itself: `conductor --json workspace status <workspaceId>` gives `status` `initializing`, `ready` or `archived`.\n\n**Read the transcript** to see what a worker did or said. Events come oldest first, 100 per page; `hasMore` tells when to fetch the next page with `--after` the last event id. Keep the last id you read and poll from it.\n\n```sh\nconductor --json session message <sessionId> --limit 100 > /tmp/abc-12-events.json\njq -r '.hasMore, .data[-1].id' /tmp/abc-12-events.json\nconductor --json session message <sessionId> --after <lastEventId> --limit 100\n```\n\nThe second line prints whether more pages exist and the id to continue from. `.content.rawPayload` is the agent's own event format, so the filters depend on the worker's agent (the `agent` of its profile in `armada.toml`).\n\nA `claude` worker: each turn's final reply, then the commands and tools it ran.\n\n```sh\njq -r '.data[] | select(.content.rawPayload.type == \"result\") | .content.rawPayload | \"error=\\(.is_error)\\n\\(.result)\"' /tmp/abc-12-events.json\njq -r '.data[] | select(.content.rawPayload.type == \"assistant\") | .content.rawPayload.message.content[] | select(.type == \"tool_use\") | .input.command // .name' /tmp/abc-12-events.json\n```\n\nA `codex` worker: its events are `.content.rawPayload.event`, each item once as `item.started` and once as `item.completed`; read the completed ones. Its messages (`phase` is `commentary` along the way, `final_answer` at the end of a turn), then each command with its exit code, and its tool calls (Linear and other MCP servers).\n\n```sh\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"agentMessage\") | \"[\\(.phase)] \\(.text)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"commandExecution\") | \"exit=\\(.exitCode) \\(.command)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"mcpToolCall\") | \"\\(.server) \\(.tool)\"' /tmp/abc-12-events.json\n```\n\nAnother agent, or a filter that prints nothing: count the event types, look at one event of the type you need, and adapt the filter.\n\n```sh\njq -r '.data[].content.rawPayload | .type // .event.type // \"(no payload)\"' /tmp/abc-12-events.json | sort | uniq -c\n```\n\n## Stop and archive\n\n```sh\nconductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n\n- `session cancel` stops the running turn: `{\"status\", \"canceledQueuedMessages\"}`, and the session is `idle` within seconds. The workspace stays; a message starts a new turn. Use it on a worker that runs the wrong thing.\n- `workspace archive` answers `{\"status\": \"archived\"}`. Archive a worker's workspace after its pull request is merged, or after `armada release --ticket ABC-12 --reason \"<why>\"` for a worker that stops without handing back. The branch and the pull request stay on GitHub.\n- **Wait for `idle` before archiving.** A hand-back often arrives while the worker's session is still `working`: `armada report ready-to-merge` runs inside its last turn, which then writes its final reply. Archive only once `session status` answers `idle`. Poll it every 15 seconds; if it is still `working` after 10 minutes, cancel the turn and archive (the transcript keeps what it was doing). Run the whole block as one command; it can take up to 10 minutes, so run it in the background or give it a longer command timeout:\n\n```sh\nfor i in $(seq 40); do\n [ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] || break\n sleep 15\ndone\n[ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] && conductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n- After an archive, `session status` still answers `idle`; `workspace status` says `archived`.\n"
6170
+ }
6171
+ ]
6172
+ },
6173
+ {
6174
+ name: "armada-runtime-herdr",
6175
+ files: [
6176
+ {
6177
+ path: "SKILL.md",
6178
+ content: '---\nname: armada-runtime-herdr\ndescription: Runtime guide for persistent Armada workers on this machine through herdr. Four sections cover launch, message, status, and stop with safe worktree archival.\n---\n\nHerdr keeps each worker in its own worktree and terminal across coordinator restarts. Run these commands on the machine that launched the worker, against the same herdr server/session. The claim stores JSON `{workspace,pane,agent}`: recover it from `armada status --json` or the ticket\'s claim comment instead of relying on your old coordinator session. Requires herdr 0.9.1+, a supported harness already signed in, and an Armada coordinator sign-in. Never handle harness keys or sign-ins.\n\n## Launch\n\n```sh\narmada launch ABC-12 --runtime herdr --profile backend --reason "back end work" --json\n```\n\nThe profile in `[herdr.profiles]` selects the harness, model and effort. Label routing wins; use a reason for semantic selection or an override. An optional `--harness claude|codex|opencode|deepseek` checks the selected profile. DeepSeek profiles run OpenCode with the exact configured DeepSeek model; Armada reports their runtime agent as `opencode` while preserving the DeepSeek profile label. Launch checks tools first, creates a worktree, starts the harness, and sends the scoped worker brief. Its JSON gives the `handle` and worktree path, without the token. The worker signs in with its one-time launch token, claims the stored handle and starts its heartbeat. No claim after the configured timeout: read the pane, fix the cause, or revoke the unused launch with `armada launch revoke ABC-12`. Failed launch retains the worktree for inspection.\n\n## Message\n\n```sh\narmada answer <inbox-id> "Plan approved. Go on."\narmada answer ABC-12 "<answer to a live harness approval or question>"\narmada answer --note ABC-12 --message-file /tmp/abc-12-message.md\n```\n\nFor herdr, Armada verifies the saved pane, delivers literal text plus Enter and then records the answer on the ticket and in the inbox. Read an approval UI before deciding what input it expects; the answer may be a short choice such as `y`. Delivery errors leave the question open and write no successful answer. Inspect the pane before retrying after a timeout: the terminal may already have received the input. There is no separate delivery step. Successful delivery confirms submission, not that the worker has completed a turn. For other runtimes, follow their guide and deliver before recording with Armada.\n\n## Status\n\n```sh\narmada status --json\narmada inbox\nherdr agent get <pane>\nherdr agent read <pane> --source recent-unwrapped --lines 120\nherdr agent wait <pane> --until idle --until done --until blocked --timeout 30000\n```\n\n`status`, `inbox` and each `watch` poll discover workers from persisted claims and publish local observations to Armada. The dashboard shows that stored live state beside the last report; it never probes a local runtime. Observations expire after `policy.silence_minutes`.\n\nHerdr\'s `.result.agent` carries `workspace_id`, `pane_id`, `name` and `agent_status`. Verify all three IDs against the claim. `working` is a running turn, `blocked` is an approval or question UI, and `idle`/`done` are ready for input. A live `runtime-blocked` inbox entry can appear before a worker report; read its pane and answer by ticket. It clears after an answer until the next blocked transition. Herdr\'s state-change counter preserves approvals that arrive between polls, even when both readings are blocked. `unknown` falls back to Armada reports; it is not proof of completion. DeepSeek and other harnesses also report their phase to herdr via `pane report-agent --source armada` on report, ask and heartbeat. Reporting failures warn and do not fail the worker command.\n\nTerminal reads print text directly, not JSON. Do not paste credentials or complete transcripts into tickets. A coordinator restart changes no worker handle: read `armada status` and continue from those claims.\n\n## Stop and archive\n\n```sh\n# For unfinished work, release the ticket with its reason first.\narmada release --ticket ABC-12 --reason "<why the worker is being stopped>"\narmada stop ABC-12\n```\n\nAfter merge, run `armada stop ABC-12` directly; the released claim is still discoverable for cleanup. Stop verifies the linked worktree belongs to this repository and the claim\'s branch. It refuses uncommitted files (including untracked files), a missing remote upstream, an unreachable upstream, or commits not on that upstream, and explains what remains. Push or preserve that work before retrying; never force removal. It fetches the configured upstream, interrupts an active turn and waits up to five seconds for idle or done, then rechecks the checkout before `herdr worktree remove --workspace <workspace>` without `--force`. Herdr ends the workspace terminals and removes the checkout; the branch remains. The exact saved claim is marked ended. If the worker does not settle, the checkout stays intact; inspect the pane and retry. Failed removal leaves the claim and checkout for inspection; inspect `herdr worktree list` before retrying a timeout.\n'
6068
6179
  }
6069
6180
  ]
6070
6181
  },
@@ -9797,28 +9908,34 @@ function buildStatus({
9797
9908
  },
9798
9909
  silentAfterMinutes: config.policy.silentAfterMinutes,
9799
9910
  coordinatorMinutes: config.policy.coordinatorMinutes,
9800
- inFlight: lanes.map((l) => ({
9801
- id: l.issue.id,
9802
- title: l.issue.title,
9803
- url: l.issue.url,
9804
- spec: l.spec,
9805
- phase: l.phase,
9806
- phaseSource: l.phaseSource,
9807
- runtime: l.runtime,
9808
- handle: l.handle,
9809
- profile: live?.handles?.[l.issue.id]?.profile ?? l.claim?.profile ?? null,
9810
- profileReason: l.claim?.profileReason ?? null,
9811
- agent: l.agent,
9812
- since: l.since,
9813
- lastUpdate: l.lastUpdate,
9814
- lastReport: l.lastReport,
9815
- lastHeartbeat: l.lastHeartbeat,
9816
- silent: l.flags.includes("silent"),
9817
- statusLine: l.statusLine ? { summary: l.statusLine.summary, at: l.statusLine.at, url: l.statusLine.url, plan: l.statusLine.plan } : null,
9818
- pr: l.pr ? prRef(l.pr) : null,
9819
- openBlockers: l.openBlockers,
9820
- flags: l.flags
9821
- })),
9911
+ inFlight: lanes.map((l) => {
9912
+ const profileName = live?.handles?.[l.issue.id]?.profile ?? l.claim?.profile ?? null;
9913
+ const profile = profileName && l.runtime?.toLowerCase() === "herdr" ? config.herdr.profiles[profileName] : null;
9914
+ return {
9915
+ id: l.issue.id,
9916
+ title: l.issue.title,
9917
+ url: l.issue.url,
9918
+ spec: l.spec,
9919
+ phase: l.phase,
9920
+ phaseSource: l.phaseSource,
9921
+ runtime: l.runtime,
9922
+ handle: l.handle,
9923
+ profile: profileName,
9924
+ profileReason: l.claim?.profileReason ?? null,
9925
+ ...profile ? { harness: herdrHarnessLabel(profile.harness) } : {},
9926
+ agent: l.agent,
9927
+ since: l.since,
9928
+ lastUpdate: l.lastUpdate,
9929
+ lastReport: l.lastReport,
9930
+ lastHeartbeat: l.lastHeartbeat,
9931
+ runtimeState: freshRuntimeState(live?.handles?.[l.issue.id]?.runtimeState, now, config.policy.silentAfterMinutes, live?.handles?.[l.issue.id]?.claimedAt),
9932
+ silent: l.flags.includes("silent"),
9933
+ statusLine: l.statusLine ? { summary: l.statusLine.summary, at: l.statusLine.at, url: l.statusLine.url, plan: l.statusLine.plan } : null,
9934
+ pr: l.pr ? prRef(l.pr) : null,
9935
+ openBlockers: l.openBlockers,
9936
+ flags: l.flags
9937
+ };
9938
+ }),
9822
9939
  pendingLaunches: followedLaunches(launches, now),
9823
9940
  notStarted: notStartedLaunches(launches, now, config.policy.notStartedMinutes).map((l) => {
9824
9941
  const issue = issues.find((i) => i.id === l.ticket);
@@ -9876,12 +9993,15 @@ async function loadStatus(config, opts) {
9876
9993
  const launchesP = opts.launches ? opts.launches().then((launches) => ({ launches }), (err) => ({
9877
9994
  warning: `Armada's launches could not be read (${err instanceof Error ? err.message : String(err)}); workers launched that never started are not listed`
9878
9995
  })) : Promise.resolve({});
9879
- const [{ program, forge, forgeError }, events, launches, heartbeats] = await Promise.all([
9996
+ const [{ program, forge, forgeError }, events, launches, heartbeats, runtimeHandles] = await Promise.all([
9880
9997
  readStatusSources(config, opts),
9881
9998
  eventsP,
9882
9999
  launchesP,
9883
10000
  opts.heartbeats?.().catch(() => {
9884
10001
  return;
10002
+ }),
10003
+ opts.runtimeHandles?.().catch(() => {
10004
+ return;
9885
10005
  })
9886
10006
  ]);
9887
10007
  return buildStatus({
@@ -9891,6 +10011,13 @@ async function loadStatus(config, opts) {
9891
10011
  forgeError,
9892
10012
  ...events.events ? { lastEvents: events.events } : {},
9893
10013
  ...heartbeats ? { heartbeats } : {},
10014
+ ...runtimeHandles ? {
10015
+ live: {
10016
+ after: program.fetchedAt,
10017
+ events: {},
10018
+ handles: Object.fromEntries(runtimeHandles.map((h) => [h.ticket, h]))
10019
+ }
10020
+ } : {},
9894
10021
  ...launches.launches ? { launches: launches.launches } : {},
9895
10022
  extraWarnings: [events.warning, launches.warning].filter((w) => !!w),
9896
10023
  now: now()
@@ -10021,7 +10148,7 @@ ${attachments.join(`
10021
10148
  };
10022
10149
  }
10023
10150
  // package.json
10024
- var version = "0.2.36";
10151
+ var version = "0.2.38";
10025
10152
 
10026
10153
  // src/attach.ts
10027
10154
  import { resolve } from "node:path";
@@ -10558,127 +10685,523 @@ async function logout(io) {
10558
10685
  return 0;
10559
10686
  }
10560
10687
 
10561
- // src/worker.ts
10562
- function liveFleet(io, config, credentials) {
10563
- const signIn = credentials.armadaSignIn;
10564
- if (!signIn)
10565
- return {
10566
- fleet: null,
10567
- warning: "not signed in to Armada (armada login); live activity is not recorded, Linear is"
10568
- };
10569
- try {
10570
- const api = apiOf(io, credentials.armadaApi.url);
10571
- return { fleet: fleetClient({ api, signIn, project: projectOf(config) }), warning: null };
10572
- } catch (err) {
10573
- return {
10574
- fleet: null,
10575
- warning: `${err instanceof Error ? err.message : String(err)}; live activity is not recorded`
10576
- };
10688
+ // src/herdr.ts
10689
+ class HerdrError extends UsageError {
10690
+ code;
10691
+ constructor(message, code) {
10692
+ super(message);
10693
+ this.code = code;
10577
10694
  }
10578
10695
  }
10579
- function statusLive(io, config, credentials) {
10580
- const { fleet } = liveFleet(io, config, credentials);
10581
- return fleet ? {
10582
- lastEvents: () => fleet.lastEventTimes(),
10583
- heartbeats: () => fleet.heartbeatTimes(),
10584
- launches: () => fleet.pendingLaunches()
10585
- } : undefined;
10586
- }
10587
- function currentTicket(io, config, explicit, workers = []) {
10588
- const fromEnv = io.env.ARMADA_TICKET?.trim();
10589
- const id = explicit?.trim() || fromEnv || (() => {
10590
- const branch = io.gitBranch?.();
10591
- return branch ? ticketFromBranch(branch, config.tracker.programRoot) : null;
10592
- })() || (workers.length === 1 ? workers[0] : null);
10593
- if (!id)
10594
- throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
10595
- return id.toUpperCase();
10596
- }
10597
- function context(io, config, credentials) {
10598
- if (!credentials.linearApiKey)
10599
- throw missingKey(LINEAR_KEY);
10600
- const linearOpts = {
10601
- apiKey: credentials.linearApiKey,
10602
- labels: config.tracker.labels,
10603
- ...io.fetch ? { fetch: io.fetch } : {}
10604
- };
10605
- const linear = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
10606
- const live = liveFleet(io, config, credentials);
10607
- const token = credentials.githubToken;
10608
- return {
10609
- config,
10610
- linear,
10611
- fleet: async () => live,
10612
- readPull: token ? (number) => fetchPullRequest({
10613
- token,
10614
- repository: config.github.repository,
10615
- number,
10616
- ...io.fetch ? { fetch: io.fetch } : {}
10617
- }) : null,
10618
- now: io.now ?? (() => new Date)
10619
- };
10620
- }
10621
- function print(io, outcome, json) {
10622
- if (json) {
10623
- io.stdout(`${JSON.stringify(outcome, null, 2)}
10624
- `);
10696
+ var harnessArgs = (p) => [
10697
+ "--model",
10698
+ herdrHarnessKind(p.harness) === "opencode" ? `${p.model.split("#")[0]}#${p.effort}` : p.model,
10699
+ ...p.harness === "codex" ? ["-c", `model_reasoning_effort=${JSON.stringify(p.effort)}`] : p.harness === "claude" ? ["--effort", p.effort] : [],
10700
+ ...p.extraArgs
10701
+ ];
10702
+ var object = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : null;
10703
+ var id = (v) => typeof v === "string" && /^[a-zA-Z0-9][a-zA-Z0-9:_-]{0,127}$/.test(v);
10704
+ function parseHerdrHandle(raw) {
10705
+ let h = null;
10706
+ try {
10707
+ h = object(JSON.parse(raw));
10708
+ } catch {}
10709
+ if (!h || !id(h.workspace) || !id(h.pane) || !id(h.agent) || !/^[a-z][a-z0-9_-]{0,31}$/.test(h.agent))
10710
+ throw new UsageError("invalid herdr claim handle; expected JSON with workspace, pane and agent");
10711
+ return { workspace: h.workspace, pane: h.pane, agent: h.agent };
10712
+ }
10713
+ function herdrPhase(phase) {
10714
+ if (phase === "blocked" || phase === "awaiting-approval" || phase === "awaiting-validation")
10715
+ return "blocked";
10716
+ if (phase === "ready-to-merge")
10717
+ return "idle";
10718
+ return phase && ["planning", "implementing", "shipping"].includes(phase) ? "working" : "unknown";
10719
+ }
10720
+ async function reportHerdr(io, phase, agent, heartbeat = false) {
10721
+ if (io.env.HERDR_ENV !== "1" || !io.env.HERDR_PANE_ID)
10625
10722
  return;
10626
- }
10627
- const out = [...outcome.lines];
10628
- const s = outcome.state;
10629
- if (s)
10630
- out.push(`Now: ${s.status} · phase ${s.phase ?? "none"} · runtime ${s.runtime ?? "none"} · profile ${s.profile ?? "none"}`);
10631
- out.push(outcome.url);
10632
- if (outcome.inbox) {
10633
- if (!outcome.inbox.length)
10634
- out.push("Inbox: nothing waiting for you.");
10635
- else {
10636
- out.push(`Inbox (${outcome.inbox.length}) — read and act on these:`);
10637
- for (const item of outcome.inbox)
10638
- out.push(` #${item.id} ${item.kind}${item.author ? ` from ${item.author}` : ""} · ${item.createdAt}`, ...item.body.split(`
10639
- `).map((l) => ` ${l}`));
10640
- }
10641
- }
10642
- io.stdout(`${out.join(`
10643
- `)}
10644
- `);
10645
- for (const w of outcome.warnings)
10646
- io.stderr(`armada: warning: ${w}
10723
+ try {
10724
+ if (!id(io.env.HERDR_PANE_ID))
10725
+ throw new Error("invalid pane");
10726
+ await new Herdr(io).report(io.env.HERDR_PANE_ID, agent, herdrPhase(phase), heartbeat);
10727
+ } catch {
10728
+ io.stderr(`armada: warning: could not report worker state to herdr; Armada reporting continues.
10647
10729
  `);
10730
+ }
10648
10731
  }
10649
- async function readMessage(io, options, name = "message") {
10650
- const fileOption = `${name}-file`;
10651
- if (options[name] !== undefined && options[fileOption] !== undefined)
10652
- throw new UsageError(`pass --${name} or --${fileOption}, not both`);
10653
- const file = options[fileOption];
10654
- if (file === undefined)
10655
- return options[name] ?? null;
10656
- const text = file === "-" ? await io.readStdin?.() ?? null : await io.readFile(file);
10657
- if (text === null)
10658
- throw new UsageError(`cannot read the ${name} from ${file}`);
10659
- if (!text.trim())
10660
- throw new UsageError(`${file === "-" ? "standard input" : `${name} file ${file}`} is empty or whitespace-only`, `pass --${name} "<text>" or pipe a non-empty ${name} into --${fileOption} -`);
10661
- return text;
10662
- }
10663
- async function withContext(io, config, credentials, json, act) {
10664
- print(io, await act(context(io, config, credentials)), json);
10665
- return 0;
10666
- }
10667
- async function claim(io, config, credentials, a) {
10668
- const [ticket, ...extra] = a.rest;
10669
- if (!ticket)
10670
- throw new UsageError("claim needs a ticket: armada claim <ticket> --runtime <name> --handle <id>");
10671
- if (extra.length)
10672
- throw new UsageError(`unexpected argument ${extra[0]}`);
10673
- const runtime = a.options.runtime?.trim();
10674
- const handle = a.options.handle?.trim();
10675
- if (!runtime)
10676
- throw new UsageError("--runtime is required, e.g. --runtime conductor");
10677
- const profile = a.options.profile?.trim() || null;
10678
- const reason = a.options.reason?.trim() || null;
10679
- if (reason && !profile)
10680
- throw new UsageError("--reason goes with --profile: it says why the routed profile is not used");
10681
- try {
10732
+ var runtimeEnvironment = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => /^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TMP|TEMP|LANG|TERM|LC_[A-Z_]+|XDG_(CONFIG_HOME|DATA_HOME|STATE_HOME|CACHE_HOME|RUNTIME_DIR)|HERDR_(SESSION|SOCKET_PATH|CONFIG_PATH))$/.test(name)));
10733
+ var credentialNames = (env, extra) => [
10734
+ ...new Set([
10735
+ "LINEAR_API_KEY",
10736
+ "GITHUB_TOKEN",
10737
+ "GH_TOKEN",
10738
+ "ARMADA_API_KEY",
10739
+ "ARMADA_SESSION_TOKEN",
10740
+ "ARMADA_SIGNED_IN_TO",
10741
+ "ARMADA_API_URL",
10742
+ "OPENAI_API_KEY",
10743
+ "ANTHROPIC_API_KEY",
10744
+ ...Object.keys(env).filter((name) => /^(ARMADA_|CONDUCTOR_)|(?:KEY|TOKEN|SECRET|PASSWORD)$/.test(name)),
10745
+ ...extra
10746
+ ])
10747
+ ].filter((name) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name)).sort();
10748
+
10749
+ class Herdr {
10750
+ io;
10751
+ constructor(io) {
10752
+ this.io = io;
10753
+ }
10754
+ async call(args, timeoutMs = 40000) {
10755
+ const operation = args.slice(0, 2).join(" ");
10756
+ let reply;
10757
+ let code;
10758
+ try {
10759
+ if (!this.io.exec)
10760
+ throw new Error("no exec");
10761
+ const out = await this.io.exec("herdr", args, { cwd: this.io.cwd, timeoutMs });
10762
+ code = out.code;
10763
+ if (code === 0 && !out.stdout.trim() && !out.stderr.trim() && ["pane run", "pane report-agent"].includes(operation))
10764
+ return {};
10765
+ reply = object(JSON.parse(out.stdout || out.stderr));
10766
+ } catch {
10767
+ throw new UsageError(`herdr ${operation} failed; inspect the runtime with herdr agent list`);
10768
+ }
10769
+ const error = object(reply?.error);
10770
+ if (code !== 0 || error) {
10771
+ const reason = typeof error?.code === "string" && /^[a-z_]{1,64}$/.test(error.code) ? ` (${error.code})` : "";
10772
+ throw new HerdrError(`herdr ${operation} failed${reason}; inspect the runtime with herdr agent list`, reason ? String(error?.code) : null);
10773
+ }
10774
+ if (!reply)
10775
+ throw new UsageError(`herdr ${operation} returned invalid JSON`);
10776
+ return reply;
10777
+ }
10778
+ async ensureServer() {
10779
+ const status = async (timeoutMs) => {
10780
+ const server = object((await this.call(["status", "--json"], timeoutMs)).server);
10781
+ if (!server || typeof server.running !== "boolean")
10782
+ throw new UsageError("invalid herdr server status response");
10783
+ if (server.running && (server.compatible === false || server.endpoint_compatible === false))
10784
+ throw new UsageError("the running herdr server is incompatible; update or restart it before launching");
10785
+ return server.running;
10786
+ };
10787
+ if (await status(5000))
10788
+ return;
10789
+ if (!this.io.detach || !await this.io.detach("herdr", ["server"], { cwd: this.io.cwd, env: runtimeEnvironment(this.io.env) }))
10790
+ throw new UsageError("could not start herdr server; start it headless with herdr server");
10791
+ const now = this.io.now ?? (() => new Date);
10792
+ const deadline = now().getTime() + 5000;
10793
+ for (let attempt = 0;attempt < 20; attempt++) {
10794
+ const remaining = deadline - now().getTime();
10795
+ if (remaining <= 0)
10796
+ break;
10797
+ if (await status(Math.min(1000, remaining)))
10798
+ return;
10799
+ const delay = Math.min(250, deadline - now().getTime());
10800
+ if (delay > 0)
10801
+ await (this.io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))))(delay);
10802
+ }
10803
+ throw new UsageError("herdr server did not become ready; inspect herdr status");
10804
+ }
10805
+ async create(input) {
10806
+ const agent = input.ticket.toLowerCase();
10807
+ if (!/^[a-z][a-z0-9_-]{0,31}$/.test(agent))
10808
+ throw new UsageError("ticket cannot be used as a herdr agent name");
10809
+ const r = object((await this.call([
10810
+ "worktree",
10811
+ "create",
10812
+ "--cwd",
10813
+ input.repo,
10814
+ "--branch",
10815
+ input.branch,
10816
+ "--base",
10817
+ input.base,
10818
+ "--no-focus"
10819
+ ])).result);
10820
+ const workspace = object(r?.workspace)?.workspace_id;
10821
+ const rootPane = object(r?.root_pane)?.pane_id;
10822
+ const path = object(r?.worktree)?.path;
10823
+ if (!id(workspace) || !id(rootPane) || typeof path !== "string" || !path.startsWith("/") || object(r?.root_pane)?.workspace_id !== workspace)
10824
+ throw new UsageError("invalid herdr worktree response; inspect herdr worktree list before retrying");
10825
+ const tab = object((await this.call([
10826
+ "tab",
10827
+ "create",
10828
+ "--workspace",
10829
+ workspace,
10830
+ "--cwd",
10831
+ path,
10832
+ "--no-focus",
10833
+ ...credentialNames(this.io.env, input.secrets ?? []).flatMap((name) => ["--env", `${name}=`]),
10834
+ "--env",
10835
+ `ARMADA_TICKET=${input.ticket}`
10836
+ ])).result);
10837
+ const pane = object(tab?.root_pane)?.pane_id;
10838
+ if (!id(pane) || pane === rootPane || object(tab?.root_pane)?.workspace_id !== workspace)
10839
+ throw new UsageError("invalid herdr worker pane response; inspect herdr pane list before retrying");
10840
+ await this.call(["pane", "close", rootPane]);
10841
+ return { workspace, pane, agent, path };
10842
+ }
10843
+ async start(handle, profile) {
10844
+ const r = await this.call([
10845
+ "agent",
10846
+ "start",
10847
+ handle.agent,
10848
+ "--kind",
10849
+ herdrHarnessKind(profile.harness),
10850
+ "--pane",
10851
+ handle.pane,
10852
+ "--timeout",
10853
+ "30000",
10854
+ "--",
10855
+ ...harnessArgs(profile)
10856
+ ]);
10857
+ this.checkAgent(r, handle);
10858
+ }
10859
+ async prompt(handle, prompt) {
10860
+ const r = await this.call([
10861
+ "agent",
10862
+ "prompt",
10863
+ handle.agent,
10864
+ prompt,
10865
+ "--wait",
10866
+ "--until",
10867
+ "working",
10868
+ "--timeout",
10869
+ "30000"
10870
+ ]);
10871
+ const agent = this.checkAgent(r, handle);
10872
+ if (agent.agent_status !== "working")
10873
+ throw new UsageError("herdr did not confirm the worker is working");
10874
+ }
10875
+ async state(handle) {
10876
+ return (await this.reading(handle)).state;
10877
+ }
10878
+ async reading(handle) {
10879
+ const agent = this.checkAgent(await this.call(["agent", "get", handle.pane], 5000), handle);
10880
+ const state = agent.agent_status;
10881
+ if (!["working", "blocked", "idle", "done", "unknown"].includes(String(state)))
10882
+ throw new UsageError("invalid herdr agent state");
10883
+ const sequence = agent.state_change_seq;
10884
+ if (sequence !== undefined && (!Number.isSafeInteger(sequence) || Number(sequence) < 0))
10885
+ throw new UsageError("invalid herdr state-change sequence");
10886
+ return { state, ...sequence === undefined ? {} : { sequence: Number(sequence) } };
10887
+ }
10888
+ async message(handle, text) {
10889
+ const state = await this.state(handle);
10890
+ if (state === "blocked")
10891
+ await this.call(["pane", "run", handle.pane, text]);
10892
+ else
10893
+ this.checkAgent(await this.call(["agent", "prompt", handle.pane, text]), handle);
10894
+ }
10895
+ async quiesce(handle) {
10896
+ const state = await this.state(handle);
10897
+ if (state === "idle" || state === "done")
10898
+ return;
10899
+ if (state === "unknown")
10900
+ throw new UsageError("cannot stop an unverified active turn; wait for herdr idle state");
10901
+ await this.call(["agent", "send-keys", handle.pane, "ctrl+c"], 5000);
10902
+ const agent = this.checkAgent(await this.call(["agent", "wait", handle.pane, "--until", "idle", "--until", "done", "--timeout", "5000"], 7000), handle);
10903
+ if (agent.agent_status !== "idle" && agent.agent_status !== "done")
10904
+ throw new UsageError("worker is still active; its worktree was retained");
10905
+ }
10906
+ async report(pane, agent, state, heartbeat = false) {
10907
+ if (agent === "armada" || heartbeat) {
10908
+ const current = object(object((await this.call(["pane", "get", pane], 5000)).result)?.pane);
10909
+ if (current?.pane_id !== pane)
10910
+ throw new UsageError("invalid herdr pane response");
10911
+ if (agent === "armada" && typeof current.agent === "string" && current.agent)
10912
+ agent = current.agent;
10913
+ if (heartbeat && state === "working" && current.agent_status === "blocked")
10914
+ state = "blocked";
10915
+ }
10916
+ if (agent === "deepseek" || agent === herdrHarnessLabel("deepseek"))
10917
+ agent = herdrHarnessKind("deepseek");
10918
+ await this.call(["pane", "report-agent", pane, "--source", "armada", "--agent", agent, "--state", state], 5000);
10919
+ }
10920
+ async worktree(handle) {
10921
+ const ws = object(object((await this.call(["workspace", "get", handle.workspace], 5000)).result)?.workspace);
10922
+ const tree = object(ws?.worktree);
10923
+ if (ws?.workspace_id !== handle.workspace || tree?.is_linked_worktree !== true || typeof tree.repo_root !== "string" || !tree.repo_root.startsWith("/") || typeof tree.checkout_path !== "string" || !tree.checkout_path.startsWith("/") || tree.repo_root === tree.checkout_path)
10924
+ throw new UsageError("herdr workspace is not a verified linked worktree; left it untouched");
10925
+ return { repo: tree.repo_root, path: tree.checkout_path };
10926
+ }
10927
+ async remove(handle, path) {
10928
+ const result = object((await this.call(["worktree", "remove", "--workspace", handle.workspace])).result);
10929
+ if (result?.workspace_id !== handle.workspace || result?.path !== path || result?.forced !== false)
10930
+ throw new UsageError("invalid herdr worktree removal response; inspect herdr worktree list before retrying");
10931
+ }
10932
+ checkAgent(reply, handle) {
10933
+ const agent = object(object(reply.result)?.agent);
10934
+ if (!agent || agent.name !== handle.agent || agent.pane_id !== handle.pane || agent.workspace_id !== handle.workspace)
10935
+ throw new UsageError("invalid herdr agent response; inspect herdr agent list before retrying");
10936
+ return agent;
10937
+ }
10938
+ }
10939
+
10940
+ // src/runtime.ts
10941
+ var isHerdr = (runtime) => runtime.toLowerCase() === "herdr";
10942
+ async function observeHerdr(io, fleet) {
10943
+ const handles = await fleet.runtimeHandles();
10944
+ const local = handles.filter((h) => isHerdr(h.runtime));
10945
+ if (!local.length)
10946
+ return handles;
10947
+ await Promise.all(local.map(async (h) => {
10948
+ try {
10949
+ await verifyProvenance(io, h);
10950
+ const reading = await new Herdr(io).reading(parseHerdrHandle(h.handle));
10951
+ await fleet.observeRuntime({ ticket: h.ticket, handle: h.handle, claimedAt: h.claimedAt, ...reading });
10952
+ } catch {}
10953
+ }));
10954
+ return fleet.runtimeHandles();
10955
+ }
10956
+ function observingFleet(io, fleet) {
10957
+ return {
10958
+ ...fleet,
10959
+ inbox: async (query) => {
10960
+ try {
10961
+ await observeHerdr(io, fleet);
10962
+ } catch {}
10963
+ return fleet.inbox(query);
10964
+ }
10965
+ };
10966
+ }
10967
+ async function deliverHerdr(io, fleet, ticket, text, expected) {
10968
+ const h = await fleet.runtimeHandle(ticket);
10969
+ if (!h || !isHerdr(h.runtime))
10970
+ return false;
10971
+ if (!expected || h.handle !== expected.handle || h.claimedAt !== expected.claimedAt)
10972
+ throw new Refusal(`${ticket}'s claim changed before delivery; no answer was delivered`, "armada inbox");
10973
+ if (h.releasedAt)
10974
+ throw new Refusal(`${ticket}'s herdr worker has ended; no answer was delivered`, "armada status");
10975
+ await verifyProvenance(io, h);
10976
+ const current = await fleet.runtimeHandle(ticket);
10977
+ if (!current || current.handle !== h.handle || current.claimedAt !== h.claimedAt || current.releasedAt)
10978
+ throw new Refusal(`${ticket}'s claim changed before delivery; no answer was delivered`, "armada inbox");
10979
+ await new Herdr(io).message(parseHerdrHandle(h.handle), text);
10980
+ return true;
10981
+ }
10982
+ async function verifyProvenance(io, h) {
10983
+ const tree = await new Herdr(io).worktree(parseHerdrHandle(h.handle));
10984
+ const git = async (cwd, args) => {
10985
+ const result = await io.exec?.("git", args, { cwd, timeoutMs: 5000 });
10986
+ if (result?.code !== 0)
10987
+ throw new Refusal("could not verify the herdr claim repository", "armada status");
10988
+ return result.stdout.trim();
10989
+ };
10990
+ const commonArgs = ["rev-parse", "--path-format=absolute", "--git-common-dir"];
10991
+ const local = await git(io.cwd, commonArgs);
10992
+ const worker = await git(tree.path, commonArgs);
10993
+ if (!local || local !== worker || !h.branch || await git(tree.path, ["branch", "--show-current"]) !== h.branch)
10994
+ throw new Refusal("herdr workspace does not match the claimed repository and branch", "armada status");
10995
+ }
10996
+ async function stop(io, config, credentials, args) {
10997
+ const [raw, ...extra] = args.rest;
10998
+ if (!raw || extra.length)
10999
+ throw new Refusal("stop needs one ticket: armada stop <ticket>", "armada stop --help");
11000
+ requireSignIn(credentials);
11001
+ const { fleet } = liveFleet(io, config, credentials);
11002
+ if (!fleet)
11003
+ throw new Refusal("stop needs Armada's stored claim", "armada whoami");
11004
+ const ticket = raw.toUpperCase();
11005
+ const h = await fleet.runtimeHandle(ticket);
11006
+ if (!h || !isHerdr(h.runtime))
11007
+ throw new Refusal(`${ticket} has no herdr claim to stop`, "armada status");
11008
+ const handle = parseHerdrHandle(h.handle);
11009
+ const runtime = new Herdr(io);
11010
+ let tree;
11011
+ try {
11012
+ tree = await runtime.worktree(handle);
11013
+ } catch (error) {
11014
+ if (!(error instanceof HerdrError) || error.code !== "workspace_not_found")
11015
+ throw error;
11016
+ if (!await fleet.stopRuntime({ ticket, handle: h.handle, claimedAt: h.claimedAt }))
11017
+ throw new Refusal("claim changed during archive recovery", "armada status");
11018
+ io.stdout(args.json ? `${JSON.stringify({ ticket, stopped: true, alreadyAbsent: true })}
11019
+ ` : `${ticket}'s herdr workspace is already absent; its claim is ended.
11020
+ `);
11021
+ return 0;
11022
+ }
11023
+ const git = async (cwd, argv) => {
11024
+ const r = await io.exec?.("git", argv, { cwd, timeoutMs: 30000 });
11025
+ if (r?.code !== 0)
11026
+ throw new Refusal("could not verify the worker's Git state; left its worktree untouched", `git -C ${tree.path} status`);
11027
+ return r.stdout.trim();
11028
+ };
11029
+ const localCommon = await git(io.cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
11030
+ const treeCommon = await git(tree.path, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
11031
+ const branch = await git(tree.path, ["branch", "--show-current"]);
11032
+ if (localCommon !== treeCommon || !h.branch || branch !== h.branch)
11033
+ throw new Refusal("herdr worktree does not match this repository and claim branch; left it untouched", "herdr worktree list");
11034
+ const dirty = await git(tree.path, ["status", "--porcelain=v1", "--untracked-files=all"]);
11035
+ if (dirty)
11036
+ throw new Refusal(`cannot stop ${ticket}: uncommitted work remains:
11037
+ ${dirty}`, `git -C ${tree.path} status`);
11038
+ const upstream = await git(tree.path, [
11039
+ "for-each-ref",
11040
+ "--format=%(upstream:remotename)%00%(upstream:remoteref)",
11041
+ `refs/heads/${branch}`
11042
+ ]);
11043
+ const [remote, ref] = upstream.split("\x00");
11044
+ if (!remote || remote === "." || remote.startsWith("-") || !ref?.startsWith("refs/heads/"))
11045
+ throw new Refusal(`cannot stop ${ticket}: the branch has no verified remote upstream`, `git -C ${tree.path} push -u origin ${branch}`);
11046
+ const advertised = await git(tree.path, ["ls-remote", "--exit-code", "--heads", "--", remote, ref]);
11047
+ const [remoteHead, remoteRef] = advertised.split("\t");
11048
+ if (!/^[a-f0-9]{40,64}$/.test(remoteHead ?? "") || remoteRef !== ref)
11049
+ throw new Refusal(`cannot stop ${ticket}: could not verify the upstream head`, `git -C ${tree.path} fetch`);
11050
+ await git(tree.path, ["fetch", "--no-tags", "--no-write-fetch-head", "--", remote, ref]);
11051
+ const localHead = await git(tree.path, ["rev-parse", "HEAD"]);
11052
+ const left = await git(tree.path, ["log", "--format=%h %s", `${remoteHead}..${localHead}`]);
11053
+ if (left)
11054
+ throw new Refusal(`cannot stop ${ticket}: unpushed commits remain:
11055
+ ${left}`, `git -C ${tree.path} push`);
11056
+ await runtime.quiesce(handle);
11057
+ if (await git(tree.path, ["status", "--porcelain=v1", "--untracked-files=all"]))
11058
+ throw new Refusal(`cannot stop ${ticket}: the worktree changed during verification`, `git -C ${tree.path} status`);
11059
+ const current = await fleet.runtimeHandle(ticket);
11060
+ if (!current || current.handle !== h.handle || current.claimedAt !== h.claimedAt)
11061
+ throw new Refusal(`${ticket}'s claim changed; left the runtime untouched`, "armada status");
11062
+ const state = await runtime.state(handle);
11063
+ if (state !== "idle" && state !== "done")
11064
+ throw new Refusal("worker resumed during stop; left its worktree untouched", "armada status");
11065
+ if (await git(tree.path, ["rev-parse", "HEAD"]) !== localHead)
11066
+ throw new Refusal(`cannot stop ${ticket}: new commits appeared during verification`, `git -C ${tree.path} status`);
11067
+ await runtime.remove(handle, tree.path);
11068
+ if (!await fleet.stopRuntime({ ticket, handle: h.handle, claimedAt: h.claimedAt }))
11069
+ throw new Refusal("worktree removed, but claim changed during cleanup; inspect the new claim", "armada status");
11070
+ const result = { ticket, path: tree.path, stopped: true };
11071
+ io.stdout(args.json ? `${JSON.stringify(result, null, 2)}
11072
+ ` : `Stopped ${ticket} and removed ${tree.path}; its branch is retained.
11073
+ `);
11074
+ return 0;
11075
+ }
11076
+
11077
+ // src/worker.ts
11078
+ function liveFleet(io, config, credentials) {
11079
+ const signIn = credentials.armadaSignIn;
11080
+ if (!signIn)
11081
+ return {
11082
+ fleet: null,
11083
+ warning: "not signed in to Armada (armada login); live activity is not recorded, Linear is"
11084
+ };
11085
+ try {
11086
+ const api = apiOf(io, credentials.armadaApi.url);
11087
+ return { fleet: fleetClient({ api, signIn, project: projectOf(config) }), warning: null };
11088
+ } catch (err) {
11089
+ return {
11090
+ fleet: null,
11091
+ warning: `${err instanceof Error ? err.message : String(err)}; live activity is not recorded`
11092
+ };
11093
+ }
11094
+ }
11095
+ function statusLive(io, config, credentials) {
11096
+ const { fleet } = liveFleet(io, config, credentials);
11097
+ return fleet ? {
11098
+ lastEvents: () => fleet.lastEventTimes(),
11099
+ heartbeats: () => fleet.heartbeatTimes(),
11100
+ launches: () => fleet.pendingLaunches(),
11101
+ runtimeHandles: () => observeHerdr(io, fleet)
11102
+ } : undefined;
11103
+ }
11104
+ function currentTicket(io, config, explicit, workers = []) {
11105
+ const fromEnv = io.env.ARMADA_TICKET?.trim();
11106
+ const id = explicit?.trim() || fromEnv || (() => {
11107
+ const branch = io.gitBranch?.();
11108
+ return branch ? ticketFromBranch(branch, config.tracker.programRoot) : null;
11109
+ })() || (workers.length === 1 ? workers[0] : null);
11110
+ if (!id)
11111
+ throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
11112
+ return id.toUpperCase();
11113
+ }
11114
+ function context(io, config, credentials) {
11115
+ if (!credentials.linearApiKey)
11116
+ throw missingKey(LINEAR_KEY);
11117
+ const linearOpts = {
11118
+ apiKey: credentials.linearApiKey,
11119
+ labels: config.tracker.labels,
11120
+ ...io.fetch ? { fetch: io.fetch } : {}
11121
+ };
11122
+ const linear = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
11123
+ const live = liveFleet(io, config, credentials);
11124
+ const token = credentials.githubToken;
11125
+ return {
11126
+ config,
11127
+ linear,
11128
+ fleet: async () => live,
11129
+ readPull: token ? (number) => fetchPullRequest({
11130
+ token,
11131
+ repository: config.github.repository,
11132
+ number,
11133
+ ...io.fetch ? { fetch: io.fetch } : {}
11134
+ }) : null,
11135
+ now: io.now ?? (() => new Date)
11136
+ };
11137
+ }
11138
+ function print(io, outcome, json) {
11139
+ if (json) {
11140
+ io.stdout(`${JSON.stringify(outcome, null, 2)}
11141
+ `);
11142
+ return;
11143
+ }
11144
+ const out = [...outcome.lines];
11145
+ const s = outcome.state;
11146
+ if (s)
11147
+ out.push(`Now: ${s.status} · phase ${s.phase ?? "none"} · runtime ${s.runtime ?? "none"} · profile ${s.profile ?? "none"}`);
11148
+ out.push(outcome.url);
11149
+ if (outcome.inbox) {
11150
+ if (!outcome.inbox.length)
11151
+ out.push("Inbox: nothing waiting for you.");
11152
+ else {
11153
+ out.push(`Inbox (${outcome.inbox.length}) — read and act on these:`);
11154
+ for (const item of outcome.inbox)
11155
+ out.push(` #${item.id} ${item.kind}${item.author ? ` from ${item.author}` : ""} · ${item.createdAt}`, ...item.body.split(`
11156
+ `).map((l) => ` ${l}`));
11157
+ }
11158
+ }
11159
+ io.stdout(`${out.join(`
11160
+ `)}
11161
+ `);
11162
+ for (const w of outcome.warnings)
11163
+ io.stderr(`armada: warning: ${w}
11164
+ `);
11165
+ }
11166
+ async function readMessage(io, options, name = "message") {
11167
+ const fileOption = `${name}-file`;
11168
+ if (options[name] !== undefined && options[fileOption] !== undefined)
11169
+ throw new UsageError(`pass --${name} or --${fileOption}, not both`);
11170
+ const file = options[fileOption];
11171
+ if (file === undefined)
11172
+ return options[name] ?? null;
11173
+ const text = file === "-" ? await io.readStdin?.() ?? null : await io.readFile(file);
11174
+ if (text === null)
11175
+ throw new UsageError(`cannot read the ${name} from ${file}`);
11176
+ if (!text.trim())
11177
+ throw new UsageError(`${file === "-" ? "standard input" : `${name} file ${file}`} is empty or whitespace-only`, `pass --${name} "<text>" or pipe a non-empty ${name} into --${fileOption} -`);
11178
+ return text;
11179
+ }
11180
+ async function withContext(io, config, credentials, json, act) {
11181
+ const outcome = await act(context(io, config, credentials));
11182
+ if (outcome.state?.phase) {
11183
+ const profile = outcome.state.profile;
11184
+ const agent = profile ? config.herdr.profiles[profile]?.harness : null;
11185
+ await reportHerdr(io, outcome.state.phase, agent ?? "armada");
11186
+ }
11187
+ print(io, outcome, json);
11188
+ return 0;
11189
+ }
11190
+ async function claim(io, config, credentials, a) {
11191
+ const [ticket, ...extra] = a.rest;
11192
+ if (!ticket)
11193
+ throw new UsageError("claim needs a ticket: armada claim <ticket> --runtime <name> --handle <id>");
11194
+ if (extra.length)
11195
+ throw new UsageError(`unexpected argument ${extra[0]}`);
11196
+ const runtime = a.options.runtime?.trim();
11197
+ const handle = a.options.handle?.trim();
11198
+ if (!runtime)
11199
+ throw new UsageError("--runtime is required, e.g. --runtime conductor");
11200
+ const profile = a.options.profile?.trim() || null;
11201
+ const reason = a.options.reason?.trim() || null;
11202
+ if (reason && !profile)
11203
+ throw new UsageError("--reason goes with --profile: it says why the routed profile is not used");
11204
+ try {
10682
11205
  checkRequestedProfile(config, profile, a.options.runtime?.toLowerCase() === "herdr" ? "herdr" : "conductor");
10683
11206
  } catch (err) {
10684
11207
  if (err instanceof ProfileError)
@@ -10824,7 +11347,23 @@ async function answer(io, config, credentials, a) {
10824
11347
  const text = positional ?? fromOption;
10825
11348
  if (!text?.trim())
10826
11349
  throw new UsageError(`answer needs the text: ${usage}`);
10827
- return withContext(io, config, credentials, a.json, (ctx) => answerItem(ctx, { target, text, note }));
11350
+ return withContext(io, config, credentials, a.json, (ctx) => answerItem({
11351
+ ...ctx,
11352
+ deliverAnswer: async (ticket, message, runtime, claim) => {
11353
+ if (runtime && runtime.toLowerCase() !== "herdr")
11354
+ return false;
11355
+ const { fleet } = liveFleet(io, config, credentials);
11356
+ if (!fleet) {
11357
+ if (runtime?.toLowerCase() === "herdr")
11358
+ throw new Refusal("cannot read the herdr claim before delivery", "armada whoami");
11359
+ return false;
11360
+ }
11361
+ const delivered = await deliverHerdr(io, fleet, ticket, message, claim);
11362
+ if (!delivered && runtime?.toLowerCase() === "herdr")
11363
+ throw new Refusal("the herdr claim is missing or changed; no answer was delivered", "armada status");
11364
+ return delivered;
11365
+ }
11366
+ }, { target, text, note }));
10828
11367
  }
10829
11368
  function waitSeconds(raw) {
10830
11369
  if (raw === undefined)
@@ -10853,10 +11392,12 @@ function renderEntries(project, items) {
10853
11392
  if (e.kind === "hand-back" && !/shipped with (?:ship-pr-dev|the fallback:)|shipping path unreported/.test(e.body))
10854
11393
  out.push(" shipping path unreported");
10855
11394
  }
11395
+ if (items.some((e) => e.kind === "runtime-blocked"))
11396
+ out.push('Read the blocked herdr pane with its runtime guide, then answer: armada answer <ticket> "<answer>".');
10856
11397
  if (items.some((e) => e.kind === "question" || e.kind === "plan"))
10857
- out.push(`Deliver each answer in the worker's session with the runtime guide, then record it: armada answer <id> "<answer>".`);
11398
+ out.push(`For herdr, armada answer delivers automatically. Deliver each other answer in the worker's session with the runtime guide, then record it: armada answer <id> "<answer>".`);
10858
11399
  if (items.some((e) => ["answer-request", "launch-request", "merge-request", "release-request", "plan-changes"].includes(e.kind)))
10859
- out.push('Dashboard requests: deliver an answer-request, then armada answer <id> "<answer>"; launch a launch-request (its claim resolves it), or decline it with armada answer <id> "<why>". Handle or decline merge-request, release-request and plan-changes, then resolve them with armada answer <id> "<result>". Plan changes are not an approval.');
11400
+ out.push('Dashboard requests: armada answer <id> "<answer>" delivers herdr answer-requests automatically; deliver answers for other runtimes first; launch a launch-request (its claim resolves it), or decline it with armada answer <id> "<why>". Handle or decline merge-request, release-request and plan-changes, then resolve them with armada answer <id> "<result>". Plan changes are not an approval.');
10860
11401
  return out;
10861
11402
  }
10862
11403
  function renderInbox(r, next) {
@@ -10881,7 +11422,7 @@ async function inbox(io, config, credentials, a) {
10881
11422
  const { fleet, warning } = liveFleet(io, config, credentials);
10882
11423
  if (!fleet)
10883
11424
  throw new Refusal(`the inbox is on Armada, which cannot be reached: ${warning ?? "no answer"}`, "armada whoami");
10884
- const report = await checkInbox(fleet, {
11425
+ const report = await checkInbox(observingFleet(io, fleet), {
10885
11426
  project: config.project.slug,
10886
11427
  coordinator: coordinatorHandle(io),
10887
11428
  facts: detectCoordinator(io),
@@ -11081,7 +11622,7 @@ async function watchUntil(io, config, credentials, json, configPath) {
11081
11622
  throw new Refusal(`the inbox is on Armada, which cannot be reached: ${warning ?? "no answer"}`, "armada whoami");
11082
11623
  const before = paths ? await readWatchState(paths, project) : null;
11083
11624
  await remember(io, project, { root: dirname2(configPath), stopped: null });
11084
- const report = await watchInbox(fleet, {
11625
+ const report = await watchInbox(observingFleet(watchingIo, fleet), {
11085
11626
  project,
11086
11627
  signal: controller.signal,
11087
11628
  coordinator: coordinatorHandle(io),
@@ -11350,6 +11891,9 @@ ${next.line}
11350
11891
  return 0;
11351
11892
  }
11352
11893
 
11894
+ // src/doctor.ts
11895
+ import { join as join4 } from "node:path";
11896
+
11353
11897
  // src/local-tools.ts
11354
11898
  import { stripVTControlCharacters } from "node:util";
11355
11899
  var MINIMUM_HERDR_VERSION = "0.9.1";
@@ -11358,11 +11902,14 @@ var TOOLS = {
11358
11902
  claude: { command: "claude", install: "curl -fsSL https://claude.ai/install.sh | bash" },
11359
11903
  codex: { command: "codex", install: "npm i -g @openai/codex" },
11360
11904
  opencode: { command: "opencode", install: "curl -fsSL https://opencode.ai/install | bash" },
11361
- deepseek: { command: "dsh", install: "npm i -g @deepseek-ai/dsh" }
11905
+ dsh: { command: "dsh", install: "" }
11362
11906
  };
11363
11907
  function localHarnesses(config) {
11364
11908
  return [...new Set(Object.values(config.herdr?.profiles ?? {}).map((profile) => profile.harness))];
11365
11909
  }
11910
+ function localModelProfiles(config) {
11911
+ return Object.entries(config.herdr?.profiles ?? {}).flatMap(([name, profile]) => profile.harness === "opencode" || profile.harness === "deepseek" ? [{ name, harness: profile.harness, model: profile.model ?? "" }] : []);
11912
+ }
11366
11913
  async function probe(io, command, args) {
11367
11914
  if (!io.exec)
11368
11915
  return null;
@@ -11443,7 +11990,7 @@ async function signInCheck(io, harness) {
11443
11990
  }
11444
11991
  } catch {}
11445
11992
  }
11446
- } else if (harness === "codex") {
11993
+ } else {
11447
11994
  login = "codex login";
11448
11995
  const result = await probe(io, command, ["login", "status"]);
11449
11996
  if (result?.code === 0)
@@ -11451,38 +11998,121 @@ async function signInCheck(io, harness) {
11451
11998
  else if (result?.code === 1 && /(?:^|\n)Not logged in\s*(?:\n|$)/i.test(`${result.stdout}
11452
11999
  ${result.stderr}`))
11453
12000
  state = "missing";
11454
- } else if (harness === "opencode") {
11455
- login = "opencode auth login";
11456
- const result = await probe(io, command, ["auth", "list"]);
11457
- if (result?.code === 0) {
11458
- const text = stripVTControlCharacters(`${result.stdout}
11459
- ${result.stderr}`);
11460
- const count = text.match(/\b(\d+) credentials\b/);
11461
- const environment = text.match(/\b(\d+) environment variables?\b/);
11462
- if (count)
11463
- state = Number(count[1]) > 0 || Number(environment?.[1] ?? 0) > 0 ? "ready" : "missing";
11464
- }
11465
- } else {
11466
- login = "dsh web";
11467
12001
  }
11468
12002
  return {
11469
12003
  id: `local-${command}-sign-in`,
11470
12004
  level: state === "ready" ? "ok" : state === "missing" ? "error" : "warning",
11471
- message: state === "ready" ? `${command} reports credentials are present${harness === "opencode" ? "; the owner must check the selected provider" : ""}` : state === "missing" ? `${command} is not signed in` : `${command}: could not check sign-in`,
11472
- fix: state === "ready" ? null : `the owner runs \`${login}\`${harness === "deepseek" ? " and configures the provider in Settings → Models" : ""}; Armada never runs sign-in`
12005
+ message: state === "ready" ? `${command} reports credentials are present` : state === "missing" ? `${command} is not signed in` : `${command}: could not check sign-in`,
12006
+ fix: state === "ready" ? null : `the owner runs \`${login}\`; Armada never runs sign-in`
12007
+ };
12008
+ }
12009
+ async function openCodeModels(io) {
12010
+ const result = await probe(io, "opencode", ["models"]);
12011
+ if (result?.code !== 0)
12012
+ return null;
12013
+ return [
12014
+ ...new Set(stripVTControlCharacters(result.stdout).split(`
12015
+ `).map((line) => line.trim()).filter((line) => /^[^\s/#]+\/[^\s#]+$/.test(line)))
12016
+ ];
12017
+ }
12018
+ function modelCheck(profile, available) {
12019
+ const model = profile.model;
12020
+ const matching = available?.filter((id) => profile.harness !== "deepseek" || isDeepseekModel(id)) ?? [];
12021
+ const ready = !!model && matching.includes(model);
12022
+ const label = profile.harness === "deepseek" ? "deepseek (OpenCode + DeepSeek model)" : "opencode";
12023
+ return {
12024
+ id: `local-opencode-${profile.harness}:${profile.name || model}`,
12025
+ level: ready ? "ok" : "error",
12026
+ message: `${label}${profile.name ? ` profile ${profile.name}` : ""}: ${ready ? `OpenCode lists ${model}` : available === null ? "could not check opencode models" : `${model || "the profile's model"} is not listed by OpenCode`}
12027
+ ${ready ? "" : `Available models: ${matching.length ? matching.map((id, i) => `${i + 1}. ${id} — model = ${JSON.stringify(id)}`).join("; ") : "none"}`}`.trimEnd(),
12028
+ fix: ready ? null : `the owner runs \`opencode\`, then \`/connect\`, or picks a model listed by \`opencode models\`; add \`model = "<exact model id>"\`${profile.name ? ` under [herdr.profiles.${profile.name}]` : ""}; Armada never handles the key`
12029
+ };
12030
+ }
12031
+ async function offerLocalModels(io, detected, configPath, options = {}) {
12032
+ if (detected.availableModels === null)
12033
+ return detected;
12034
+ let changed = false;
12035
+ for (const profile of detected.profiles) {
12036
+ if (modelCheck(profile, detected.availableModels).level === "ok")
12037
+ continue;
12038
+ const models = detected.availableModels.filter((id) => profile.harness !== "deepseek" || isDeepseekModel(id));
12039
+ if (!models.length || options.readOnly || !io.interactive || io.env.CI || !io.prompt || !io.writeFile || !configPath || !profile.name)
12040
+ continue;
12041
+ io.stderr(`Choose a model for [herdr.profiles.${profile.name}]:
12042
+ ${models.map((id, i) => ` ${i + 1}. ${id}`).join(`
12043
+ `)}
12044
+ `);
12045
+ const before = await io.readFile(configPath);
12046
+ const answer = await io.prompt("Model number (Enter to leave unchanged): ", { hidden: false });
12047
+ if (answer === null)
12048
+ break;
12049
+ if (!answer.trim())
12050
+ continue;
12051
+ const selected = /^\d+$/.test(answer.trim()) ? models[Number(answer.trim()) - 1] : undefined;
12052
+ if (!selected) {
12053
+ io.stderr(`No model was selected; configuration unchanged.
12054
+ `);
12055
+ continue;
12056
+ }
12057
+ try {
12058
+ if (before === null)
12059
+ throw new Error("missing config");
12060
+ const after = setHerdrModel(before, profile.name, selected);
12061
+ if (await io.readFile(configPath) !== before)
12062
+ throw new Error("config changed");
12063
+ await io.writeFile(configPath, after);
12064
+ profile.model = selected;
12065
+ changed = true;
12066
+ io.stderr(`Wrote model = ${JSON.stringify(selected)} under [herdr.profiles.${profile.name}] in ${configPath}.
12067
+ `);
12068
+ } catch {
12069
+ io.stderr(`Could not safely save the model in ${configPath}; add model = ${JSON.stringify(selected)} under [herdr.profiles.${profile.name}] yourself.
12070
+ `);
12071
+ }
12072
+ }
12073
+ return changed ? detectLocalTools(io, detected.harnesses, detected.profiles) : detected;
12074
+ }
12075
+ async function dshInformation(io) {
12076
+ const tool = await detectTool(io, "dsh");
12077
+ const present = tool.state === "ready";
12078
+ return {
12079
+ id: "local-dsh",
12080
+ level: "ok",
12081
+ message: `${present ? `dsh ${tool.version} is on PATH` : tool.state === "missing" ? "dsh is not installed" : "dsh installation could not be checked"}; information only: deepseek (OpenCode + DeepSeek model) runs OpenCode. Inspected dsh 0.1.5-rc.2 is one-shot, with no follow-up input or --resume`,
12082
+ fix: null
11473
12083
  };
11474
12084
  }
11475
- async function detectLocalTools(io, harnesses) {
12085
+ async function detectLocalTools(io, harnesses, configured = []) {
12086
+ const profiles = configured.map((profile) => typeof profile === "string" ? { name: "", harness: "deepseek", model: profile } : { ...profile });
12087
+ for (const harness of harnesses) {
12088
+ if ((harness === "opencode" || harness === "deepseek") && !profiles.some((profile) => profile.harness === harness))
12089
+ profiles.push({ name: "", harness, model: "" });
12090
+ }
12091
+ let availableModels = null;
11476
12092
  const tools = [];
11477
12093
  const checks = [];
11478
- for (const name of ["herdr", ...new Set(harnesses)]) {
12094
+ const binaries = new Set(harnesses.map((harness) => harness === "deepseek" ? "opencode" : harness));
12095
+ for (const name of ["herdr", ...binaries]) {
11479
12096
  const tool = await detectTool(io, name);
11480
12097
  tools.push(tool);
11481
12098
  checks.push(toolCheck(tool));
11482
- if (name !== "herdr" && tool.state === "ready")
11483
- checks.push(await signInCheck(io, name));
12099
+ if (name !== "herdr" && tool.state === "ready") {
12100
+ if (name !== "opencode")
12101
+ checks.push(await signInCheck(io, name));
12102
+ else {
12103
+ availableModels = await openCodeModels(io);
12104
+ checks.push(...profiles.map((profile) => modelCheck(profile, availableModels)));
12105
+ }
12106
+ }
11484
12107
  }
11485
- return { tools, checks, ready: !checks.some((check) => check.level === "error") };
12108
+ return {
12109
+ tools,
12110
+ profiles,
12111
+ availableModels,
12112
+ harnesses: [...new Set(harnesses)],
12113
+ checks,
12114
+ ready: !checks.some((check) => check.level === "error")
12115
+ };
11486
12116
  }
11487
12117
  async function offerLocalInstalls(io, detected, options = {}) {
11488
12118
  const platform = io.platform ?? process.platform;
@@ -11490,7 +12120,7 @@ async function offerLocalInstalls(io, detected, options = {}) {
11490
12120
  return detected;
11491
12121
  let attempted = false;
11492
12122
  for (const tool of detected.tools) {
11493
- if (tool.state === "ready" || tool.state === "unknown")
12123
+ if (tool.name === "dsh" || tool.state === "ready" || tool.state === "unknown")
11494
12124
  continue;
11495
12125
  const check = toolCheck(tool);
11496
12126
  const answer = await io.prompt(`${check.message}: \`${tool.install}\` — install now? [y/N] `, { hidden: false });
@@ -11500,21 +12130,24 @@ async function offerLocalInstalls(io, detected, options = {}) {
11500
12130
  continue;
11501
12131
  attempted = true;
11502
12132
  const definition = TOOLS[tool.name];
11503
- const npm = tool.name === "codex" || tool.name === "deepseek";
11504
- const code = await io.spawn(npm ? "npm" : "sh", npm ? ["i", "-g", tool.name === "codex" ? "@openai/codex" : "@deepseek-ai/dsh"] : ["-c", definition.install], { cwd: io.cwd, env: installerEnv(io.env) }).catch(() => null);
12133
+ const npm = tool.name === "codex";
12134
+ const code = await io.spawn(npm ? "npm" : "sh", npm ? ["i", "-g", "@openai/codex"] : ["-c", definition.install], {
12135
+ cwd: io.cwd,
12136
+ env: installerEnv(io.env)
12137
+ }).catch(() => null);
11505
12138
  if (code !== 0)
11506
12139
  io.stderr(`${tool.command} installation failed${code === null ? "" : ` (exit ${code})`}. Run \`${definition.install}\` yourself.
11507
12140
  `);
11508
12141
  }
11509
12142
  if (!attempted)
11510
12143
  return detected;
11511
- const result = await detectLocalTools(io, detected.tools.filter((tool) => tool.name !== "herdr").map((tool) => tool.name));
12144
+ const result = await detectLocalTools(io, detected.harnesses, detected.profiles);
11512
12145
  if (result.tools.some((tool) => tool.state !== "ready"))
11513
12146
  io.stderr(`Some local tools still cannot run. Check PATH, open a new terminal if needed, and retry.
11514
12147
  `);
11515
12148
  return result;
11516
12149
  }
11517
- async function ensureLocalTools(io, harness) {
12150
+ async function ensureLocalTools(io, harness, model) {
11518
12151
  const print = (detected) => {
11519
12152
  for (const check of detected.checks) {
11520
12153
  if (check.level === "ok")
@@ -11523,13 +12156,26 @@ async function ensureLocalTools(io, harness) {
11523
12156
  `);
11524
12157
  }
11525
12158
  };
11526
- const detected = await detectLocalTools(io, [harness]);
12159
+ const detected = await detectLocalTools(io, [harness], harness === "deepseek" || harness === "opencode" ? [{ name: "", harness, model: model ?? "" }] : []);
11527
12160
  print(detected);
11528
12161
  const result = await offerLocalInstalls(io, detected);
11529
12162
  if (result !== detected)
11530
12163
  print(result);
11531
12164
  return result.ready;
11532
12165
  }
12166
+ async function ensureLocalProfile(io, configPath, name, profile) {
12167
+ if (profile.harness !== "opencode" && profile.harness !== "deepseek")
12168
+ return await ensureLocalTools(io, profile.harness, profile.model) ? profile.model : null;
12169
+ const detected = await detectLocalTools(io, [profile.harness], [{ name, harness: profile.harness, model: profile.model }]);
12170
+ const installed = await offerLocalInstalls(io, detected);
12171
+ const chosen = await offerLocalModels(io, installed, configPath);
12172
+ for (const check of chosen.checks) {
12173
+ if (check.level !== "ok")
12174
+ io.stderr(`${check.message}${check.fix ? `: ${check.fix}` : ""}
12175
+ `);
12176
+ }
12177
+ return chosen.ready ? chosen.profiles[0]?.model ?? null : null;
12178
+ }
11533
12179
 
11534
12180
  // src/repo.ts
11535
12181
  import { lstat, mkdir as mkdir2, readdir, readFile as readFile2, readlink, rm as rm2, symlink, writeFile as writeFile2 } from "node:fs/promises";
@@ -11858,7 +12504,9 @@ async function localRuntimeChecks(io, config, options = { readOnly: true }) {
11858
12504
  const harnesses = config ? localHarnesses(config) : [];
11859
12505
  if (!harnesses.length)
11860
12506
  return [];
11861
- return (await offerLocalInstalls(io, await detectLocalTools(io, harnesses), options)).checks;
12507
+ const result = await offerLocalInstalls(io, await detectLocalTools(io, harnesses, config ? localModelProfiles(config) : []), options);
12508
+ const selected = await offerLocalModels(io, result, options.configPath ?? join4(io.cwd, CONFIG_FILE), options);
12509
+ return [...selected.checks, ...harnesses.includes("deepseek") ? [await dshInformation(io)] : []];
11862
12510
  }
11863
12511
  async function buildDoctor(io, armadaVersion, options = { readOnly: true }) {
11864
12512
  const root = (io.exec ? await gitRoot(io.exec, io.cwd) : null) ?? io.cwd;
@@ -11891,7 +12539,7 @@ async function buildDoctor(io, armadaVersion, options = { readOnly: true }) {
11891
12539
  ...keyFileChecks(machine, credentials),
11892
12540
  ...await labelChecks(io, config, credentials),
11893
12541
  ...await conductorChecks(io, config),
11894
- ...await localRuntimeChecks(io, config, options),
12542
+ ...await localRuntimeChecks(io, config, { ...options, configPath: join4(root, CONFIG_FILE) }),
11895
12543
  ...config ? await reviewRuntimeChecks(io, root) : [],
11896
12544
  ...await secretChecks(api, config, credentials)
11897
12545
  ];
@@ -11997,7 +12645,12 @@ async function heartbeat(io, config, credentials, args) {
11997
12645
  now: io.now ?? (() => new Date),
11998
12646
  sleep: io.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
11999
12647
  parentAlive: alive,
12000
- ping: (input) => fleet.heartbeat(input),
12648
+ ping: async (input) => {
12649
+ const result = await fleet.heartbeat(input);
12650
+ if (result.active)
12651
+ await reportHerdr(io, result.phase, result.agent ?? "armada", true);
12652
+ return result;
12653
+ },
12001
12654
  ready: async (session) => {
12002
12655
  const name = `${config.project.slug}-heartbeat-${ticket.toLowerCase()}-${createHash3("sha256").update(`${handle}/${session.claimedAt}`).digest("hex").slice(0, 12)}`;
12003
12656
  const acquired = await takeWatchLock(paths, name, pid, io.processAlive ?? processAlive);
@@ -12025,7 +12678,7 @@ async function heartbeat(io, config, credentials, args) {
12025
12678
  // src/init.ts
12026
12679
  import { mkdtemp, realpath, rm as rm3 } from "node:fs/promises";
12027
12680
  import { tmpdir } from "node:os";
12028
- import { join as join4 } from "node:path";
12681
+ import { join as join5 } from "node:path";
12029
12682
  var STOP_HOOK_QUESTION = "Add the Claude Code stop hook to this repository's .claude/settings.json? A coordinator then cannot end its turn while workers are in flight and no armada watch runs; your user settings are not touched. [Y/n] ";
12030
12683
  async function wantsStopHook(io, opts) {
12031
12684
  if (opts.stopHook !== null)
@@ -12058,7 +12711,7 @@ async function resolveConfig(exec, root, checkout, opts) {
12058
12711
  return { config: parse(onDefault, `${CONFIG_FILE} on the default branch`), text: null, source: "default branch" };
12059
12712
  const local = await fsRepoView(root).readFile(CONFIG_FILE);
12060
12713
  if (local !== null && !opts.programRoot)
12061
- return { config: parse(local, join4(root, CONFIG_FILE)), text: local, source: "working tree" };
12714
+ return { config: parse(local, join5(root, CONFIG_FILE)), text: local, source: "working tree" };
12062
12715
  const branch = initBranch(opts.armadaVersion);
12063
12716
  if (!opts.programRoot && await sh(exec, root, "git", ["ls-remote", "origin", `refs/heads/${branch}`])) {
12064
12717
  await sh(exec, root, "git", ["fetch", "--quiet", "origin", branch]);
@@ -12129,7 +12782,7 @@ async function init(io, opts) {
12129
12782
  const base = await defaultBranch(exec, root);
12130
12783
  await sh(exec, root, "git", ["fetch", "--quiet", "origin", base]);
12131
12784
  const baseSha = await sh(exec, root, "git", ["rev-parse", "FETCH_HEAD"]);
12132
- const checkout = await realpath(await mkdtemp(join4(tmpdir(), "armada-init-")));
12785
+ const checkout = await realpath(await mkdtemp(join5(tmpdir(), "armada-init-")));
12133
12786
  try {
12134
12787
  await sh(exec, root, "git", ["worktree", "add", "--quiet", "--detach", checkout, baseSha]);
12135
12788
  const { config, text, source } = await resolveConfig(exec, root, checkout, opts);
@@ -12232,167 +12885,7 @@ async function init(io, opts) {
12232
12885
  }
12233
12886
 
12234
12887
  // src/launch.ts
12235
- import { dirname as dirname5, join as join5 } from "node:path";
12236
-
12237
- // src/herdr.ts
12238
- var harnessArgs = (p) => [
12239
- "--model",
12240
- p.harness === "opencode" ? `${p.model.split("#")[0]}#${p.effort}` : p.model,
12241
- ...p.harness === "codex" ? ["-c", `model_reasoning_effort=${JSON.stringify(p.effort)}`] : p.harness === "claude" ? ["--effort", p.effort] : [],
12242
- ...p.extraArgs
12243
- ];
12244
- var object = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : null;
12245
- var id = (v) => typeof v === "string" && /^[a-zA-Z0-9:_-]{1,128}$/.test(v);
12246
- var runtimeEnvironment = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => /^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TMP|TEMP|LANG|TERM|LC_[A-Z_]+|XDG_(CONFIG_HOME|DATA_HOME|STATE_HOME|CACHE_HOME|RUNTIME_DIR)|HERDR_(SESSION|SOCKET_PATH|CONFIG_PATH))$/.test(name)));
12247
- var credentialNames = (env, extra) => [
12248
- ...new Set([
12249
- "LINEAR_API_KEY",
12250
- "GITHUB_TOKEN",
12251
- "GH_TOKEN",
12252
- "ARMADA_API_KEY",
12253
- "ARMADA_SESSION_TOKEN",
12254
- "ARMADA_SIGNED_IN_TO",
12255
- "ARMADA_API_URL",
12256
- "OPENAI_API_KEY",
12257
- "ANTHROPIC_API_KEY",
12258
- ...Object.keys(env).filter((name) => /^(ARMADA_|CONDUCTOR_)|(?:KEY|TOKEN|SECRET|PASSWORD)$/.test(name)),
12259
- ...extra
12260
- ])
12261
- ].filter((name) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name)).sort();
12262
-
12263
- class Herdr {
12264
- io;
12265
- constructor(io) {
12266
- this.io = io;
12267
- }
12268
- async call(args, timeoutMs = 40000) {
12269
- const operation = args.slice(0, 2).join(" ");
12270
- let reply;
12271
- let code;
12272
- try {
12273
- if (!this.io.exec)
12274
- throw new Error("no exec");
12275
- const out = await this.io.exec("herdr", args, { cwd: this.io.cwd, timeoutMs });
12276
- code = out.code;
12277
- reply = object(JSON.parse(out.stdout || out.stderr));
12278
- } catch {
12279
- throw new UsageError(`herdr ${operation} failed; inspect the runtime with herdr agent list`);
12280
- }
12281
- const error = object(reply?.error);
12282
- if (code !== 0 || error) {
12283
- const reason = typeof error?.code === "string" && /^[a-z_]{1,64}$/.test(error.code) ? ` (${error.code})` : "";
12284
- throw new UsageError(`herdr ${operation} failed${reason}; inspect the runtime with herdr agent list`);
12285
- }
12286
- if (!reply)
12287
- throw new UsageError(`herdr ${operation} returned invalid JSON`);
12288
- return reply;
12289
- }
12290
- async ensureServer() {
12291
- const status = async (timeoutMs) => {
12292
- const server = object((await this.call(["status", "--json"], timeoutMs)).server);
12293
- if (!server || typeof server.running !== "boolean")
12294
- throw new UsageError("invalid herdr server status response");
12295
- if (server.running && (server.compatible === false || server.endpoint_compatible === false))
12296
- throw new UsageError("the running herdr server is incompatible; update or restart it before launching");
12297
- return server.running;
12298
- };
12299
- if (await status(5000))
12300
- return;
12301
- if (!this.io.detach || !await this.io.detach("herdr", ["server"], { cwd: this.io.cwd, env: runtimeEnvironment(this.io.env) }))
12302
- throw new UsageError("could not start herdr server; start it headless with herdr server");
12303
- const now = this.io.now ?? (() => new Date);
12304
- const deadline = now().getTime() + 5000;
12305
- for (let attempt = 0;attempt < 20; attempt++) {
12306
- const remaining = deadline - now().getTime();
12307
- if (remaining <= 0)
12308
- break;
12309
- if (await status(Math.min(1000, remaining)))
12310
- return;
12311
- const delay = Math.min(250, deadline - now().getTime());
12312
- if (delay > 0)
12313
- await (this.io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))))(delay);
12314
- }
12315
- throw new UsageError("herdr server did not become ready; inspect herdr status");
12316
- }
12317
- async create(input) {
12318
- const agent = input.ticket.toLowerCase();
12319
- if (!/^[a-z][a-z0-9_-]{0,31}$/.test(agent))
12320
- throw new UsageError("ticket cannot be used as a herdr agent name");
12321
- const r = object((await this.call([
12322
- "worktree",
12323
- "create",
12324
- "--cwd",
12325
- input.repo,
12326
- "--branch",
12327
- input.branch,
12328
- "--base",
12329
- input.base,
12330
- "--no-focus"
12331
- ])).result);
12332
- const workspace = object(r?.workspace)?.workspace_id;
12333
- const rootPane = object(r?.root_pane)?.pane_id;
12334
- const path = object(r?.worktree)?.path;
12335
- if (!id(workspace) || !id(rootPane) || typeof path !== "string" || !path.startsWith("/") || object(r?.root_pane)?.workspace_id !== workspace)
12336
- throw new UsageError("invalid herdr worktree response; inspect herdr worktree list before retrying");
12337
- const tab = object((await this.call([
12338
- "tab",
12339
- "create",
12340
- "--workspace",
12341
- workspace,
12342
- "--cwd",
12343
- path,
12344
- "--no-focus",
12345
- ...credentialNames(this.io.env, input.secrets ?? []).flatMap((name) => ["--env", `${name}=`]),
12346
- "--env",
12347
- `ARMADA_TICKET=${input.ticket}`
12348
- ])).result);
12349
- const pane = object(tab?.root_pane)?.pane_id;
12350
- if (!id(pane) || pane === rootPane || object(tab?.root_pane)?.workspace_id !== workspace)
12351
- throw new UsageError("invalid herdr worker pane response; inspect herdr pane list before retrying");
12352
- await this.call(["pane", "close", rootPane]);
12353
- return { workspace, pane, agent, path };
12354
- }
12355
- async start(handle, profile) {
12356
- const r = await this.call([
12357
- "agent",
12358
- "start",
12359
- handle.agent,
12360
- "--kind",
12361
- profile.harness,
12362
- "--pane",
12363
- handle.pane,
12364
- "--timeout",
12365
- "30000",
12366
- "--",
12367
- ...harnessArgs(profile)
12368
- ]);
12369
- this.checkAgent(r, handle);
12370
- }
12371
- async prompt(handle, prompt) {
12372
- const r = await this.call([
12373
- "agent",
12374
- "prompt",
12375
- handle.agent,
12376
- prompt,
12377
- "--wait",
12378
- "--until",
12379
- "working",
12380
- "--timeout",
12381
- "30000"
12382
- ]);
12383
- const agent = this.checkAgent(r, handle);
12384
- if (agent.agent_status !== "working")
12385
- throw new UsageError("herdr did not confirm the worker is working");
12386
- }
12387
- checkAgent(reply, handle) {
12388
- const agent = object(object(reply.result)?.agent);
12389
- if (!agent || agent.name !== handle.agent || agent.pane_id !== handle.pane || agent.workspace_id !== handle.workspace)
12390
- throw new UsageError("invalid herdr agent response; inspect herdr agent list before retrying");
12391
- return agent;
12392
- }
12393
- }
12394
-
12395
- // src/launch.ts
12888
+ import { dirname as dirname5, join as join6 } from "node:path";
12396
12889
  async function launch(io, config, credentials, args, version, configPath) {
12397
12890
  if (args.rest[0] !== "revoke")
12398
12891
  return launchLocal(io, config, credentials, args, version, configPath);
@@ -12420,13 +12913,13 @@ async function launchLocal(io, config, credentials, args, version, configPath) {
12420
12913
  const [input, ...extra] = args.rest;
12421
12914
  const o = args.options;
12422
12915
  if (!input || extra.length || !/^[A-Za-z][A-Za-z0-9]{0,15}-\d{1,9}$/.test(input) || o.runtime !== "herdr")
12423
- throw new UsageError("launch needs a ticket and runtime: armada launch <ticket> --runtime herdr [--harness claude|codex|opencode]");
12916
+ throw new UsageError("launch needs a ticket and runtime: armada launch <ticket> --runtime herdr [--harness claude|codex|opencode|deepseek]");
12424
12917
  const requested = o.profile?.trim() || null;
12425
12918
  const reason = o.reason?.trim() || null;
12426
12919
  if (reason && !requested)
12427
12920
  throw new UsageError("--reason goes with --profile");
12428
12921
  if (o.harness && !HERDR_HARNESSES.includes(o.harness))
12429
- throw new UsageError("--harness must be claude, codex or opencode");
12922
+ throw new UsageError("--harness must be claude, codex, opencode or deepseek (OpenCode + DeepSeek model)");
12430
12923
  try {
12431
12924
  checkRequestedProfile(config, requested, "herdr");
12432
12925
  } catch (error) {
@@ -12489,8 +12982,18 @@ async function launchLocal(io, config, credentials, args, version, configPath) {
12489
12982
  interactive: args.json ? false : io.interactive,
12490
12983
  exec: (command, argv, options) => execute(command, argv, { ...options, timeoutMs: options.timeoutMs ?? 1e4 })
12491
12984
  };
12492
- if (!await ensureLocalTools(preflight, choice.profile.harness))
12985
+ const model = await ensureLocalProfile(preflight, configPath, choice.name, choice.profile);
12986
+ if (model === null)
12493
12987
  return 1;
12988
+ choice.profile.model = model;
12989
+ const openCode = herdrHarnessKind(choice.profile.harness) === "opencode";
12990
+ const configSnapshot = openCode ? await io.readFile(configPath) : null;
12991
+ if (openCode) {
12992
+ if (!io.writeFile || configSnapshot === null)
12993
+ throw new UsageError("local OpenCode launch needs the configuration copied into its worker worktree");
12994
+ if (JSON.stringify(parseConfig(configSnapshot, configPath)) !== JSON.stringify(config))
12995
+ throw new UsageError("configuration changed during preflight; retry launch with the saved model");
12996
+ }
12494
12997
  const root = await io.exec("git", ["rev-parse", "--show-toplevel"], { cwd: io.cwd, timeoutMs: 1e4 });
12495
12998
  if (root.code !== 0 || !root.stdout.trim().startsWith("/"))
12496
12999
  throw new UsageError("local launch must run in a git repository");
@@ -12499,7 +13002,7 @@ async function launchLocal(io, config, credentials, args, version, configPath) {
12499
13002
  const base = remote.code === 0 ? remote.stdout.match(/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m)?.[1] : null;
12500
13003
  if (!base)
12501
13004
  throw new UsageError("could not read the default branch of origin");
12502
- const conventions = config.brief.extra ? { path: config.brief.extra, text: await io.readFile(join5(dirname5(configPath), config.brief.extra)) } : null;
13005
+ const conventions = config.brief.extra ? { path: config.brief.extra, text: await io.readFile(join6(dirname5(configPath), config.brief.extra)) } : null;
12503
13006
  const npm = await checkPublished(version, io.fetch ?? fetch);
12504
13007
  if (npm.state === "missing")
12505
13008
  throw new UsageError(`armada ${version} is not on npm yet; publish this version before launching local workers`);
@@ -12510,6 +13013,8 @@ async function launchLocal(io, config, credentials, args, version, configPath) {
12510
13013
  try {
12511
13014
  await runtime.ensureServer();
12512
13015
  handle = await runtime.create({ repo, branch, base, ticket: ticketId, secrets: config.secrets.names });
13016
+ if (configSnapshot !== null && io.writeFile)
13017
+ await io.writeFile(join6(handle.path, CONFIG_FILE), configSnapshot);
12513
13018
  const b = buildBrief({
12514
13019
  config,
12515
13020
  ticket,
@@ -12545,6 +13050,8 @@ async function launchLocal(io, config, credentials, args, version, configPath) {
12545
13050
  runtime: "herdr",
12546
13051
  profile: choice.name,
12547
13052
  harness: choice.profile.harness,
13053
+ actualHarness: herdrHarnessKind(choice.profile.harness),
13054
+ harnessDescription: herdrHarnessLabel(choice.profile.harness),
12548
13055
  branch,
12549
13056
  handle: herdrClaimHandle(handle),
12550
13057
  path: handle.path,
@@ -12552,7 +13059,7 @@ async function launchLocal(io, config, credentials, args, version, configPath) {
12552
13059
  watch
12553
13060
  };
12554
13061
  io.stdout(args.json ? `${JSON.stringify(result, null, 2)}
12555
- ` : `Launched ${ticketId} with ${result.harness} on profile ${choice.name}.
13062
+ ` : `Launched ${ticketId} with ${result.harnessDescription} on profile ${choice.name}.
12556
13063
  Worktree: ${handle.path}
12557
13064
  Handle: ${result.handle}
12558
13065
  The worker signs in and claims its ticket from the brief.
@@ -12565,7 +13072,7 @@ ${watch.line}
12565
13072
  import { randomUUID } from "node:crypto";
12566
13073
  import { rm as rm4 } from "node:fs/promises";
12567
13074
  import { hostname, tmpdir as tmpdir2 } from "node:os";
12568
- import { dirname as dirname6, join as join6 } from "node:path";
13075
+ import { dirname as dirname6, join as join7 } from "node:path";
12569
13076
  var TRANSIENT = /\bHTTP 5\d\d\b|\b5\d\d (?:Bad Gateway|Service Unavailable|Gateway Time-?out|Internal Server Error)\b|Bad Gateway|Service Unavailable|Gateway Time-?out|ECONNRESET|ETIMEDOUT|connection reset|i\/o timeout|TLS handshake timeout/i;
12570
13077
  var tail = (text, lines = 30) => text.trimEnd().split(`
12571
13078
  `).slice(-lines).join(`
@@ -12643,7 +13150,7 @@ function gitRepo(exec, cwd) {
12643
13150
  },
12644
13151
  async testMerge({ branch, base, head, number, commands }) {
12645
13152
  await must(["fetch", "--quiet", "origin", branch, `refs/pull/${number}/head`]);
12646
- const dir = join6(tmpdir2(), `armada-merge-${number}-${randomUUID().slice(0, 8)}`);
13153
+ const dir = join7(tmpdir2(), `armada-merge-${number}-${randomUUID().slice(0, 8)}`);
12647
13154
  const remove = async () => {
12648
13155
  await git(["worktree", "remove", "--force", dir]);
12649
13156
  await git(["worktree", "prune"]);
@@ -12787,7 +13294,7 @@ async function merge(io, config, credentials, a, configPath) {
12787
13294
  `),
12788
13295
  installedSkill: async (name) => {
12789
13296
  for (const dir of [AGENTS_SKILLS_DIR, CLAUDE_SKILLS_DIR])
12790
- if (await io.readFile(join6(repoDir, dir, name, "SKILL.md")) !== null)
13297
+ if (await io.readFile(join7(repoDir, dir, name, "SKILL.md")) !== null)
12791
13298
  return true;
12792
13299
  return false;
12793
13300
  }
@@ -12881,11 +13388,11 @@ function renderStatus(r) {
12881
13388
  if (!r.inFlight.length)
12882
13389
  out.push(" nobody is working");
12883
13390
  for (const t of r.inFlight) {
12884
- const who = [t.runtime, t.agent].filter(Boolean).join(" · ") || "unassigned";
13391
+ const who = [t.runtime, t.runtimeState && `live ${t.runtimeState}`, t.agent].filter(Boolean).join(" · ") || "unassigned";
12885
13392
  out.push(` ${pad(t.id, idWidth)} ${pad(phaseLabel(t), phaseWidth)} ${who} · ${t.lastReport ? `reported ${relative2(t.lastReport, now)}` : `updated ${relative2(t.lastUpdate, now)}`}`);
12886
13393
  out.push(`${indent}${truncate(t.title, 90)}${t.spec ? ` [${t.spec}]` : ""}`);
12887
13394
  if (t.profile)
12888
- out.push(`${indent}Profile: ${t.profile}${t.profileReason ? ` — ${t.profileReason}` : ""}`);
13395
+ out.push(`${indent}Profile: ${t.profile}${t.harness ? ` · ${t.harness}` : ""}${t.profileReason ? ` — ${t.profileReason}` : ""}`);
12889
13396
  if (t.statusLine?.summary)
12890
13397
  out.push(`${indent}“${truncate(t.statusLine.summary, 100)}”`);
12891
13398
  if (t.statusLine?.plan)
@@ -13417,12 +13924,15 @@ var COMMAND_HELP = {
13417
13924
  this machine. Needs a sign-in to Armada
13418
13925
  watch --stop Stop only this project's verified watch and release its lock. Local,
13419
13926
  no sign-in needed. Never stop a watch just to read inbox or status
13927
+ `,
13928
+ stop: ` stop <ticket>
13929
+ Stop a herdr worker and archive its worktree only when clean and fully pushed
13420
13930
  `,
13421
13931
  answer: ` answer <item|ticket> "<answer>"
13422
- Coordinator: record an answer already delivered in the worker's
13423
- session (runtime guide): resolves the question or plan and posts it on
13424
- the ticket. A ticket id answers its open questions and plans. A hand-back id can
13425
- clear a merged/closed PR or a Done/Canceled ticket. Never calls a runtime
13932
+ Coordinator: deliver to a herdr worker and record the answer. For other
13933
+ runtimes, deliver with the runtime guide first. Resolves the question or
13934
+ plan and posts it on the ticket. A ticket id also answers a live herdr block.
13935
+ A hand-back id can clear a merged/closed PR or a Done/Canceled ticket
13426
13936
  answer --note <ticket|plan item> "<message>"
13427
13937
  Coordinator: record a delivered note; an open plan is resolved
13428
13938
  `,
@@ -13446,7 +13956,8 @@ var COMMAND_HELP = {
13446
13956
  A pull request the owner was asked about merges only once they approved
13447
13957
  that exact head (or it with only the base merged in).
13448
13958
  `,
13449
- launch: ` launch <ticket> --runtime herdr [--harness claude|codex|opencode]
13959
+ launch: ` launch <ticket> --runtime herdr [--harness claude|codex|opencode|deepseek]
13960
+ deepseek (OpenCode + DeepSeek model) runs a persistent session
13450
13961
  [--profile <name> [--reason <why>]] [--validation <n|none>]
13451
13962
  Create the ticket's worktree and start a persistent local worker
13452
13963
  with its launch-token brief. Profiles follow [[herdr.routing]]
@@ -13525,6 +14036,7 @@ var CONFIG_OPTION = new Set([
13525
14036
  "inbox",
13526
14037
  "watch",
13527
14038
  "answer",
14039
+ "stop",
13528
14040
  "merge",
13529
14041
  "brief",
13530
14042
  "launch"
@@ -13719,7 +14231,7 @@ async function findConfig(io, explicit, command = "status") {
13719
14231
  return { path, text };
13720
14232
  }
13721
14233
  for (let dir = resolve3(io.cwd);; dir = dirname8(dir)) {
13722
- const path = join7(dir, CONFIG_FILE);
14234
+ const path = join8(dir, CONFIG_FILE);
13723
14235
  const text = await io.readFile(path);
13724
14236
  if (text !== null)
13725
14237
  return { path, text };
@@ -13852,7 +14364,7 @@ async function dispatch(argv, io) {
13852
14364
  });
13853
14365
  return await heartbeat(io, config, credentials, args);
13854
14366
  }
13855
- const worker = { claim, report, release, ask, inbox, answer, validate, "ask-owner": askOwner, done }[args.command];
14367
+ const worker = { claim, report, release, ask, inbox, answer, stop, validate, "ask-owner": askOwner, done }[args.command];
13856
14368
  if (worker) {
13857
14369
  const { path, text } = await findConfig(io, args.config, args.command);
13858
14370
  const config = parseConfig(text, path);
@@ -14199,6 +14711,7 @@ var code = await run(process.argv.slice(2), {
14199
14711
  return null;
14200
14712
  throw err;
14201
14713
  }),
14714
+ writeFile: (path, text) => writeFile3(path, text, "utf8"),
14202
14715
  stdout: (t) => process.stdout.write(t),
14203
14716
  readBinaryFile: async (path, maxBytes) => {
14204
14717
  const file = await open2(path, "r").catch((err) => {