@staff0rd/assist 0.710.0 → 0.711.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.
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { Command } from "commander";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@staff0rd/assist",
9
- version: "0.710.0",
9
+ version: "0.711.0",
10
10
  type: "module",
11
11
  main: "dist/index.js",
12
12
  bin: {
@@ -660,8 +660,7 @@ var assistConfigShape = {
660
660
  verify: z3.string().optional()
661
661
  }).optional(),
662
662
  backlog: z3.strictObject({
663
- previewComments: z3.boolean().default(false),
664
- crossRepo: z3.boolean().default(false)
663
+ previewComments: z3.boolean().default(false)
665
664
  }).optional(),
666
665
  backup: z3.strictObject({
667
666
  dir: z3.string().default(DEFAULT_BACKUP_DIR)
@@ -825,7 +824,17 @@ var assistConfigShape = {
825
824
  }).default({ outputDir: "./screenshots" }),
826
825
  sessions: z3.strictObject({
827
826
  nodeName: z3.string().optional(),
828
- links: z3.array(z3.strictObject({ name: z3.string(), url: z3.string() })).optional(),
827
+ links: z3.array(
828
+ z3.union([
829
+ z3.strictObject({ name: z3.string(), url: z3.string() }),
830
+ z3.strictObject({
831
+ name: z3.string(),
832
+ ssh: z3.string(),
833
+ port: z3.number().int(),
834
+ localPort: z3.number().int().optional()
835
+ })
836
+ ])
837
+ ).optional(),
829
838
  linkVersionCheck: z3.enum(["block", "warn", "off"]).default("block"),
830
839
  includeCommittedChanges: z3.boolean().default(true),
831
840
  topBar: z3.boolean().default(true),
@@ -4205,11 +4214,6 @@ var backlogConfigHelp = [
4205
4214
  setter: "assist config set backlog.previewComments true",
4206
4215
  note: "review 'backlog comment' in the web preview pane before it is written (default: off)"
4207
4216
  },
4208
- {
4209
- key: "backlog.crossRepo",
4210
- setter: "assist config set backlog.crossRepo true",
4211
- note: "let phase runs, /draft and /refine plan and make changes in other repos (default: off, limited to this repo)"
4212
- },
4213
4217
  {
4214
4218
  key: "clone.baseDir",
4215
4219
  setter: "assist config set clone.baseDir ~/git",
@@ -6513,17 +6517,6 @@ function buildManualCheckLines(manualChecks, commitBeforePhaseEnd) {
6513
6517
  return [];
6514
6518
  }
6515
6519
 
6516
- // src/commands/backlog/buildJiraStartedLines.ts
6517
- function buildJiraStartedLines(item, phaseNumber) {
6518
- if (phaseNumber !== 1 || !item.jiraKey) {
6519
- return [];
6520
- }
6521
- return [
6522
- "",
6523
- `As your first step, before any implementation, run \`/jira started ${item.jiraKey}\` to assign the issue to yourself and transition it to In Progress.`
6524
- ];
6525
- }
6526
-
6527
6520
  // src/commands/backlog/buildAuthoredPhasePrompt.ts
6528
6521
  function buildAuthoredPhasePrompt(item, phaseNumber, phase, options2 = {
6529
6522
  commitBeforePhaseEnd: false
@@ -6536,7 +6529,7 @@ function buildAuthoredPhasePrompt(item, phaseNumber, phase, options2 = {
6536
6529
  ...buildJiraStartedLines(item, phaseNumber),
6537
6530
  "",
6538
6531
  "Focus ONLY on this phase. Do not work on other phases.",
6539
- options2.crossRepo ? void 0 : "Work only in this item's own repo. Do not modify, commit or push any other repo without the user's explicit permission \u2014 if a task needs changes elsewhere, stop and ask the user to file that work as a separate item in that repo's backlog.",
6532
+ "Work only in this item's own repo. Do not modify, commit or push any other repo without the user's explicit permission \u2014 if a task needs changes elsewhere, stop and ask the user, and suggest filing that work as a separate item in that repo's backlog.",
6540
6533
  "If you need to modify backlog items, run `assist backlog --help` to discover available commands.",
6541
6534
  "When you have completed all tasks for this phase, run /verify to check your work.",
6542
6535
  ...buildManualCheckLines(manualChecks, options2.commitBeforePhaseEnd),
@@ -6563,6 +6556,15 @@ function buildContextLines(item, phaseNumber, phase) {
6563
6556
  formatTasks(phase)
6564
6557
  ];
6565
6558
  }
6559
+ function buildJiraStartedLines(item, phaseNumber) {
6560
+ if (phaseNumber !== 1 || !item.jiraKey) {
6561
+ return [];
6562
+ }
6563
+ return [
6564
+ "",
6565
+ `As your first step, before any implementation, run \`/jira started ${item.jiraKey}\` to assign the issue to yourself and transition it to In Progress.`
6566
+ ];
6567
+ }
6566
6568
  function formatTasks(phase) {
6567
6569
  return phase.tasks.map((t) => `- ${t.task}`).join("\n");
6568
6570
  }
@@ -6619,14 +6621,13 @@ function buildReviewPrompt(item, phaseNumber, options2 = {
6619
6621
  // src/commands/backlog/buildPhasePrompt.ts
6620
6622
  var REVIEW_PHASE_NAME = "Review";
6621
6623
  function buildPhasePrompt(item, phaseNumber, phase) {
6622
- const { worktree, backlog } = loadConfig();
6624
+ const worktree = loadConfig().worktree;
6623
6625
  const commitBeforePhaseEnd = worktree?.commitBeforePhaseEnd ?? worktree?.commitBeforeManualChecks ?? false;
6624
6626
  if (phase.name === REVIEW_PHASE_NAME) {
6625
6627
  return buildReviewPrompt(item, phaseNumber, { commitBeforePhaseEnd });
6626
6628
  }
6627
6629
  return buildAuthoredPhasePrompt(item, phaseNumber, phase, {
6628
- commitBeforePhaseEnd,
6629
- crossRepo: backlog?.crossRepo ?? false
6630
+ commitBeforePhaseEnd
6630
6631
  });
6631
6632
  }
6632
6633
 
@@ -12774,8 +12775,8 @@ var seqConfigHelp = [
12774
12775
  var nodesConfigHelp = [
12775
12776
  {
12776
12777
  key: "sessions.links",
12777
- setter: "assist sessions nodes link <name> http://127.0.0.1:<port>",
12778
- note: "linked nodes whose sessions merge into this node's web UI; each name must match the peer's sessions.nodeName"
12778
+ setter: "assist sessions nodes link <name> http://127.0.0.1:<port> (or --ssh <alias> --port <port>)",
12779
+ note: "linked nodes whose sessions merge into this node's web UI, each direct (url) or over an ssh tunnel (ssh alias, peer port, localPort); each name must match the peer's sessions.nodeName"
12779
12780
  },
12780
12781
  {
12781
12782
  key: "sessions.linkVersionCheck",
@@ -14075,6 +14076,27 @@ async function prList(req, res) {
14075
14076
  respondJson(res, 200, { prs: await getOpenPrs(cwd) });
14076
14077
  }
14077
14078
 
14079
+ // src/commands/sessions/shared/loadLinkSpecs.ts
14080
+ var TUNNEL_PORT_BASE = 43e3;
14081
+ function defaultTunnelPort(port) {
14082
+ return TUNNEL_PORT_BASE + port % 1e3;
14083
+ }
14084
+ function toLinkSpec(link3) {
14085
+ if ("url" in link3) return { name: link3.name, url: link3.url };
14086
+ const localPort = link3.localPort ?? defaultTunnelPort(link3.port);
14087
+ return {
14088
+ name: link3.name,
14089
+ url: `http://127.0.0.1:${localPort}`,
14090
+ ssh: { alias: link3.ssh, port: link3.port, localPort }
14091
+ };
14092
+ }
14093
+ function loadLinkSpecs() {
14094
+ return (loadConfig().sessions?.links ?? []).map(toLinkSpec);
14095
+ }
14096
+ function findLinkSpec(name) {
14097
+ return loadLinkSpecs().find((spec) => spec.name === name);
14098
+ }
14099
+
14078
14100
  // src/commands/sessions/shared/newTraceId.ts
14079
14101
  import { randomUUID as randomUUID7 } from "crypto";
14080
14102
  var TRACE_HEADER = "x-assist-trace-id";
@@ -14138,7 +14160,7 @@ function proxyTarget(req) {
14138
14160
  if (!url.pathname.startsWith("/api/") || !node) return { kind: "local" };
14139
14161
  if (arrivedOverLink(req) || node === resolveNodeName())
14140
14162
  return { kind: "local" };
14141
- const link3 = loadConfig().sessions?.links?.find((l) => l.name === node);
14163
+ const link3 = findLinkSpec(node);
14142
14164
  if (!link3) return { kind: "unknown", node };
14143
14165
  url.searchParams.delete("node");
14144
14166
  return {
@@ -39396,6 +39418,14 @@ function registerRun(program2) {
39396
39418
 
39397
39419
  // src/commands/sessions/nodes/formatLink.ts
39398
39420
  import chalk249 from "chalk";
39421
+
39422
+ // src/commands/sessions/daemon/links/describeTarget.ts
39423
+ function describeTarget({ url, ssh }) {
39424
+ if (!ssh) return `direct ${url}`;
39425
+ return `ssh ${ssh.alias}:${ssh.port} via 127.0.0.1:${ssh.localPort}`;
39426
+ }
39427
+
39428
+ // src/commands/sessions/nodes/formatLink.ts
39399
39429
  var STATE_COLOURS = {
39400
39430
  connected: chalk249.green,
39401
39431
  connecting: chalk249.yellow,
@@ -39407,7 +39437,7 @@ function formatLink(link3) {
39407
39437
  const peer = link3.peerVersion ? ` peer ${link3.peerVersion}` : "";
39408
39438
  const error = link3.error ? `
39409
39439
  ${chalk249.dim(`last error${link3.errorAt ? ` ${link3.errorAt}` : ""}: ${link3.error}`)}` : "";
39410
- return ` ${link3.name} ${colour(link3.state)} direct ${link3.url}${peer}${error}`;
39440
+ return ` ${link3.name} ${colour(link3.state)} ${describeTarget(link3)}${peer}${error}`;
39411
39441
  }
39412
39442
 
39413
39443
  // src/commands/sessions/daemon/listDaemonPids.ts
@@ -43176,10 +43206,10 @@ function restoreAllSessions(spawner, sessions, notify2) {
43176
43206
 
43177
43207
  // src/commands/sessions/daemon/retrySession.ts
43178
43208
  function retrySession(session, clients, onStatusChange) {
43179
- const spawn11 = respawnThunk(session);
43180
- if (!spawn11) return false;
43209
+ const spawn13 = respawnThunk(session);
43210
+ if (!spawn13) return false;
43181
43211
  const respawn = () => {
43182
- respawnSession(session, spawn11, "running", clients, onStatusChange);
43212
+ respawnSession(session, spawn13, "running", clients, onStatusChange);
43183
43213
  daemonLog(`session ${session.id} retried: ${session.name}`);
43184
43214
  };
43185
43215
  const pty2 = session.pty;
@@ -43710,11 +43740,140 @@ async function selfUpdatePeer(url) {
43710
43740
  throw new Error(body.error ?? `self-update responded ${response.status}`);
43711
43741
  }
43712
43742
 
43743
+ // src/commands/sessions/daemon/links/SshTunnel.ts
43744
+ import { createInterface as createInterface10 } from "readline";
43745
+ import { setTimeout as delay2 } from "timers/promises";
43746
+
43747
+ // src/commands/sessions/daemon/links/killOrphanOnDaemonExit.ts
43748
+ var liveChildren = /* @__PURE__ */ new Set();
43749
+ var exitHookInstalled = false;
43750
+ function killOrphanOnDaemonExit(child) {
43751
+ liveChildren.add(child);
43752
+ child.once("exit", () => liveChildren.delete(child));
43753
+ if (exitHookInstalled) return;
43754
+ exitHookInstalled = true;
43755
+ process.once("exit", () => {
43756
+ for (const live of liveChildren) live.kill();
43757
+ });
43758
+ }
43759
+
43760
+ // src/commands/sessions/daemon/links/sshTunnelArgs.ts
43761
+ function sshTunnelArgs({ alias, port, localPort }) {
43762
+ return [
43763
+ "-N",
43764
+ "-o",
43765
+ "BatchMode=yes",
43766
+ "-o",
43767
+ "ExitOnForwardFailure=yes",
43768
+ "-o",
43769
+ "ServerAliveInterval=15",
43770
+ "-o",
43771
+ "ServerAliveCountMax=3",
43772
+ "-L",
43773
+ `${localPort}:127.0.0.1:${port}`,
43774
+ alias
43775
+ ];
43776
+ }
43777
+
43778
+ // src/commands/sessions/daemon/links/SshTunnelIo.ts
43779
+ import { spawn as spawn11 } from "child_process";
43780
+
43781
+ // src/commands/sessions/shared/portAccepts.ts
43782
+ import { connect as connect3 } from "net";
43783
+ function portAccepts(port, timeoutMs = 1e3) {
43784
+ return new Promise((resolve25) => {
43785
+ const socket = connect3({ host: "127.0.0.1", port });
43786
+ const settle = (ok) => {
43787
+ socket.destroy();
43788
+ resolve25(ok);
43789
+ };
43790
+ socket.setTimeout(timeoutMs, () => settle(false));
43791
+ socket.once("connect", () => settle(true));
43792
+ socket.once("error", () => settle(false));
43793
+ });
43794
+ }
43795
+
43796
+ // src/commands/sessions/daemon/links/SshTunnelIo.ts
43797
+ var defaultSshTunnelIo = {
43798
+ spawn: (args) => spawn11("ssh", args, {
43799
+ stdio: ["ignore", "ignore", "pipe"],
43800
+ windowsHide: true
43801
+ }),
43802
+ accepts: (port) => portAccepts(port),
43803
+ bindTimeoutMs: 15e3,
43804
+ pollMs: 200
43805
+ };
43806
+
43807
+ // src/commands/sessions/daemon/links/SshTunnel.ts
43808
+ var SshTunnel = class {
43809
+ constructor(name, target, io = defaultSshTunnelIo) {
43810
+ this.name = name;
43811
+ this.target = target;
43812
+ this.io = io;
43813
+ }
43814
+ child;
43815
+ exitReason = "";
43816
+ lastStderr = "";
43817
+ async ready() {
43818
+ if (!this.child) this.start();
43819
+ await this.waitBound(this.child);
43820
+ }
43821
+ dispose() {
43822
+ const child = this.child;
43823
+ this.child = void 0;
43824
+ if (!child) return;
43825
+ daemonLog(`link ${this.name} tunnel: stopping ssh`);
43826
+ child.kill();
43827
+ }
43828
+ start() {
43829
+ const args = sshTunnelArgs(this.target);
43830
+ daemonLog(`link ${this.name} tunnel: spawning ssh ${args.join(" ")}`);
43831
+ const child = this.io.spawn(args);
43832
+ this.child = child;
43833
+ this.lastStderr = "";
43834
+ killOrphanOnDaemonExit(child);
43835
+ if (child.stderr)
43836
+ createInterface10({ input: child.stderr }).on("line", (line) => {
43837
+ this.lastStderr = line;
43838
+ daemonLog(`link ${this.name} ssh: ${line}`);
43839
+ });
43840
+ child.once("error", (error) => this.onExit(child, error.message));
43841
+ child.once(
43842
+ "exit",
43843
+ (code, signal) => this.onExit(child, signal ? `signal ${signal}` : `code ${code}`)
43844
+ );
43845
+ }
43846
+ onExit(child, reason4) {
43847
+ if (this.child !== child) return;
43848
+ this.child = void 0;
43849
+ this.exitReason = this.lastStderr ? `${reason4}: ${this.lastStderr}` : reason4;
43850
+ daemonLog(`link ${this.name} tunnel: ssh exited (${this.exitReason})`);
43851
+ }
43852
+ async waitBound(child) {
43853
+ const { alias, localPort } = this.target;
43854
+ const deadline = Date.now() + this.io.bindTimeoutMs;
43855
+ while (Date.now() < deadline) {
43856
+ if (this.child !== child)
43857
+ throw new Error(`ssh tunnel to ${alias} exited (${this.exitReason})`);
43858
+ if (await this.io.accepts(localPort)) return;
43859
+ await delay2(this.io.pollMs);
43860
+ }
43861
+ this.dispose();
43862
+ throw new Error(
43863
+ `ssh tunnel to ${alias} did not bind 127.0.0.1:${localPort} within ${this.io.bindTimeoutMs / 1e3}s`
43864
+ );
43865
+ }
43866
+ };
43867
+
43868
+ // src/commands/sessions/daemon/links/sshTunnelFor.ts
43869
+ var sshTunnelFor = (spec) => spec.ssh ? new SshTunnel(spec.name, spec.ssh) : void 0;
43870
+
43713
43871
  // src/commands/sessions/daemon/links/linkDeps.ts
43714
43872
  function linkDeps(options2, callbacks) {
43715
43873
  return {
43716
43874
  ...callbacks,
43717
43875
  transport: options2.transport ?? connectLinkWebSocket,
43876
+ tunnel: options2.tunnel ?? sshTunnelFor,
43718
43877
  heal: options2.heal ?? selfUpdatePeer,
43719
43878
  reconnectMs: options2.reconnectMs ?? 3e3,
43720
43879
  createTimeoutMs: options2.createTimeoutMs ?? 15e3
@@ -43819,6 +43978,7 @@ function createLinkContext(spec, deps2) {
43819
43978
  deps: deps2,
43820
43979
  relay: createRelayState(spec.name, deps2.viewers, deps2.onSessionsChanged),
43821
43980
  breaker: new LaunchCircuitBreaker(`link ${spec.name} ws`),
43981
+ tunnel: deps2.tunnel(spec),
43822
43982
  socket: null,
43823
43983
  greeted: false,
43824
43984
  state: "disconnected",
@@ -43837,6 +43997,7 @@ function describeLink(ctx) {
43837
43997
  return {
43838
43998
  name: ctx.spec.name,
43839
43999
  url: ctx.spec.url,
44000
+ ssh: ctx.spec.ssh,
43840
44001
  state: ctx.state,
43841
44002
  error: ctx.blockedMessage ?? ctx.lastError?.message,
43842
44003
  errorAt: ctx.lastError?.at,
@@ -43936,15 +44097,15 @@ function linkHealRefusal(node, peerVersion, healAttempted) {
43936
44097
  }
43937
44098
 
43938
44099
  // src/commands/sessions/daemon/links/scheduleReconnect.ts
43939
- function armReconnect(ctx, delay2) {
44100
+ function armReconnect(ctx, delay3) {
43940
44101
  clearTimeout(ctx.reconnectTimer);
43941
- ctx.reconnectTimer = setTimeout(ctx.connect, delay2);
44102
+ ctx.reconnectTimer = setTimeout(ctx.connect, delay3);
43942
44103
  ctx.reconnectTimer.unref?.();
43943
44104
  }
43944
44105
  function scheduleReconnect2(ctx) {
43945
44106
  if (ctx.disposed || ctx.blockedMessage) return;
43946
- const delay2 = ctx.breaker.tripped() ? ctx.breaker.remainingMs() : ctx.deps.reconnectMs;
43947
- armReconnect(ctx, delay2);
44107
+ const delay3 = ctx.breaker.tripped() ? ctx.breaker.remainingMs() : ctx.deps.reconnectMs;
44108
+ armReconnect(ctx, delay3);
43948
44109
  }
43949
44110
  function reconnectNow(ctx) {
43950
44111
  ctx.breaker.clear();
@@ -44186,8 +44347,10 @@ async function openLink(ctx) {
44186
44347
  if (ctx.disposed || ctx.blockedMessage || ctx.socket) return;
44187
44348
  if (ctx.breaker.tripped()) return scheduleReconnect2(ctx);
44188
44349
  setLinkState(ctx, "connecting");
44189
- daemonLog(`link ${ctx.spec.name} ws: connecting to ${ctx.spec.url}`);
44190
44350
  try {
44351
+ await ctx.tunnel?.ready();
44352
+ if (ctx.disposed) return;
44353
+ daemonLog(`link ${ctx.spec.name} ws: connecting to ${ctx.spec.url}`);
44191
44354
  const socket = await ctx.deps.transport(ctx.spec.url, {
44192
44355
  onLine: (line) => onLinkLine(ctx, line),
44193
44356
  onClose: (reason4) => onLinkClose(ctx, socket, reason4)
@@ -44250,21 +44413,25 @@ var NodeLink = class {
44250
44413
  this.ctx.disposed = true;
44251
44414
  clearTimeout(this.ctx.reconnectTimer);
44252
44415
  disconnectLink(this.ctx);
44416
+ this.ctx.tunnel?.dispose();
44253
44417
  }
44254
44418
  };
44255
44419
 
44256
44420
  // src/commands/sessions/daemon/links/reconcileLinks.ts
44421
+ function sameTarget(wanted, current) {
44422
+ return wanted?.url === current.url && JSON.stringify(wanted.ssh) === JSON.stringify(current.ssh);
44423
+ }
44257
44424
  function reconcileLinks(links2, specs, create) {
44258
44425
  const wanted = new Map(specs.map((spec) => [spec.name, spec]));
44259
44426
  for (const [name, link3] of links2) {
44260
- if (wanted.get(name)?.url === link3.spec.url) continue;
44427
+ if (sameTarget(wanted.get(name), link3.spec)) continue;
44261
44428
  daemonLog(`link ${name}: removed`);
44262
44429
  link3.dispose();
44263
44430
  links2.delete(name);
44264
44431
  }
44265
44432
  for (const spec of specs) {
44266
44433
  if (links2.has(spec.name)) continue;
44267
- daemonLog(`link ${spec.name}: added (${spec.url})`);
44434
+ daemonLog(`link ${spec.name}: added (${describeTarget(spec)})`);
44268
44435
  const link3 = create(spec);
44269
44436
  links2.set(spec.name, link3);
44270
44437
  link3.start();
@@ -44297,7 +44464,7 @@ var NodeLinks = class {
44297
44464
  this.options = options2;
44298
44465
  }
44299
44466
  reload() {
44300
- const specs = this.options.specs?.() ?? loadConfig().sessions?.links ?? [];
44467
+ const specs = this.options.specs?.() ?? loadLinkSpecs();
44301
44468
  const deps2 = linkDeps(this.options, {
44302
44469
  viewers: () => this.clients.viewers(),
44303
44470
  onSessionsChanged: this.onSessionsChanged,
@@ -44785,7 +44952,7 @@ function exitAfterFlush(code) {
44785
44952
  }
44786
44953
 
44787
44954
  // src/commands/sessions/daemon/handleConnection.ts
44788
- import { createInterface as createInterface10 } from "readline";
44955
+ import { createInterface as createInterface11 } from "readline";
44789
44956
 
44790
44957
  // src/commands/sessions/daemon/handleHelloRequest.ts
44791
44958
  var handleHelloRequest = (client, m, d) => {
@@ -44800,10 +44967,10 @@ var handleHelloRequest = (client, m, d) => {
44800
44967
  };
44801
44968
 
44802
44969
  // src/commands/sessions/daemon/creator.ts
44803
- function creator(isNew, spawn11) {
44970
+ function creator(isNew, spawn13) {
44804
44971
  return (client, m, d) => {
44805
44972
  if (m.links.route(client, d)) return;
44806
- const result = spawn11(m, d);
44973
+ const result = spawn13(m, d);
44807
44974
  if (typeof result !== "string") {
44808
44975
  sendTo(client, { type: "error", message: result.error });
44809
44976
  return;
@@ -45329,7 +45496,7 @@ function handleConnection(socket, manager) {
45329
45496
  };
45330
45497
  manager.addClient(client);
45331
45498
  manager.clients.greet(client);
45332
- const lines2 = createInterface10({ input: socket });
45499
+ const lines2 = createInterface11({ input: socket });
45333
45500
  lines2.on("error", () => {
45334
45501
  });
45335
45502
  lines2.on("line", (line) => {
@@ -45528,6 +45695,37 @@ function failed2(hop, error, remediation) {
45528
45695
  return { hop, ok: false, error, remediation };
45529
45696
  }
45530
45697
 
45698
+ // src/commands/sessions/nodes/agentHop.ts
45699
+ var ONEPASSWORD_AGENT = '"~/Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock"';
45700
+ async function agentHop(ssh, probes) {
45701
+ const agent = await probes.sshAgent(ssh.alias);
45702
+ switch (agent.status) {
45703
+ case "ok":
45704
+ return passed(
45705
+ "agent",
45706
+ `${agent.keys} key(s)${agent.socket ? ` via ${agent.socket}` : ""}`
45707
+ );
45708
+ case "missing":
45709
+ return failed2(
45710
+ "agent",
45711
+ `no IdentityAgent for ${ssh.alias} and SSH_AUTH_SOCK is unset`,
45712
+ `IdentityAgent missing \u2014 add \`IdentityAgent ${ONEPASSWORD_AGENT}\` under \`Host ${ssh.alias}\` in ~/.ssh/config`
45713
+ );
45714
+ case "no-keys":
45715
+ return failed2(
45716
+ "agent",
45717
+ `the agent${agent.socket ? ` at ${agent.socket}` : ""} holds no keys`,
45718
+ "add or import an SSH key in 1Password, then allow it in the SSH agent"
45719
+ );
45720
+ case "unreachable":
45721
+ return failed2(
45722
+ "agent",
45723
+ agent.error,
45724
+ "1Password SSH agent not reachable \u2014 open and unlock 1Password and turn on Settings \u2192 Developer \u2192 Use the SSH agent"
45725
+ );
45726
+ }
45727
+ }
45728
+
45531
45729
  // src/commands/sessions/nodes/fetchPeerJson.ts
45532
45730
  var PEER_TIMEOUT_MS = 3e3;
45533
45731
  function peerErrorCode(error) {
@@ -45614,8 +45812,61 @@ function linkStateHop(spec, probes) {
45614
45812
  );
45615
45813
  }
45616
45814
 
45815
+ // src/commands/sessions/nodes/sshHop.ts
45816
+ var REMEDIATIONS = [
45817
+ [
45818
+ /connection refused/i,
45819
+ (alias) => `Remote Login is off on ${alias} \u2014 on a Mac turn on System Settings \u2192 General \u2192 Sharing \u2192 Remote Login; on Windows run \`Start-Service sshd\` (OpenSSH Server)`
45820
+ ],
45821
+ [
45822
+ /could not resolve hostname/i,
45823
+ (alias) => `no \`Host ${alias}\` in ~/.ssh/config and ${alias} does not resolve \u2014 add a Host entry with its HostName`
45824
+ ],
45825
+ [
45826
+ /host key verification failed/i,
45827
+ (alias) => `run \`ssh ${alias}\` once to accept its host key`
45828
+ ],
45829
+ [
45830
+ /agent refused operation|sign_and_send_pubkey/i,
45831
+ () => "1Password refused to sign \u2014 unlock it and approve the key request"
45832
+ ],
45833
+ [
45834
+ /permission denied/i,
45835
+ (alias) => `${alias} rejected every key offered \u2014 add this node's 1Password public key to ~/.ssh/authorized_keys on ${alias} (C:\\ProgramData\\ssh\\administrators_authorized_keys for a Windows administrator)`
45836
+ ],
45837
+ [
45838
+ /timed out/i,
45839
+ (alias) => `${alias} did not answer on its ssh port \u2014 is it awake and on this network?`
45840
+ ]
45841
+ ];
45842
+ async function sshHop(ssh, probes) {
45843
+ const { code, stderr } = await probes.ssh(ssh.alias);
45844
+ if (code === 0) return passed("ssh", `ssh ${ssh.alias} authenticated`);
45845
+ const error = stderr || `ssh exited ${code}`;
45846
+ const match = REMEDIATIONS.find(([pattern2]) => pattern2.test(error));
45847
+ return failed2(
45848
+ "ssh",
45849
+ error,
45850
+ match?.[1](ssh.alias) ?? `run \`ssh -v ${ssh.alias}\` to see where it fails`
45851
+ );
45852
+ }
45853
+
45854
+ // src/commands/sessions/nodes/tunnelHop.ts
45855
+ async function tunnelHop(spec, ssh, probes) {
45856
+ const bound = `127.0.0.1:${ssh.localPort}`;
45857
+ if (await probes.tunnel(ssh.localPort))
45858
+ return passed("tunnel", `${bound} \u2192 ${ssh.alias}:${ssh.port}`);
45859
+ return failed2(
45860
+ "tunnel",
45861
+ `nothing bound on ${bound}`,
45862
+ `this node's daemon keeps \`ssh -N -L ${ssh.localPort}:127.0.0.1:${ssh.port} ${ssh.alias}\` up \u2014 run \`assist daemon restart\` and check daemon.log for \`link ${spec.name} tunnel:\` and \`link ${spec.name} ssh:\` lines`
45863
+ );
45864
+ }
45865
+
45617
45866
  // src/commands/sessions/nodes/webHop.ts
45618
45867
  function webRemediation(spec, error) {
45868
+ if (spec.ssh && error.status === void 0)
45869
+ return `nothing listening on ${spec.ssh.port} on ${spec.ssh.alias} \u2014 is project-switch running ${spec.name}'s web server?`;
45619
45870
  const { hostname: hostname2, port } = new URL(spec.url);
45620
45871
  switch (peerErrorCode(error)) {
45621
45872
  case "ECONNREFUSED":
@@ -45643,7 +45894,7 @@ async function webHop(spec, probes) {
45643
45894
  hop: failed2(
45644
45895
  "web",
45645
45896
  `peer reports nodeName ${health2.nodeName}, link expects ${spec.name}`,
45646
- `relink with \`assist sessions nodes unlink ${spec.name}\` then \`assist sessions nodes link ${health2.nodeName} ${spec.url}\`, or set sessions.nodeName on the peer`
45897
+ `relink with \`assist sessions nodes unlink ${spec.name}\` then \`assist sessions nodes link ${health2.nodeName} ${spec.ssh ? `--ssh ${spec.ssh.alias} --port ${spec.ssh.port}` : spec.url}\`, or set sessions.nodeName on the peer`
45647
45898
  )
45648
45899
  };
45649
45900
  return {
@@ -45667,6 +45918,17 @@ function peerDaemonHop(spec, health2) {
45667
45918
  async function diagnoseLink(spec, probes) {
45668
45919
  const hops = [];
45669
45920
  const done2 = () => ({ ...spec, ok: hops.every((h) => h.ok), hops });
45921
+ if (spec.ssh) {
45922
+ const { ssh } = spec;
45923
+ for (const probe of [
45924
+ () => agentHop(ssh, probes),
45925
+ () => sshHop(ssh, probes),
45926
+ () => tunnelHop(spec, ssh, probes)
45927
+ ]) {
45928
+ hops.push(await probe());
45929
+ if (!hops.at(-1)?.ok) return done2();
45930
+ }
45931
+ }
45670
45932
  const web3 = await webHop(spec, probes);
45671
45933
  hops.push(web3.hop);
45672
45934
  if (!web3.health) return done2();
@@ -45725,6 +45987,77 @@ async function probePeerHello(url) {
45725
45987
  return result;
45726
45988
  }
45727
45989
 
45990
+ // src/commands/sessions/nodes/probeSsh.ts
45991
+ import { spawn as spawn12 } from "child_process";
45992
+ var PROBE_TIMEOUT_MS = 15e3;
45993
+ function probeSsh(alias) {
45994
+ return new Promise((resolve25) => {
45995
+ const child = spawn12(
45996
+ "ssh",
45997
+ ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", alias, "exit"],
45998
+ { stdio: ["ignore", "ignore", "pipe"], windowsHide: true }
45999
+ );
46000
+ let stderr = "";
46001
+ child.stderr.on("data", (chunk) => {
46002
+ stderr += chunk;
46003
+ });
46004
+ const timer = setTimeout(() => child.kill(), PROBE_TIMEOUT_MS);
46005
+ child.once("error", (error) => {
46006
+ clearTimeout(timer);
46007
+ resolve25({ code: null, stderr: error.message });
46008
+ });
46009
+ child.once("close", (code) => {
46010
+ clearTimeout(timer);
46011
+ resolve25({ code, stderr: stderr.trim() });
46012
+ });
46013
+ });
46014
+ }
46015
+
46016
+ // src/commands/sessions/nodes/probeSshAgent.ts
46017
+ import { spawnSync as spawnSync11 } from "child_process";
46018
+ import { homedir as homedir26 } from "os";
46019
+ var PROBE_TIMEOUT_MS2 = 5e3;
46020
+ function parseIdentityAgent(sshConfig, env = process.env) {
46021
+ const line = sshConfig.split(/\r?\n/).find((l) => l.toLowerCase().startsWith("identityagent "));
46022
+ const value = line?.slice("identityagent ".length).trim().replace(/^"(.*)"$/, "$1");
46023
+ if (!value || value.toLowerCase() === "none") return void 0;
46024
+ if (value === "SSH_AUTH_SOCK" || value === "$SSH_AUTH_SOCK")
46025
+ return env.SSH_AUTH_SOCK;
46026
+ return value.replace(/^~(?=$|[/\\])/, homedir26());
46027
+ }
46028
+ function configuredAgent(alias) {
46029
+ const result = spawnSync11("ssh", ["-G", alias], {
46030
+ encoding: "utf8",
46031
+ timeout: PROBE_TIMEOUT_MS2,
46032
+ windowsHide: true
46033
+ });
46034
+ return parseIdentityAgent(result.stdout ?? "") ?? process.env.SSH_AUTH_SOCK;
46035
+ }
46036
+ async function probeSshAgent(alias) {
46037
+ const socket = configuredAgent(alias);
46038
+ if (!socket && process.platform !== "win32") return { status: "missing" };
46039
+ const result = spawnSync11("ssh-add", ["-l"], {
46040
+ encoding: "utf8",
46041
+ timeout: PROBE_TIMEOUT_MS2,
46042
+ windowsHide: true,
46043
+ env: socket ? { ...process.env, SSH_AUTH_SOCK: socket } : process.env
46044
+ });
46045
+ if (result.error)
46046
+ return { status: "unreachable", socket, error: result.error.message };
46047
+ if (result.status === 0)
46048
+ return {
46049
+ status: "ok",
46050
+ socket,
46051
+ keys: result.stdout.trim().split(/\r?\n/).length
46052
+ };
46053
+ if (result.status === 1) return { status: "no-keys", socket };
46054
+ return {
46055
+ status: "unreachable",
46056
+ socket,
46057
+ error: result.stderr.trim() || `ssh-add exited ${result.status}`
46058
+ };
46059
+ }
46060
+
45728
46061
  // src/commands/sessions/nodes/printReport.ts
45729
46062
  import chalk250 from "chalk";
45730
46063
  function printReport(report2) {
@@ -45753,6 +46086,9 @@ function doctorProbes(live) {
45753
46086
  return {
45754
46087
  health: (url) => fetchPeerJson(url, "/api/health"),
45755
46088
  hello: probePeerHello,
46089
+ sshAgent: probeSshAgent,
46090
+ ssh: probeSsh,
46091
+ tunnel: (localPort) => portAccepts(localPort),
45756
46092
  linkState: (name) => {
45757
46093
  if (!live) return "no-daemon";
45758
46094
  return live.links.find((l) => l.name === name) ?? "unknown-link";
@@ -45760,9 +46096,7 @@ function doctorProbes(live) {
45760
46096
  };
45761
46097
  }
45762
46098
  async function doctorNodes(name, options2) {
45763
- const specs = (loadConfig().sessions?.links ?? []).filter(
45764
- (spec) => !name || spec.name === name
45765
- );
46099
+ const specs = loadLinkSpecs().filter((spec) => !name || spec.name === name);
45766
46100
  if (name && specs.length === 0)
45767
46101
  throw new Error(`No link named ${name}; see assist sessions nodes`);
45768
46102
  const probes = doctorProbes(await queryNodes());
@@ -45802,13 +46136,38 @@ function parseLinkUrl(url) {
45802
46136
  throw new Error(`link url must be http(s): ${url}`);
45803
46137
  return parsed.origin;
45804
46138
  }
45805
- async function linkNode(name, url) {
46139
+ function parsePort(flag, value) {
46140
+ const port = Number(value);
46141
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
46142
+ throw new Error(`${flag} must be a port number, got ${value}`);
46143
+ return port;
46144
+ }
46145
+ function freeTunnelPort(port, others) {
46146
+ const taken = new Set(others.map((link3) => toLinkSpec(link3).ssh?.localPort));
46147
+ let candidate = defaultTunnelPort(port);
46148
+ while (taken.has(candidate)) candidate++;
46149
+ return candidate;
46150
+ }
46151
+ function buildLink(name, url, options2, others) {
46152
+ if (url && options2.ssh)
46153
+ throw new Error("pass either <url> or --ssh <alias>, not both");
46154
+ if (url) return { name, url: parseLinkUrl(url) };
46155
+ if (!options2.ssh)
46156
+ throw new Error("pass the peer's <url> or --ssh <alias> --port <port>");
46157
+ const port = parsePort("--port", options2.port);
46158
+ const localPort = options2.localPort ? parsePort("--local-port", options2.localPort) : freeTunnelPort(port, others);
46159
+ return { name, ssh: options2.ssh, port, localPort };
46160
+ }
46161
+ async function linkNode(name, url, options2) {
45806
46162
  if (name.includes(":")) throw new Error("node names cannot contain ':'");
45807
46163
  if (name === resolveNodeName())
45808
46164
  throw new Error(`${name} is this node; link to a different node`);
45809
- const others = readLinks().filter((link3) => link3.name !== name);
45810
- await writeLinks([...others, { name, url: parseLinkUrl(url) }]);
45811
- console.log(chalk251.green(`Linked ${name} (${parseLinkUrl(url)})`));
46165
+ const others = readLinks().filter((link4) => link4.name !== name);
46166
+ const link3 = buildLink(name, url, options2, others);
46167
+ await writeLinks([...others, link3]);
46168
+ console.log(
46169
+ chalk251.green(`Linked ${name} (${describeTarget(toLinkSpec(link3))})`)
46170
+ );
45812
46171
  }
45813
46172
 
45814
46173
  // src/commands/sessions/nodes/listNodes.ts
@@ -45817,11 +46176,10 @@ async function nodesReport() {
45817
46176
  const live = await queryNodes();
45818
46177
  if (live)
45819
46178
  return { local: live.local, daemonRunning: true, links: live.links };
45820
- const configured = loadConfig().sessions?.links ?? [];
45821
46179
  return {
45822
46180
  local: resolveNodeName(),
45823
46181
  daemonRunning: false,
45824
- links: configured.map((link3) => ({ ...link3, state: "disconnected" }))
46182
+ links: loadLinkSpecs().map((link3) => ({ ...link3, state: "disconnected" }))
45825
46183
  };
45826
46184
  }
45827
46185
  async function listNodes(options2) {
@@ -45845,7 +46203,7 @@ async function fetchLogTail(name, lines2) {
45845
46203
  path: daemonPaths.log,
45846
46204
  lines: readLogTail(daemonPaths.log, lines2)
45847
46205
  };
45848
- const link3 = loadConfig().sessions?.links?.find((l) => l.name === name);
46206
+ const link3 = findLinkSpec(name);
45849
46207
  if (!link3)
45850
46208
  throw new Error(`No link named ${name}; see assist sessions nodes`);
45851
46209
  try {
@@ -45887,8 +46245,14 @@ async function unlinkNode(name) {
45887
46245
  // src/commands/sessions/nodes/registerNodes.ts
45888
46246
  function registerNodes(sessions) {
45889
46247
  const cmd = sessions.command("nodes").description("List this node and every linked node with its link state").option("--json", "Output as JSON").action(listNodes);
45890
- cmd.command("link <name> <url>").description(
45891
- "Link a peer node by its web server URL (name must match the peer's sessions.nodeName)"
46248
+ cmd.command("link <name> [url]").description(
46249
+ "Link a peer node by its web server URL, or over ssh with --ssh and --port (name must match the peer's sessions.nodeName)"
46250
+ ).option(
46251
+ "--ssh <alias>",
46252
+ "Tunnel to the peer through this ~/.ssh/config alias"
46253
+ ).option("--port <port>", "The peer's loopback web server port (with --ssh)").option(
46254
+ "--local-port <port>",
46255
+ "Local end of the ssh tunnel (default: 43000 + port % 1000, bumped past other links)"
45892
46256
  ).action(linkNode);
45893
46257
  cmd.command("unlink <name>").description("Remove a linked node").action(unlinkNode);
45894
46258
  cmd.command("doctor [name]").description(