@floh-solutions/pharos-cli 0.32.0 → 0.33.0

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.
@@ -3,10 +3,10 @@ import { realpath, stat } from "node:fs/promises";
3
3
  import { basename, isAbsolute, join } from "node:path";
4
4
  import { promisify } from "node:util";
5
5
  import { findApp, HOSTS, HOST_IDS, AGENT_IDS, MODES, isAgentId, isHostId, isMode, } from "../delegate/hosts.js";
6
- import { ARGUS_REASONS, ARGUS_TEXT_LIMIT, ARGUS_WAIT_SECONDS, ArgusUnreachableError, askArgus, delegateRequest, delegateStatusRequest, fleetStatusRequest, isFailure, parseFleet, PROBE_REQUEST, rankWorkers, readDelegation, readTimeoutMs, servesDelegate, systemArgusDeps, unreachable, } from "../delegate/argus.js";
6
+ import { ARGUS_NEW_WORKER, ARGUS_REASONS, ARGUS_TEXT_LIMIT, ARGUS_WAIT_SECONDS, ArgusUnreachableError, askArgus, candidatesSupport, delegateCandidatesRequest, delegateRequest, delegateStatusRequest, fleetStatusRequest, isFailure, mapRefusal, parseCandidates, parseFleet, rankWorkers, readDelegation, readTimeoutMs, systemArgusDeps, unreachable, } from "../delegate/argus.js";
7
7
  import { asTypedInput, LAUNCH_SCRIPT, launchCommand, SEND_TO_TAB_SCRIPT } from "../delegate/quote.js";
8
8
  import { findSessions, rankSessions, systemProbes, } from "../delegate/sessions.js";
9
- import { BRIDGE_EXTENSION_ID, bridgeAtLeast, CLAUDE_EXTENSION_ID, extensionsDirectory, installedExtensions, SESSION_BRIDGE_VERSION, } from "../delegate/vsix.js";
9
+ import { BRIDGE_EXTENSION_ID, bridgeAtLeast, bundledBridge, bundledVsixPath, CLAUDE_EXTENSION_ID, extensionsDirectory, installBridge, installedExtensions, SESSION_BRIDGE_VERSION, } from "../delegate/vsix.js";
10
10
  import { CliError, EXIT_FAILED, EXIT_USAGE, emit, emitText, usageError } from "../output.js";
11
11
  import { resolveOnPath } from "./doctor.js";
12
12
  const run = promisify(execFile);
@@ -21,25 +21,47 @@ export const REASONS = [
21
21
  "automation-denied",
22
22
  "folder-missing",
23
23
  "unsupported",
24
- /** `--session <id>` named a session that is no longer a target on this folder. */
25
- "session-gone",
26
24
  /**
27
- * `--session` named a Navarch worker that is not the one the daemon's own
28
- * find would pick, or asked for a new one — neither of which the `delegate`
29
- * op can express: it takes no target worker (argus #1402). The id is real
30
- * and the session is alive, which is why this is not `session-gone`.
25
+ * `--session <id>` named a session that is no longer a target on this folder.
26
+ *
27
+ * On Navarch it is also what the daemon's `worker-not-eligible` becomes: the
28
+ * row you picked is not one this machine will deliver to, whether it exited,
29
+ * took a mission, or was never a candidate. Same fact, same fix — read the
30
+ * list again and pick from it.
31
31
  */
32
- "session-not-targetable",
32
+ "session-gone",
33
+ // **`session-not-targetable` was here and is gone** (#1412). It said the
34
+ // `delegate` op could not express a target worker at all; argus #1402 added
35
+ // `worker`, so no call can produce it any more. A daemon that predates that
36
+ // field is `argusd-outdated`, which is the truth and carries the fix (reload
37
+ // the daemon) — where this one carried none.
38
+ //
33
39
  // …and the Argus socket's own, each naming a different fix. See
34
40
  // `delegate/argus.js` — they are defined there because that is where the
35
41
  // daemon's reasons are mapped onto them.
36
42
  ...ARGUS_REASONS,
37
43
  ];
44
+ /**
45
+ * A second, narrower axis on a refusal: WHICH shape of a reason this is.
46
+ *
47
+ * One value so far, and it exists because one `bridge-not-installed` now has a
48
+ * different fix from the others. The app renders that reason with an Install
49
+ * button; `stale-window` means the install has already happened and what is
50
+ * needed is a window reload, so the app can swap the button for a reload hint
51
+ * (#1409, #1413) without reading the prose.
52
+ *
53
+ * **Optional, and absent on every refusal that does not need it.** A decoder
54
+ * that has never seen it keeps working — which is what lets the app adopt it
55
+ * whenever it gets to it rather than in lockstep with this release.
56
+ */
57
+ export const CAUSES = ["stale-window"];
38
58
  export const SYSTEM_DEPS = {
39
59
  findApp,
40
60
  resolveOnPath,
41
61
  probes: systemProbes,
42
62
  installedExtensions,
63
+ bundledBridge,
64
+ installBridge: (host, env) => installBridge({ env, hosts: [host] }),
43
65
  osascript: async (source, args) => {
44
66
  // `--` ends option parsing, so a prompt that begins with a dash is an
45
67
  // argument and not a flag. Every variable value travels as argv; nothing
@@ -101,6 +123,19 @@ function tabPick(pick) {
101
123
  return pick;
102
124
  throw new CliError(`--session ${pick.id} is a Navarch worker id, and this route delivers by process id.`, "internal", EXIT_FAILED);
103
125
  }
126
+ /**
127
+ * The mirror of {@link tabPick}: {@link sessionPick} parses a navarch `--session`
128
+ * as a uuid or `new` and nothing else, so a pid cannot reach that route.
129
+ *
130
+ * A guard rather than a cast for the same reason as its twin — the day the
131
+ * parse changes, this says so here instead of sending a process id to argusd
132
+ * as a worker uuid and getting `bad-worker` back about a value nobody typed.
133
+ */
134
+ function workerPick(pick) {
135
+ if (pick === undefined || pick.kind !== "pid")
136
+ return pick;
137
+ throw new CliError(`--session ${pick.pid} is a process id, and Navarch delivers by worker uuid.`, "internal", EXIT_FAILED);
138
+ }
104
139
  /** The reserved id. `--list` never prints it, so it can never shadow a real session. */
105
140
  export const NEW_SESSION = "new";
106
141
  /**
@@ -147,6 +182,39 @@ export function sessionPick(value, host) {
147
182
  }
148
183
  return { kind: "pid", pid: Number(given) };
149
184
  }
185
+ /**
186
+ * `--gh-account <login>` → the value to send, or a usage error.
187
+ *
188
+ * **A usage error and never a refusal**, the same split `--session` makes: a
189
+ * refusal is a fact about this machine that the app renders with a fix beside
190
+ * it, and "you passed an empty string" is not a fact about the machine. The
191
+ * one refusal this flag can produce is `gh-account-unknown`, and it comes off
192
+ * the socket — the daemon holds the accounts, so only the daemon can say an
193
+ * account is not one of them.
194
+ *
195
+ * **A login-shaped token: no whitespace.** `gh` logins have none, and neither
196
+ * does any spelling this CLI derives — it resolves a project folder's origin
197
+ * against `repos.json` and gets a login. Navarch will ALSO match a human's
198
+ * account *label*, and a label may well contain a space; such a label cannot
199
+ * be named through this flag, and the login always can. That is the trade, and
200
+ * it is the right way round: a value with a space in it reaching argusd would
201
+ * be one quoting mistake away from arriving as two.
202
+ */
203
+ export function ghAccountOption(value) {
204
+ if (value === undefined)
205
+ return undefined;
206
+ const given = value.trim();
207
+ if (given === "") {
208
+ throw usageError("--gh-account needs a GitHub login, or the name of an account bound in Navarch ▸ Accounts. "
209
+ + "Leave the flag off to let the session run as whoever this machine is logged in as.");
210
+ }
211
+ if (/\s/.test(given) || CONTROL.test(given)) {
212
+ throw usageError(`--gh-account takes one login-shaped token and ${JSON.stringify(value)} is not one: a GitHub `
213
+ + "login has no spaces. (Navarch also matches an account's label, which may have one — pass "
214
+ + "the login instead; it always resolves.)", { ghAccount: value });
215
+ }
216
+ return given;
217
+ }
150
218
  export async function runDelegate(io, env, options, deps = SYSTEM_DEPS) {
151
219
  const host = oneOf(options.host, "--host", HOST_IDS, isHostId);
152
220
  const agent = oneOf(options.agent, "--agent", AGENT_IDS, isAgentId);
@@ -174,6 +242,15 @@ export async function runDelegate(io, env, options, deps = SYSTEM_DEPS) {
174
242
  throw usageError("--status needs the `request` id the delegation answered with.");
175
243
  }
176
244
  const pick = sessionPick(options.session, host);
245
+ // **Accepted everywhere, honoured only by Navarch.** It is validated for
246
+ // shape on every host so a typo is caught where it was typed; what happens
247
+ // to it after that is the route's, and for the three hosts that cannot bind
248
+ // an identity it is a sentence on the outcome rather than a refusal. Only
249
+ // Navarch STARTS a session on the caller's behalf — a Terminal window and a
250
+ // VS Code terminal both inherit whatever `gh` this machine is logged in as,
251
+ // and there is nothing this verb could do about that short of writing to
252
+ // somebody's keyring.
253
+ const ghAccount = ghAccountOption(options.ghAccount);
177
254
  // **`--list` needs no prompt**, and demanding one would make the app build a
178
255
  // message it is only going to throw away to refresh a menu. Nor does
179
256
  // `--status`, which is a read about a delegation whose text was sent already.
@@ -188,17 +265,33 @@ export async function runDelegate(io, env, options, deps = SYSTEM_DEPS) {
188
265
  throw usageError(`--folder must be absolute, got ${JSON.stringify(folder)}.`, { folder });
189
266
  }
190
267
  const base = { host, agent, mode, folder };
191
- const refuse = (reason, detail, delegation) => emitRefusal(io, options.pretty, {
268
+ /**
269
+ * What `--gh-account` did on a host that cannot honour it: nothing, said out
270
+ * loud. Appended in ONE place rather than by each route, because a route
271
+ * that forgot it would be the silent case this sentence exists to prevent —
272
+ * and the app renders `detail` verbatim, so a value that travelled and did
273
+ * nothing has to be in it. `--list` and `--status` are not sends and do not
274
+ * get it; they never reach {@link succeed} with anything to say about a
275
+ * session this call started.
276
+ */
277
+ const accountNote = ghAccount === undefined || host === "navarch"
278
+ ? ""
279
+ : ` The GitHub account “${ghAccount}” was not applied: only Navarch starts a session on your `
280
+ + `behalf and can bind one to it. A ${HOSTS[host].name} session runs as whichever account `
281
+ + "`gh` on this machine is logged in as.";
282
+ const refuse = (reason, detail, extra = {}) => emitRefusal(io, options.pretty, {
192
283
  ok: false,
193
284
  reason,
285
+ ...(extra.cause === undefined ? {} : { cause: extra.cause }),
194
286
  detail,
195
287
  ...base,
196
- ...(delegation === undefined ? {} : { delegation }),
288
+ ...(extra.delegation === undefined ? {} : { delegation: extra.delegation }),
197
289
  });
198
290
  const succeed = (outcome) => emitOutcome(io, options.pretty, {
199
291
  ok: true,
200
292
  ...base,
201
293
  ...outcome,
294
+ detail: outcome.detail + accountNote,
202
295
  ...(options.dryRun ? { dryRun: true } : {}),
203
296
  });
204
297
  // **`--status` asks the daemon, and nothing else.** It deliberately skips
@@ -229,7 +322,7 @@ export async function runDelegate(io, env, options, deps = SYSTEM_DEPS) {
229
322
  // though it were a fact about the machine — and a GUI-launched Pharos has
230
323
  // roughly `/usr/bin:/bin`, so it would refuse on nearly every real call.
231
324
  if (host === "navarch") {
232
- return delegateToNavarch(io, env, agent, folder, text, base, options, pick, deps, refuse, succeed);
325
+ return delegateToNavarch(io, env, agent, folder, text, base, options, workerPick(pick), ghAccount, deps, refuse, succeed);
233
326
  }
234
327
  // **May be null, and that is not always a refusal.** The Terminal route runs
235
328
  // the agent by this path, so it must exist there; the VS Code extension route
@@ -333,23 +426,29 @@ function nameOf(agent) {
333
426
  /**
334
427
  * `--host navarch` — the send, the inventory and the dry run.
335
428
  *
336
- * All three go through one function because all three need the same two facts,
337
- * and the order they are established in is the whole contract:
338
- *
339
- * 1. **Does this argusd serve the verb?** `fleet_status` answers on every
340
- * generation of the daemon measured against one built from the commit
341
- * before `delegate` so a `--list` that skipped this would happily
342
- * enumerate workers that a send is about to refuse to touch. The probe is a
343
- * `delegate_status` read about an id that cannot exist: free, ungated,
344
- * side-effect-free. See {@link PROBE_REQUEST}.
345
- * 2. **Who is on the folder**, which is a PREDICTION and never the find
346
- * itself. The daemon does the find that counts, against a snapshot that may
347
- * have moved since this read.
348
- *
349
- * A plain send needs neither and asks for neither: one round trip, and the
350
- * daemon's own answer says where it landed.
429
+ * All three go through one function because all three rest on the same read,
430
+ * and which of them needs it is the whole contract:
431
+ *
432
+ * 1. **`delegate_candidates`** the find, asked rather than performed
433
+ * (argus #1402). It answers two questions at once, and both matter here:
434
+ * *who is on this folder*, as the daemon's own ranked list rather than as
435
+ * this CLI's prediction of it; and *does this daemon read a target at
436
+ * all*, since the op landed in the same change as `worker` and
437
+ * `gh_account`. A daemon that answers `unknown-op` serves neither, and it
438
+ * would IGNORE both rather than refuse them so `--session` and
439
+ * `--gh-account` are refused `argusd-outdated` there with nothing sent,
440
+ * while `--list` falls back to `fleet_status` and says so in `source`.
441
+ * 2. …and nothing else. **A plain send asks for none of it**: one round trip,
442
+ * the daemon does the find that counts, and its own answer says where the
443
+ * prompt landed.
444
+ *
445
+ * A pick is deliberately **not** re-checked against that list before a real
446
+ * send. The daemon validates `worker` against the very predicate the list came
447
+ * from — one rule, three callers — and its refusal names which of six reasons
448
+ * it was. A second copy of the rule here could only disagree with it, and the
449
+ * disagreeing copy is the one nobody is looking at.
351
450
  */
352
- async function delegateToNavarch(io, env, agent, folder, text, base, options, pick, deps, refuse, succeed) {
451
+ async function delegateToNavarch(io, env, agent, folder, text, base, options, pick, ghAccount, deps, refuse, succeed) {
353
452
  const kind = agent;
354
453
  const argus = deps.argus(env);
355
454
  // The daemon's own compare resolves `~`, `.`/`..` and the three symlinked
@@ -357,39 +456,64 @@ async function delegateToNavarch(io, env, agent, folder, text, base, options, pi
357
456
  // somebody made would miss every worker on it, so it is canonicalised here,
358
457
  // exactly as the Terminal route canonicalises before matching a cwd.
359
458
  const directory = await canonicalFolder(folder);
459
+ /** Does this call carry a field argus #1402 added? Both are ignored by an older daemon. */
460
+ const aims = pick !== undefined || ghAccount !== undefined;
360
461
  try {
361
- // `--session new`, and any pick that is not the worker the daemon would
362
- // choose, are refused BEFORE anything is sent — see {@link notTargetable}.
363
- const listing = options.list || options.dryRun || pick !== undefined
364
- ? await navarchFleet(argus, kind, directory)
462
+ const found = options.list || options.dryRun || aims
463
+ ? await navarchCandidates(argus, kind, directory)
365
464
  : null;
366
- if (listing !== null && isFailure(listing))
367
- return refuseFailure(refuse, listing);
368
- const ranked = listing ?? [];
465
+ if (found !== null && isFailure(found))
466
+ return refuseFailure(refuse, found);
467
+ const ranked = found?.workers ?? [];
468
+ const target = found?.target ?? null;
469
+ // `found!` below, three times and for one reason: `--list`, `--dry-run` and
470
+ // a call that `aims` are exactly the three that set it, so inside each of
471
+ // them the read has happened. A plain send is the only path where it is
472
+ // null, and it returns before any of them.
369
473
  if (options.list)
370
- return emitNavarchList(io, base, agent, ranked, options.pretty);
371
- if (pick !== undefined) {
372
- const gap = notTargetable(pick, ranked, agent);
373
- if (gap !== null)
374
- return refuse("session-not-targetable", gap);
474
+ return emitNavarchList(io, base, agent, found, options.pretty);
475
+ // **The version gate, and it is the reason a pick costs a round trip.**
476
+ // `delegate` ignores a key it does not know, so on a daemon that predates
477
+ // #1402 a `worker` is discarded and the find runs anyway — `sent`, about a
478
+ // pane the person did not choose — and a `gh_account` is discarded too,
479
+ // leaving a fresh worker running as whoever `gh` last logged in as. Both
480
+ // are exactly what these flags exist to prevent, and neither is visible in
481
+ // the reply, so the only place to catch it is here, before the send.
482
+ if (aims && found !== null && found.source === "fleet_status") {
483
+ return refuse("argusd-outdated", targetUnsupported(pick, ghAccount));
375
484
  }
376
485
  const oneLine = navarchText(text);
377
- const target = ranked[0] ?? null;
378
486
  if (options.dryRun) {
487
+ const picked = pick === undefined
488
+ ? headOf(ranked, target)
489
+ : pick.kind === "new"
490
+ ? null
491
+ : (ranked.find((worker) => worker.id === pick.id) ?? null);
492
+ // The one refusal a dry run can predict exactly, and only because the
493
+ // gate above has already run: a named worker means `aims`, so the list
494
+ // in hand is `delegate_candidates`' own — the very set `delegate`
495
+ // validates `worker` against. A uuid missing from it is a uuid the send
496
+ // would refuse `worker-not-eligible`.
497
+ if (pick?.kind === "worker" && picked === null) {
498
+ return refuse("session-gone", wouldBeGone(pick.id, ranked, agent));
499
+ }
379
500
  return succeed({
380
- action: target === null ? "launched" : "sent",
501
+ action: picked === null ? "launched" : "sent",
381
502
  session: null,
382
- sessions: ranked.map((worker, index) => workerRow(worker, agent, index === 0)),
383
- detail: target === null
384
- ? `Would ask Navarch to start a ${nameOf(agent)} worker in ${folder} and type the prompt `
385
- + "into it. No worker of that kind is free on this folder — a worker holding a board "
386
- + "mission and an Argus Agent are both deliberately not candidates."
387
- : `Would ask Navarch to type the prompt into “${target.name}” (${statusWord(target.status)}). `
388
- + "The find is argusd's rather than this CLI's, so this is the worker it would pick from "
389
- + "the snapshot as it stands now.",
503
+ sessions: rowsOf(ranked, agent, target),
504
+ source: found.source,
505
+ detail: dryRunDetail(picked, pick, ranked, agent, folder, ghAccount, found.source),
390
506
  });
391
507
  }
392
- const reply = await askArgus(argus, delegateRequest({ directory, kind, text: oneLine }), readTimeoutMs(ARGUS_WAIT_SECONDS));
508
+ const reply = await askArgus(argus, delegateRequest({
509
+ directory,
510
+ kind,
511
+ text: oneLine,
512
+ ...(pick === undefined
513
+ ? {}
514
+ : { worker: pick.kind === "new" ? ARGUS_NEW_WORKER : pick.id }),
515
+ ...(ghAccount === undefined ? {} : { ghAccount }),
516
+ }), readTimeoutMs(ARGUS_WAIT_SECONDS));
393
517
  const outcome = readDelegation(reply);
394
518
  if (isFailure(outcome))
395
519
  return refuseFailure(refuse, outcome);
@@ -430,75 +554,151 @@ async function navarchStatus(io, env, request, base, deps, refuse, succeed) {
430
554
  }
431
555
  }
432
556
  /**
433
- * The probe, then the fleet, then the find ranked the way the daemon ranks
434
- * it. The candidates on that folder with `[0]` first, or the refusal that
435
- * stopped it.
557
+ * One `delegate_candidates` read, with the fallback an un-reloaded daemon
558
+ * needs or the refusal that stopped it.
559
+ *
560
+ * Three daemons answer this, and `candidatesSupport` tells them apart by the
561
+ * `reason` KEY rather than by prose:
562
+ *
563
+ * - **it served the read** → the rows are the daemon's own, ranked by the
564
+ * daemon's own rule, and every #1402 field is honoured;
565
+ * - **`unknown-op`** → it serves `delegate` and predates #1402. `fleet_status`
566
+ * answers on every generation of argusd, so the list is still worth having —
567
+ * as this CLI's prediction, marked `fleet_status`;
568
+ * - **no `reason` at all** → it predates `delegate` itself, which
569
+ * {@link mapRefusal} already turns into `argusd-outdated`. Listing workers a
570
+ * send is about to refuse to touch would be worse than saying so.
571
+ *
572
+ * `bad-directory` and `bad-kind` are mapped like any other refusal: the read
573
+ * validates them exactly as `delegate` does, so an empty list stays an answer
574
+ * ("nothing eligible there") and a folder that is not there stays a typo.
436
575
  */
437
- async function navarchFleet(argus, kind, directory) {
438
- const probe = await askArgus(argus, delegateStatusRequest(PROBE_REQUEST, 0), readTimeoutMs(0));
439
- if (!servesDelegate(probe)) {
440
- // `servesDelegate` is false only for a refusal, and a refusal with no
441
- // `reason` is a pre-delegate daemon whatever its prose says — which
442
- // `readDelegation` has already turned into `argusd-outdated`.
443
- const failure = readDelegation(probe);
444
- if (isFailure(failure))
445
- return failure;
576
+ async function navarchCandidates(argus, kind, directory) {
577
+ const reply = await askArgus(argus, delegateCandidatesRequest(directory, kind), readTimeoutMs(0));
578
+ const support = candidatesSupport(reply);
579
+ if (support !== "no-op") {
580
+ if (!reply.ok)
581
+ return mapRefusal(reply);
582
+ const { workers, target } = parseCandidates(reply);
583
+ return { workers, target, source: "daemon" };
446
584
  }
447
585
  const fleet = await askArgus(argus, fleetStatusRequest(), readTimeoutMs(0));
448
- if (!fleet.ok) {
449
- const failure = readDelegation(fleet);
450
- if (isFailure(failure))
451
- return failure;
452
- }
453
- return fleet.ok ? rankWorkers(parseFleet(fleet), kind, directory) : [];
586
+ if (!fleet.ok)
587
+ return mapRefusal(fleet);
588
+ const workers = rankWorkers(parseFleet(fleet), kind, directory);
589
+ return { workers, target: workers[0]?.id ?? null, source: "fleet_status" };
454
590
  }
455
591
  /**
456
- * Why `--session` cannot be honoured here yet, or null when it can.
457
- *
458
- * **The `delegate` op takes no target worker.** The find lives entirely in the
459
- * daemon (`BoardStore.delegateTarget`) and Navarch types into whatever it
460
- * named, so the only pick this CLI can promise is the one the daemon would
461
- * have made anyway verified against an isolated daemon, where two eligible
462
- * workers on one folder always drew the lower uuid. Answering `sent` about any
463
- * other is answering about a pane the person did not choose, which is the one
464
- * failure this verb is built around not producing.
465
- *
466
- * It is NOT `session-gone`: that id is a real, live worker, and telling
467
- * somebody their session had died would send them looking for a corpse. argus
468
- * #1402 adds the target field; when it lands this refusal goes and nothing
469
- * else here changes.
592
+ * `--session` or `--gh-account` against an argusd that predates argus #1402
593
+ * the refusal, and it is `argusd-outdated` because a reload is the fix.
594
+ *
595
+ * **The danger is that it would not refuse.** `delegate` reads the keys it
596
+ * knows and ignores the rest, so a target it has never heard of is discarded
597
+ * and the find runs anyway. The caller gets `sent`, naming a worker the person
598
+ * did not pick or a fresh worker running as whoever `gh` was last logged in
599
+ * as. Nothing in the reply distinguishes that from having been obeyed, which
600
+ * is why the check is here and not in a reading of the answer.
470
601
  */
471
- function notTargetable(pick, ranked, agent) {
472
- const head = ranked[0] ?? null;
473
- if (pick.kind === "worker" && head !== null && head.id === pick.id)
474
- return null;
475
- const what = pick.kind === "new"
476
- ? "Starting a fresh worker beside the ones already on this folder"
477
- : `Delivering to worker ${pick.kind === "worker" ? pick.id : ""}`;
478
- const instead = head === null
479
- ? `there is no ${nameOf(agent)} worker free on this folder, so a delegation starts one — which is `
480
- + "what `--session new` asks for, and already what would happen without it"
481
- : `a delegation on this folder goes to “${head.name}” (${head.id}), because argusd does the find `
482
- + "itself and this verb cannot override it";
483
- return (`${what} is not something the Argus \`delegate\` op can express yet: it takes a folder and a kind, `
484
- + `never a worker. Right now ${instead}. Nothing was sent. Board todo #1402 in the argus repo adds `
485
- + "the target field; until it lands, delegate without `--session` to use the worker `--list` marks "
486
- + "`recommended`.");
602
+ function targetUnsupported(pick, ghAccount) {
603
+ const asked = [
604
+ pick === undefined ? "" : pick.kind === "new" ? "`--session new`" : `\`--session ${pick.id}\``,
605
+ ghAccount === undefined ? "" : `\`--gh-account ${ghAccount}\``,
606
+ ].filter((part) => part !== "");
607
+ return (`${asked.join(" and ")} ${asked.length > 1 ? "name things" : "names something"} the argusd running `
608
+ + "on this machine cannot be told. It serves the delegate verb — a plain hand-off works — but the "
609
+ + "target worker and the GitHub account arrived with argus #1402, and this daemon predates it: it "
610
+ + "does not serve `delegate_candidates` either. It would not refuse them, it would IGNORE them: do "
611
+ + "its own find and report `sent` about a worker you did not choose, or start one running as "
612
+ + "whichever account `gh` was last logged in as. So nothing was sent. Reload argusd deliberately, "
613
+ + "because a reload ends every live worker session — or delegate without these flags, which works "
614
+ + "on the daemon you have.");
615
+ }
616
+ /**
617
+ * A `--dry-run --session <uuid>` whose worker is not on the daemon's own list.
618
+ *
619
+ * Predicted rather than performed, and exact where the list came from the
620
+ * daemon: `delegate_candidates` lists from the very predicate `delegate`
621
+ * validates `worker` against, so a uuid missing from it is a uuid the send
622
+ * would refuse `worker-not-eligible` — which is this verb's `session-gone`.
623
+ */
624
+ function wouldBeGone(id, ranked, agent) {
625
+ const now = ranked.length === 0
626
+ ? `No ${nameOf(agent)} worker is free in Navarch on this folder`
627
+ : `What it would accept: ${ranked.map((worker) => `${worker.name} (${worker.id})`).join(", ")}`;
628
+ return (`Worker ${id} is not one argusd would deliver to on this folder — it has exited, taken a board `
629
+ + "mission, is an Argus Agent, or was never there. That is the daemon's own answer to its own "
630
+ + `find, so a real run would be refused \`session-gone\` for exactly this. ${now}. Nothing was `
631
+ + "sent and nothing would be started: a chosen session is a choice. Re-read the inventory with "
632
+ + "`pharos delegate --list --host navarch`, or pass `--session new` to start a fresh worker on "
633
+ + "purpose.");
634
+ }
635
+ /** What a dry run would do, in the dry run's own tense. */
636
+ function dryRunDetail(picked, pick, ranked, agent, folder, ghAccount, source) {
637
+ const core = picked !== null
638
+ ? `Would ask Navarch to type the prompt into “${picked.name}” (${statusWord(picked.status)}).`
639
+ + (pick === undefined
640
+ ? source === "daemon"
641
+ ? " That is the worker argusd itself names as the target for this folder."
642
+ : " The find is argusd's rather than this CLI's, so this is the worker it would pick from"
643
+ + " the snapshot as it stands now."
644
+ : " It was named with `--session`, and argusd validates that pick against the same list it"
645
+ + " came from.")
646
+ : pick?.kind === "new"
647
+ ? `Would ask Navarch to start a FRESH ${nameOf(agent)} worker in ${folder}`
648
+ + (ranked.length === 0
649
+ ? ", which is what would have happened anyway: none is free on this folder."
650
+ : `, leaving the ${ranked.length === 1 ? "one" : String(ranked.length)} already there alone.`)
651
+ : `Would ask Navarch to start a ${nameOf(agent)} worker in ${folder} and type the prompt into `
652
+ + "it. No worker of that kind is free on this folder — a worker holding a board mission and "
653
+ + "an Argus Agent are both deliberately not candidates.";
654
+ // The account is only ever bound to a worker that is STARTED, so a dry run
655
+ // that predicts a send has to say the value would travel and do nothing —
656
+ // the same sentence argusd appends to the real answer.
657
+ const account = ghAccount === undefined
658
+ ? ""
659
+ : picked === null
660
+ ? ` It would run as the GitHub account “${ghAccount}”, and argusd refuses `
661
+ + "`gh-account-unknown` rather than substituting one if it does not know that name."
662
+ : ` The GitHub account “${ghAccount}” would not be applied: the prompt would land in a worker `
663
+ + "that is already running, and its account stands.";
664
+ return core + account;
487
665
  }
488
666
  /** The inventory, in the shape every host answers `--list` in. */
489
- function emitNavarchList(io, base, agent, ranked, pretty) {
490
- const rows = ranked.map((worker, index) => workerRow(worker, agent, index === 0));
667
+ function emitNavarchList(io, base, agent, found, pretty) {
668
+ const rows = rowsOf(found.workers, agent, found.target);
491
669
  const agentName = nameOf(agent);
492
- const detail = rows.length === 0
670
+ const head = rows.length === 0
493
671
  ? `No ${agentName} worker is free in Navarch on ${base.folder}. A delegation would start one. `
494
672
  + "A worker holding a board mission, and an Argus Agent, are running agents that are "
495
673
  + "deliberately not candidates — so this can read empty with panes open on that folder."
496
674
  : `${rows.length} ${agentName} worker${rows.length === 1 ? "" : "s"} in Navarch on ${base.folder}. `
497
- + `A plain delegate would use ${rows[0].name} (${rows[0].status}).`;
675
+ + `A plain delegate would use ${(rows.find((row) => row.recommended) ?? rows[0]).name} `
676
+ + `(${(rows.find((row) => row.recommended) ?? rows[0]).status}).`;
677
+ // **Which side answered, in the list's own prose as well as in `source`.**
678
+ // The two lists are not the same claim: one is what argusd says it would
679
+ // accept, the other is what this CLI predicts it would — and on the older
680
+ // daemon the pick a caller makes from it cannot be honoured at all, which is
681
+ // the thing a person reading the list needs to know BEFORE they pick.
682
+ const provenance = found.source === "daemon"
683
+ ? " argusd answered this list itself (`delegate_candidates`), so a row here is a row it accepts:"
684
+ + " `--session` takes any of these ids."
685
+ : " This argusd predates `delegate_candidates` (argus #1402), so the list is this CLI's own"
686
+ + " reading of `fleet_status` and a prediction of the daemon's find. `--session` and"
687
+ + " `--gh-account` are refused `argusd-outdated` against it — reloading argusd is what lifts"
688
+ + " that, and it ends every live worker session.";
689
+ const detail = head + provenance;
498
690
  // **`incomplete` is false and means it.** Every other host infers the list
499
- // from `ps` and a probe that can fail; this one is the daemon's own register
500
- // of what it is running, so a short answer is an answer and not a gap.
501
- const listing = { ok: true, ...base, sessions: rows, incomplete: false, detail };
691
+ // from `ps` and a probe that can fail; both reads here are the daemon's own
692
+ // register of what it is running, so a short answer is an answer and not a
693
+ // gap.
694
+ const listing = {
695
+ ok: true,
696
+ ...base,
697
+ sessions: rows,
698
+ incomplete: false,
699
+ source: found.source,
700
+ detail,
701
+ };
502
702
  if (!pretty)
503
703
  return emit(io, listing);
504
704
  return emitText(io, [
@@ -506,6 +706,33 @@ function emitNavarchList(io, base, agent, ranked, pretty) {
506
706
  ...rows.map((row) => `${row.recommended ? "*" : " "} ${row.id} ${row.name} — ${row.status}, ${row.detail}`),
507
707
  ].join("\n"));
508
708
  }
709
+ /**
710
+ * The rows, with `recommended` on the one the daemon would take.
711
+ *
712
+ * `target` is read rather than assumed to be `[0]`, even though the two are
713
+ * the same by construction — it is the daemon's own statement of what a plain
714
+ * delegate takes, and `recommended` is defined as exactly that. It falls back
715
+ * to the head for the `fleet_status` route, where the ranking is this CLI's
716
+ * and there is nobody else to ask.
717
+ */
718
+ function rowsOf(ranked, agent, target) {
719
+ const head = headOf(ranked, target);
720
+ return ranked.map((worker) => workerRow(worker, agent, worker === head));
721
+ }
722
+ /**
723
+ * The worker a plain delegate would take: the daemon's own `target` where
724
+ * there is one to read, and the head of the ranking otherwise — which is the
725
+ * `fleet_status` fallback, where there is nobody to ask and this CLI's own
726
+ * rule is all there is.
727
+ */
728
+ function headOf(ranked, target) {
729
+ if (target !== null) {
730
+ const named = ranked.find((worker) => worker.id === target);
731
+ if (named !== undefined)
732
+ return named;
733
+ }
734
+ return ranked[0] ?? null;
735
+ }
509
736
  /**
510
737
  * One worker as a menu row.
511
738
  *
@@ -576,7 +803,7 @@ function reportOf(outcome) {
576
803
  }
577
804
  /** A refusal that came off the socket, in this verb's own shape. */
578
805
  function refuseFailure(refuse, failure) {
579
- return refuse(failure.reason, failure.detail, failure.delegation === undefined ? undefined : reportOf(failure.delegation));
806
+ return refuse(failure.reason, failure.detail, failure.delegation === undefined ? undefined : { delegation: reportOf(failure.delegation) });
580
807
  }
581
808
  /**
582
809
  * A socket that was not there, or a conversation that broke.
@@ -671,6 +898,64 @@ function agentNotInstalled(agent, env) {
671
898
  + (agent === "claude" ? "`npm i -g @anthropic-ai/claude-code`" : "`npm i -g @openai/codex`")
672
899
  + " puts it there. If it IS installed, `pharos doctor` prints the PATH that was searched.");
673
900
  }
901
+ /**
902
+ * `--session` against a bridge that cannot carry one — the version gate's
903
+ * detail, which has three shapes because it has three different fixes.
904
+ *
905
+ * `running` is the version in place AFTER the route's own install attempt, so
906
+ * reaching here at all means one of three things: an upgrade was tried and
907
+ * failed (`upgradeFailure` says how), this pharos ships nothing to replace it
908
+ * with, or what it ships is no newer. Each of those is somebody doing a
909
+ * different thing next, which is why none of them is folded into the others.
910
+ */
911
+ function sessionTooOld(name, running, shipped, upgradeFailure) {
912
+ const unreadable = running === null || running === "";
913
+ const head = `The Pharos bridge in ${name} `
914
+ + (unreadable
915
+ ? "carries no version this can read, so it cannot be shown to understand"
916
+ : `is ${running}, which predates`)
917
+ + ` \`--session\` — that arrived in ${SESSION_BRIDGE_VERSION}. It does not ignore the session in the `
918
+ + "URI: it refuses any query key it does not know, so the prompt would never reach the editor and "
919
+ + "this would have reported it as sent.";
920
+ const fix = upgradeFailure !== null
921
+ ? ` Replacing it with ${shipped ?? "the one this pharos ships"} was tried on the way here and failed: `
922
+ + `${upgradeFailure} \`pharos setup --install vscode-bridge\` runs the same install on its own.`
923
+ : shipped === null
924
+ ? " This pharos ships no bridge it can offer as a replacement, so updating pharos is what brings one."
925
+ : bridgeAtLeast(shipped, SESSION_BRIDGE_VERSION)
926
+ ? ` \`pharos setup --install vscode-bridge\` replaces it with the one this pharos ships (${shipped}).`
927
+ : ` This pharos ships ${shipped}, which is no newer, so updating pharos is what brings one.`;
928
+ return `${head}${fix} Delegating WITHOUT --session works with the bridge you have.`;
929
+ }
930
+ /**
931
+ * The one state installing cannot fix, because the files are only half of it.
932
+ *
933
+ * VS Code replaces an extension's files immediately; the extension host in a
934
+ * window that is ALREADY OPEN goes on running the code it activated with until
935
+ * that window reloads. For an ordinary delegation that costs nothing — the old
936
+ * bridge handles the URI. For `--session` against a bridge that predated
937
+ * {@link SESSION_BRIDGE_VERSION} it costs the prompt: that code refuses the
938
+ * whole URI rather than ignoring the parameter, `open` succeeds anyway, and
939
+ * this verb would answer `sent` about a message nobody received.
940
+ *
941
+ * So it refuses once, and only once — the reload (or the next window) is all
942
+ * that stands between the person and a working send. `cause` is what tells the
943
+ * app this `bridge-not-installed` wants a reload rather than its Install
944
+ * button: the install has already happened.
945
+ */
946
+ function staleWindow(name, replaced, now, dryRun) {
947
+ const installed = now === null || now === "" ? "the bundled bridge" : now;
948
+ return (`${dryRun ? `Installing ${installed} into ${name} would replace` : `The Pharos bridge in ${name} was just replaced with ${installed}, over`} `
949
+ + `${replaced}, which predates \`--session\` (${SESSION_BRIDGE_VERSION}). A ${name} window that is `
950
+ + `already open still runs ${replaced} until it reloads, and ${replaced} does not ignore a session in `
951
+ + "the URI — it refuses the whole thing, so the prompt would be reported as sent and never arrive. "
952
+ + (dryRun
953
+ ? "A real run would install it and then refuse once, for this reason: reload that window "
954
+ + "(Developer: Reload Window) or open a new one first. Delegating WITHOUT --session would work "
955
+ + "either way."
956
+ : "Reload that window (Developer: Reload Window) or open a new one, then run this again. "
957
+ + "Delegating WITHOUT --session works either way."));
958
+ }
674
959
  /**
675
960
  * The URI the bridge handles.
676
961
  *
@@ -703,31 +988,35 @@ async function delegateToVsCode(host, agent, mode, folder, text, agentPath, env,
703
988
  }
704
989
  const extensions = await deps.installedExtensions(host, env);
705
990
  const bridge = extensions?.find((extension) => extension.id === BRIDGE_EXTENSION_ID);
706
- if (bridge === undefined) {
991
+ const bundled = await deps.bundledBridge(env);
992
+ const shipped = bundled?.manifest.version ?? null;
993
+ // Nothing installed and nothing to install with: the one state this route can
994
+ // do nothing about. A package that ships no `.vsix` is a real state — the
995
+ // bridge's build writes it and a checkout that has not run it has none — so
996
+ // it is named rather than reported as an absent extension, which would send
997
+ // somebody to an install that refuses for a different reason.
998
+ if (bridge === undefined && bundled === null) {
707
999
  const directory = extensionsDirectory(host, env) ?? "the extensions directory";
708
1000
  return refuse("bridge-not-installed", `The Pharos bridge (${BRIDGE_EXTENSION_ID}) is not installed in ${name} — looked in ${directory}`
709
1001
  + (extensions === null ? ", which does not exist: that VS Code has never run" : "")
710
- + ". `pharos setup --install vscode-bridge` installs the one this pharos ships.");
711
- }
712
- // **A bridge older than `--session` does not ignore it — it refuses the whole
713
- // URI.** It rejects any query key it does not know (the guard that makes a
714
- // single-encoded `&` in a prompt loud instead of silently truncating one), so
715
- // an unexpected `session` trips it and the prompt never reaches the editor.
716
- // Nothing comes back from VS Code to say so — `open` succeeds either way — so
717
- // without this check the verb answers `sent` about a message that was thrown
718
- // away, and the app tells the person it was delivered. Every machine that
719
- // installed the bridge before this release carries one of these.
720
- //
721
- // `bridge-not-installed` rather than a new reason id: the fix the app already
722
- // renders for it — `pharos setup --install vscode-bridge` — is exactly the
723
- // fix for this, and a reason id is a contract the app decodes.
724
- if (pick !== undefined && !bridgeAtLeast(bridge.version, SESSION_BRIDGE_VERSION)) {
725
- return refuse("bridge-not-installed", `The Pharos bridge installed in ${name} is ${bridge.version}, which predates \`--session\` — that `
726
- + `arrived in ${SESSION_BRIDGE_VERSION}. It would not ignore the session in the URI: it refuses `
727
- + "any query key it does not know, so the prompt would never reach the editor and this would have "
728
- + "reported it as sent. `pharos setup --install vscode-bridge` replaces it with the one this pharos "
729
- + "ships. Delegating WITHOUT --session works with the bridge you have.");
1002
+ + `. This pharos ships no bridge to install either (${bundledVsixPath(env)} is absent), so there is `
1003
+ + "nothing here to put in: `pnpm --filter ./packages/pharos-vscode build` writes one in a checkout, "
1004
+ + "and a published pharos packs it.");
730
1005
  }
1006
+ // **What this pharos ships goes in, on the way.** Absent, or older than the
1007
+ // bundled one, and the same verified installer `setup --install
1008
+ // vscode-bridge` runs is run first — for this flavour only. That is the whole
1009
+ // of #1394: `npm i -g` runs no installer, so before this a CLI update carried
1010
+ // a bridge that never reached an editor.
1011
+ //
1012
+ // A version that cannot be compared is left alone. `shipped` is null when the
1013
+ // package has a `.vsix` whose version could not be read at all, and replacing
1014
+ // a working bridge on a guess is the one move that can make a machine worse.
1015
+ const wanted = bridge === undefined
1016
+ ? "install"
1017
+ : shipped !== null && !bridgeAtLeast(bridge.version, shipped)
1018
+ ? "upgrade"
1019
+ : null;
731
1020
  const claudeExt = extensions?.find((extension) => extension.id === CLAUDE_EXTENSION_ID);
732
1021
  const usesExtensionBinary = mode === "extension" && agent === "claude" && claudeExt !== undefined;
733
1022
  // **The extension route needs no agent on PATH.** The Claude Code extension
@@ -764,6 +1053,88 @@ async function delegateToVsCode(host, agent, mode, folder, text, agentPath, env,
764
1053
  return refuse("session-gone", sessionGone(pick.pid, agent, host, ranked, sessions, incomplete, probeDetail));
765
1054
  }
766
1055
  }
1056
+ // **The install happens HERE, after every refusal that is a pure fact.** An
1057
+ // agent off PATH and a pick that has vanished would both have refused anyway,
1058
+ // and provisioning somebody's editor on the way to a refusal is a side effect
1059
+ // on a call that delivered nothing. Past this line the only thing left to do
1060
+ // is open the URI.
1061
+ //
1062
+ // It costs a few seconds — `code --install-extension` spawns Electron — and
1063
+ // it costs them once per CLI update per flavour, on the call that is already
1064
+ // about that editor.
1065
+ let running = bridge?.version ?? null;
1066
+ /** The version this replaced, when it replaced one. Null on a fresh install. */
1067
+ let replaced = null;
1068
+ let leadNote = "";
1069
+ let tailNote = "";
1070
+ /** Why an upgrade did not happen, when one was tried. The version gate quotes it. */
1071
+ let upgradeFailure = null;
1072
+ if (wanted !== null) {
1073
+ const into = `${shipped ?? "the bridge this pharos ships"} into ${name}`;
1074
+ if (dryRun) {
1075
+ running = shipped;
1076
+ replaced = wanted === "upgrade" ? bridge.version : null;
1077
+ leadNote =
1078
+ `Would install ${into} first`
1079
+ + (replaced === null ? "" : `, replacing ${replaced}`)
1080
+ + " — the same checksum-verified `--install-extension --force` that `pharos setup --install "
1081
+ + "vscode-bridge` runs. ";
1082
+ }
1083
+ else {
1084
+ const outcome = await deps.installBridge(host, env);
1085
+ if (outcome.ok) {
1086
+ running = shipped;
1087
+ replaced = wanted === "upgrade" ? bridge.version : null;
1088
+ leadNote = `Installed the Pharos bridge ${into} first${replaced === null ? "" : `, replacing ${replaced}`}. `;
1089
+ }
1090
+ else if (wanted === "install") {
1091
+ // Nothing was there to fall back on, so this is the refusal the route
1092
+ // had before — with what was tried, rather than with an instruction to
1093
+ // try the same thing by hand.
1094
+ return refuse("bridge-not-installed", `The Pharos bridge (${BRIDGE_EXTENSION_ID}) is not installed in ${name}, and installing the one `
1095
+ + `this pharos ships${shipped === null ? "" : ` (${shipped})`} failed. ${outcome.detail}`
1096
+ + (outcome.command === null ? "" : ` The command was: ${outcome.command}.`)
1097
+ + " `pharos setup --install vscode-bridge` runs the same install on its own.");
1098
+ }
1099
+ else {
1100
+ // **A failed UPGRADE is not a refusal.** The bridge that was there is
1101
+ // still there and still serves this delegation; refusing would take
1102
+ // away something that worked before this release existed.
1103
+ upgradeFailure = outcome.detail;
1104
+ tailNote =
1105
+ ` This pharos ships ${shipped} and installing it over ${bridge.version} failed, so ${bridge.version} `
1106
+ + `handled this. ${outcome.detail}`;
1107
+ }
1108
+ }
1109
+ }
1110
+ // The version gate, now asked about the bridge that is actually in place —
1111
+ // which after the block above may be the one just installed, or the old one
1112
+ // an upgrade failed to replace. **A bridge older than `--session` does not
1113
+ // ignore it: it refuses the whole URI**, because it rejects any query key it
1114
+ // does not know (the guard that makes a single-encoded `&` in a prompt loud
1115
+ // instead of silently truncating one). Nothing comes back from VS Code to say
1116
+ // so — `open` succeeds either way — so without this the verb answers `sent`
1117
+ // about a message that was thrown away and the app tells the person it
1118
+ // arrived.
1119
+ //
1120
+ // `bridge-not-installed` rather than a new reason id: the fix the app already
1121
+ // renders for it is the fix for this, and a reason id is a contract it
1122
+ // decodes.
1123
+ if (pick !== undefined && !bridgeAtLeast(running ?? "", SESSION_BRIDGE_VERSION)) {
1124
+ return refuse("bridge-not-installed", sessionTooOld(name, running, shipped, upgradeFailure));
1125
+ }
1126
+ // …and the case installing cannot fix, because the files are only half of it.
1127
+ if (pick !== undefined && replaced !== null && !bridgeAtLeast(replaced, SESSION_BRIDGE_VERSION)) {
1128
+ return refuse("bridge-not-installed", staleWindow(name, replaced, running, dryRun), { cause: "stale-window" });
1129
+ }
1130
+ // A replacement a window may not have picked up yet is worth saying whenever
1131
+ // it happened — but only as a note, because for a delegation that names no
1132
+ // session the old bridge handles the URI perfectly well.
1133
+ if (replaced !== null) {
1134
+ tailNote +=
1135
+ ` A ${name} window that was already open keeps ${replaced} until it reloads (Developer: Reload Window);`
1136
+ + ` the next window gets ${running ?? "the new one"}. Either serves this delegation.`;
1137
+ }
767
1138
  const uri = delegateUri(spec.vscode.scheme, { folder, agent, mode, text, session: pick });
768
1139
  const agentName = nameOf(agent);
769
1140
  const claudeExtInstalled = mode === "extension" && agent === "claude" ? claudeExt !== undefined : true;
@@ -787,11 +1158,18 @@ async function delegateToVsCode(host, agent, mode, folder, text, agentPath, env,
787
1158
  + `in an integrated terminal in ${folder}.`;
788
1159
  // A deliberate new session makes "a session may exist that was not seen"
789
1160
  // beside the point: one was not wanted. So the two notes are exclusive.
790
- const detail = pick?.kind === "new"
791
- ? `${core}${asked}`
792
- : session === null && incomplete
793
- ? `${core} Detection was incomplete (${probeDetail ?? "a probe failed"}); a running session may exist that could not be found.`
794
- : core;
1161
+ //
1162
+ // **What was done first leads and the caveats trail.** The app renders this
1163
+ // sentence as-is, and "Installed the Pharos bridge 0.3.0 into VS Code
1164
+ // Insiders first." is the fact somebody needs before the one about where the
1165
+ // prompt went.
1166
+ const detail = leadNote
1167
+ + (pick?.kind === "new"
1168
+ ? `${core}${asked}`
1169
+ : session === null && incomplete
1170
+ ? `${core} Detection was incomplete (${probeDetail ?? "a probe failed"}); a running session may exist that could not be found.`
1171
+ : core)
1172
+ + tailNote;
795
1173
  if (!dryRun) {
796
1174
  try {
797
1175
  await deps.open(uri);