@phnx-labs/agents-cli 1.23.4 → 1.23.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/bootstrap.js +14 -9
  3. package/dist/commands/exec.js +7 -7
  4. package/dist/commands/focus.js +17 -16
  5. package/dist/commands/go.js +2 -2
  6. package/dist/commands/ps-roster.d.ts +1 -1
  7. package/dist/commands/ps-roster.js +7 -5
  8. package/dist/commands/resume.d.ts +1 -0
  9. package/dist/commands/resume.js +9 -1
  10. package/dist/commands/sessions-resume.js +65 -18
  11. package/dist/commands/setup-terminal.js +3 -2
  12. package/dist/lib/exec.js +6 -1
  13. package/dist/lib/hosts/reconnect.d.ts +3 -2
  14. package/dist/lib/hosts/reconnect.js +8 -9
  15. package/dist/lib/launch-log.d.ts +15 -0
  16. package/dist/lib/launch-log.js +120 -0
  17. package/dist/lib/project-root.d.ts +1 -0
  18. package/dist/lib/project-root.js +9 -0
  19. package/dist/lib/remote-agents-json.d.ts +1 -0
  20. package/dist/lib/remote-agents-json.js +4 -2
  21. package/dist/lib/secrets-client.js +18 -3
  22. package/dist/lib/self-update.d.ts +1 -0
  23. package/dist/lib/self-update.js +4 -0
  24. package/dist/lib/session/active.d.ts +9 -3
  25. package/dist/lib/session/active.js +19 -5
  26. package/dist/lib/session/pid-registry.d.ts +1 -0
  27. package/dist/lib/session/pid-registry.js +6 -0
  28. package/dist/lib/session/remote/remote-list.d.ts +3 -1
  29. package/dist/lib/session/remote/remote-list.js +65 -19
  30. package/dist/lib/session/remote-active.d.ts +3 -1
  31. package/dist/lib/session/remote-active.js +4 -3
  32. package/dist/lib/session/session-cache.d.ts +1 -0
  33. package/dist/lib/session/session-cache.js +14 -1
  34. package/dist/lib/ssh-exec.js +1 -1
  35. package/dist/lib/terminal/backends/vscodium-agent.d.ts +31 -8
  36. package/dist/lib/terminal/backends/vscodium-agent.js +134 -7
  37. package/dist/lib/terminal/engine.d.ts +7 -1
  38. package/dist/lib/terminal/engine.js +68 -9
  39. package/dist/lib/terminal/index.d.ts +1 -1
  40. package/dist/lib/terminal/index.js +1 -1
  41. package/dist/lib/terminal/run-surface.d.ts +1 -0
  42. package/dist/lib/terminal/run-surface.js +8 -2
  43. package/dist/lib/terminal/types.d.ts +6 -2
  44. package/dist/lib/types.d.ts +1 -0
  45. package/dist/lib/types.js +1 -0
  46. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.23.6
4
+
5
+ - **Live sessions no longer drop out of `sessions --active` (roster liveness).** A resumed session was dropped from the roster on every cached rescan because the PID-reuse check compared the live process against when the session was born, so fleet workers flipped between listing their sessions and listing none. The check now uses the process's own start time. A peer answering a fleet sweep scans fresh rather than serving its snapshot, and agent-named helper processes with no session or launch record (embedded app-servers, daemons) are no longer listed as sessions. Source: `cli/src/lib/session/active.ts`, `cli/src/commands/ps-roster.ts`.
6
+
7
+ ## 1.23.5
8
+
9
+ - **`agents ps` drops a dead offloaded tab once its owner answers.** A desktop editor
10
+ tab bound to a session that runs on a fleet worker used to list as its own
11
+ `unknown` session (37 rows on one desktop) even after the worker answered the
12
+ sweep and reported no such live session. The worker is the authority for what
13
+ runs there, so the fleet merge now drops that tab's row when the worker answered
14
+ and lacks the session; a live session still shows as one row with the worker's
15
+ status, and a worker that went unheard still leaves the tab as `unknown`, never
16
+ running. A worker whose reply is not a JSON array (a login banner, an error
17
+ object) does not count as an answer. Same rule `agents feed watch` already applied. Source:
18
+ `cli/src/commands/ps-roster.ts`, `cli/src/lib/remote-agents-json.ts`.
19
+
20
+ - **`agents sessions resume` puts a VSCodium tab in the session's own project window and only says "opened" when the editor confirms it.** The `vscodium-agent` backend sent `codium --open-url …/spawn` alone, so the tab landed in whichever window was last focused (agents-cli and svatlas sessions opened inside the `agents` window) and the CLI printed `Opened 1/1` without knowing whether anything opened. It now raises the project's window first (a multi-root workspace through its workspace file), sends a `nonce` and the local `project` folder in the payload, and waits up to 15 s for the extension's ack at `~/.swarmify/agents/spawn-acks/<nonce>.json`; no ack or a wrong-window ack exits non-zero with the command that works instead. A session that already has a live editor tab is focused rather than duplicated, and a live process on its host is named (host + pid). Needs the matching agi-ext release to write acks; until then every `--vscodium` open reports the missing ack. Source: `cli/src/lib/terminal/backends/vscodium-agent.ts`, `cli/src/lib/terminal/engine.ts`, `cli/src/commands/sessions-resume.ts`, `cli/src/lib/project-root.ts`.
21
+
22
+ - **A routed `agents sessions resume` no longer hangs on the far side, and a dropped hop no longer pretends the host is unreachable.** Three faults in the SSH hop the CLI makes for itself (`runOnPeer`): (1) the peer's `agents` showed the interactive "Update available" picker before resuming, so after a crash 14 restored tabs on one worker sat in that prompt with no agent started; a hop now carries `AGENTS_PEER_HOP=1` and the peer prints the one-line upgrade notice instead. (2) Every interactive hop rode the shared ControlMaster, tying long-lived agent TUIs to one master connection and to sshd's per-connection `MaxSessions` (10); TTY sessions (`runOnPeer`, `sshStream`) now get their own connection and short probes keep multiplexing. (3) ssh exits 255 both when it cannot connect and when the remote side of a running session dies, and the CLI treated every 255 as "unreachable" and fell back to a local resume that found no transcript; it now checks with a fresh connection and only a failed one counts as unreachable. Resume also names an older process of the same session that is still running on the host (`[agents] <id> is still running on <host> as pid <n> …`) and leaves it alone. Source: `cli/src/lib/session/remote/remote-list.ts`, `cli/src/lib/ssh-exec.ts`, `cli/src/bootstrap.ts`, `cli/src/lib/self-update.ts`, `cli/src/commands/resume.ts`, `cli/src/lib/session/pid-registry.ts`.
23
+
24
+ - **A tab or hop that starts an agent opens straight into the agent.** `--quiet` (which every tab the CLI opens now passes) and a CLI-made SSH hop send everything agents itself says to a per-launch log, `~/.agents/.cache/logs/launches/<time>-<pid>.log` on the machine doing the work: routing banners, `[agents] session recovery → …`, the upgrade notice, the multi-install warning. The standalone `secrets` engine's stderr (`[secrets] using the encrypted file store …`, once per lookup) now always goes to `logs/secrets-serve.log`, and the peer's login profile output (nvm's `.npmrc` warning) to `logs/peer-login.log`. Only a launch that fails prints, as `The agent did not start: <cause>` plus the log path, and writes `launches/<session>.json`; `agents sessions --json` rows carry it as `lastLaunch`. `agents run` and `agents sessions resume|focus` never show the interactive upgrade menu, so a box on an older CLI no longer parks a tab on `? Update available … ❯ Upgrade now`. Source: `cli/src/lib/launch-log.ts`, `cli/src/bootstrap.ts`, `cli/src/lib/secrets-client.ts`, `cli/src/lib/session/remote/remote-list.ts`.
25
+
26
+ - **A tab whose SSH link drops reconnects to the same session by itself** when the host still answers, through the same reconnect loop `run --device` uses; "unreachable" is reported only after a fresh connection also fails. Source: `cli/src/lib/session/remote/remote-list.ts`, `cli/src/lib/hosts/reconnect.ts`.
27
+
28
+ - **Confirmed results only.** `sessions resume`, `sessions focus` tab opening and `run --terminal` no longer print `Opening N session(s)…`, `opened <id> — tab — …` or `Opened N/M in …`. VSCodium reports the acked window and tab; a backend with no confirmation says the request was sent and that the tab is not confirmed. Source: `cli/src/lib/terminal/engine.ts` (`describeLaunch`).
29
+
30
+ - **Live rows list the session's artifacts with a kind.** `agents sessions --active --json` (and the watch streams) now fill `artifacts` from the same ledger as `files.changes`: created images, videos, html and markdown docs, absolute on the row's own machine, with `kind` (`image`, `video`, `html`, `markdown`, `pdf`, `other`). The picker JSON (`sessions --json`, in-process path) also gains `title`, `localProject`, `lastUserMessage`, `lastAgentLine`, `editorTab` and `lastLaunch`. Source: `cli/src/lib/session/session-cache.ts`, `cli/src/lib/session/active.ts`, `cli/src/commands/sessions.ts`.
31
+
3
32
  ## 1.23.4
4
33
 
5
34
  - **A live process with no readable transcript is `unknown`, not `running`.** Being alive is not evidence that an agent is working. On 2026-10-10 the fleet stream listed 26 such rows as running: headless `codex` and `rush` processes with no session id, folder or title (11 on one machine). They now report `unknown` (phase `idle`, `◌` in `agents ps`); a dead one is still `closed`. Fleet "running" counts drop by those rows, and such a row whose editor window closed stays `unknown` instead of turning `orphaned`. Spec SES-18 says so. Source: `cli/src/lib/session/active.ts` (`resolveFallbackStatus`).
package/dist/bootstrap.js CHANGED
@@ -146,8 +146,9 @@ async function showWhatsNew(fromVersion, toVersion) {
146
146
  }
147
147
  const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
148
148
  import { getUpdateCheckPath, getMigratedSentinelPath, getUserAgentsDir, getRuntimeStateDir } from './lib/state.js';
149
+ import { LAUNCH_LOG_ENV, launchesAgent, startQuietLaunch } from './lib/launch-log.js';
149
150
  import { resolveBrandName, disabledCommandsForActiveBrand } from './lib/brand.js';
150
- import { readUpdateCache, saveUpdateCheck, dismissUpdateVersion, shouldPromptUpgrade, resolveMultiInstallInventory, remediateStaleAgentsCliInstalls, resolveRunningPackageRoot, manualUninstallCommand, } from './lib/self-update.js';
151
+ import { readUpdateCache, saveUpdateCheck, dismissUpdateVersion, shouldPromptUpgrade, isPeerHop, resolveMultiInstallInventory, remediateStaleAgentsCliInstalls, resolveRunningPackageRoot, manualUninstallCommand, } from './lib/self-update.js';
151
152
  const UPDATE_CHECK_FILE = getUpdateCheckPath();
152
153
  const MULTI_INSTALL_SCAN_FILE = path.join(path.dirname(UPDATE_CHECK_FILE), '.multi-install-scan');
153
154
  function maybeWarnMultiInstall() {
@@ -269,11 +270,11 @@ async function installResolvedPackage(metadata) {
269
270
  }
270
271
  }
271
272
  }
272
- async function promptUpgrade(latestVersion) {
273
+ async function promptUpgrade(latestVersion, mayPrompt) {
273
274
  const { default: ora } = await import('ora');
274
275
  const { confirm, select } = await import('@inquirer/prompts');
275
276
  const { isInteractiveTerminal, isPromptCancelled } = await import('./commands/utils.js');
276
- if (!isInteractiveTerminal()) {
277
+ if (!mayPrompt || !isInteractiveTerminal()) {
277
278
  console.error(chalk.yellow(`Update available: ${VERSION} -> ${latestVersion}. Run: agents upgrade --yes`));
278
279
  return;
279
280
  }
@@ -339,7 +340,7 @@ function refreshUpdateCacheInBackground() {
339
340
  .catch(() => {
340
341
  });
341
342
  }
342
- async function checkForUpdates() {
343
+ async function checkForUpdates(mayPrompt) {
343
344
  if (process.env.AGENTS_CLI_DISABLE_AUTO_UPDATE)
344
345
  return;
345
346
  maybeWarnMultiInstall();
@@ -349,7 +350,7 @@ async function checkForUpdates() {
349
350
  }
350
351
  if (shouldPromptUpgrade(cache, VERSION)) {
351
352
  try {
352
- await promptUpgrade(cache.latestVersion);
353
+ await promptUpgrade(cache.latestVersion, mayPrompt);
353
354
  }
354
355
  catch (err) {
355
356
  const { isPromptCancelled } = await import('./commands/utils.js');
@@ -358,8 +359,8 @@ async function checkForUpdates() {
358
359
  }
359
360
  }
360
361
  }
361
- async function maybeBootstrapShimIntegration(requestedCommand, isDocumentationRequest, verboseStartup) {
362
- if (!verboseStartup && (!process.stdin.isTTY || !process.stdout.isTTY)) {
362
+ async function maybeBootstrapShimIntegration(requestedCommand, isDocumentationRequest, verboseStartup, quietStart) {
363
+ if (quietStart || (!verboseStartup && (!process.stdin.isTTY || !process.stdout.isTTY))) {
363
364
  return;
364
365
  }
365
366
  if (isDocumentationRequest) {
@@ -720,10 +721,14 @@ const isReadOnlyUpdatePreview = !isDocumentationRequest &&
720
721
  ((passedArgs.find((arg) => !arg.startsWith('-')) === 'update' && passedArgs.includes('--check')) ||
721
722
  passedArgs.find((arg) => !arg.startsWith('-')) === 'menubar' ||
722
723
  (passedArgs[0] === 'config' && passedArgs.includes('menubar.autoUpdate')));
724
+ const quietStart = launchesAgent(passedArgs)
725
+ && (isPeerHop() || passedArgs.includes('--quiet') || Boolean(process.env[LAUNCH_LOG_ENV]));
726
+ if (quietStart)
727
+ startQuietLaunch(passedArgs);
723
728
  if (!isDocumentationRequest) {
724
729
  bootMark('bootstrap:evaluated');
725
730
  if (!isReadOnlyUpdatePreview) {
726
- await checkForUpdates();
731
+ await checkForUpdates(!quietStart && !launchesAgent(passedArgs));
727
732
  const { spawnDetachedSync } = await import('./lib/auto-pull.js');
728
733
  spawnDetachedSync();
729
734
  }
@@ -805,7 +810,7 @@ if (passedArgs.length === 0) {
805
810
  }
806
811
  try {
807
812
  if (!isReadOnlyUpdatePreview) {
808
- await maybeBootstrapShimIntegration(requestedCommand, isDocumentationRequest, verboseStartup);
813
+ await maybeBootstrapShimIntegration(requestedCommand, isDocumentationRequest, verboseStartup, quietStart);
809
814
  }
810
815
  bootMark('bootstrap:pre-parse');
811
816
  await program.parseAsync();
@@ -392,15 +392,14 @@ async function handleTerminalHandoff(agentSpec, options, prompt) {
392
392
  cwd: cwd ?? process.cwd(),
393
393
  sessions,
394
394
  ctx: currentContext(),
395
+ label: prompt === undefined ? 'the session' : 'the run',
395
396
  });
396
397
  if (!result.ok) {
397
- console.error(chalk.red(`Could not open a terminal: ${result.error ?? 'unknown error'}`));
398
+ console.error(chalk.red(result.description ?? `Could not open a terminal: ${result.error ?? 'unknown error'}`));
398
399
  process.exit(1);
399
400
  }
400
- if (!options.quiet) {
401
- const what = prompt === undefined ? 'session' : 'run';
402
- console.log(chalk.gray(`Opened the ${what} in ${result.description}.`));
403
- }
401
+ if (!options.quiet)
402
+ console.log(result.description);
404
403
  }
405
404
  export function resumePickerOptionConflict(options) {
406
405
  const used = [
@@ -1452,7 +1451,7 @@ ${formatModeSupportTable().split('\n').map((line) => ` ${line}`).join('\n
1452
1451
  });
1453
1452
  }
1454
1453
  }
1455
- const { pickReconnectTarget, reconnectInteractiveSession, afterInteractiveRemoteExit, SSH_CONN_FAILURE } = await import('../lib/hosts/reconnect.js');
1454
+ const { pickReconnectTarget, reconnectInteractiveSession, reattachRemoteSession, afterInteractiveRemoteExit, SSH_CONN_FAILURE } = await import('../lib/hosts/reconnect.js');
1456
1455
  const reconnectTarget = pickReconnectTarget({
1457
1456
  agent: runAgent,
1458
1457
  sessionId: hostSessionId,
@@ -1468,9 +1467,10 @@ ${formatModeSupportTable().split('\n').map((line) => ` ${line}`).join('\n
1468
1467
  });
1469
1468
  if (next.reconnect && reconnectTarget) {
1470
1469
  process.exit(await reconnectInteractiveSession({
1471
- host,
1470
+ hostName: host.name,
1472
1471
  target: reconnectTarget,
1473
1472
  initialExit: exitCode,
1473
+ reattach: () => reattachRemoteSession(host, reconnectTarget),
1474
1474
  }));
1475
1475
  }
1476
1476
  if (next.notice)
@@ -20,7 +20,7 @@ import { buildPreview } from './sessions-picker.js';
20
20
  import { multiItemPicker } from '../lib/picker.js';
21
21
  import { sessionRecoveryRunArgs } from '../lib/session/recovery.js';
22
22
  import { shellQuote, assertValidSshTarget } from '../lib/ssh-exec.js';
23
- import { openSurfaces, currentContext, availableBackends, detectCurrentBackend, } from '../lib/terminal/index.js';
23
+ import { openSurfaces, describeLaunch, currentContext, availableBackends, detectCurrentBackend, } from '../lib/terminal/index.js';
24
24
  import { addressabilityRecoveryHint } from '../lib/terminal/resolve.js';
25
25
  import { isInteractiveTerminal, isPromptCancelled } from './utils.js';
26
26
  import { setHelpSections } from '../lib/help.js';
@@ -503,7 +503,7 @@ export async function openFocusTabs(targets, self, deps = {}) {
503
503
  if (deps.attachOnly)
504
504
  return null;
505
505
  const remote = !sessionProcessIsLocal(s, self);
506
- return buildSessionRecoveryCommand(metaFor(s), remote);
506
+ return [...buildSessionRecoveryCommand(metaFor(s), remote), '--quiet'];
507
507
  };
508
508
  const planned = await Promise.all(targets.map(async (s) => {
509
509
  const rail = await probe(s, self);
@@ -532,25 +532,23 @@ export async function openFocusTabs(targets, self, deps = {}) {
532
532
  await jumpTo(openable[0].s, self, selectFallback(deps.attachOnly));
533
533
  return;
534
534
  }
535
- console.log(chalk.gray(`Opening ${openable.length} session${openable.length === 1 ? '' : 's'} in ${backend} (tabs)…`));
536
535
  const results = await open(openable.map((p) => ({
537
536
  cwd: cwdFor(p.s, byId),
537
+ project: cwdFor(p.s, byId),
538
538
  command: p.plan.command,
539
539
  agent: p.s.kind || undefined,
540
540
  sessionId: p.s.sessionId || undefined,
541
541
  })), { backend, packing: 'tabs' });
542
- let opened = 0;
543
542
  results.forEach((r, i) => {
544
543
  const p = openable[i];
545
- if (r.ok) {
546
- opened++;
547
- console.log(chalk.green(` opened ${shortId(p.s)}`) + chalk.gray(` — tab — (${p.plan.note})`));
548
- }
544
+ const line = describeLaunch(r, { verb: 'Opened', label: `${shortId(p.s)} (${p.plan.note})` });
545
+ if (r.ok)
546
+ console.log(line);
549
547
  else {
550
- console.log(chalk.red(` failed ${shortId(p.s)} — ${r.error}`));
548
+ console.error(chalk.red(line));
549
+ process.exitCode = 1;
551
550
  }
552
551
  });
553
- console.log(chalk.gray(`\nOpened ${opened}/${openable.length} in ${backend}.`));
554
552
  }
555
553
  function cwdFor(s, byId) {
556
554
  const cwd = byId.get(s.sessionId ?? '')?.cwd ?? s.cwd;
@@ -594,7 +592,7 @@ const resumeInNewTab = async (s, remote) => {
594
592
  return;
595
593
  }
596
594
  const meta = (await richMetaById(id)) ?? metaFromActive(s);
597
- const command = buildSessionRecoveryCommand(meta);
595
+ const command = [...buildSessionRecoveryCommand(meta), '--quiet'];
598
596
  const cwd = meta.cwd && fs.existsSync(meta.cwd) ? meta.cwd : process.cwd();
599
597
  const ctx = currentContext();
600
598
  const backend = detectCurrentBackend(ctx) ?? availableBackends(ctx)[0]?.id;
@@ -603,10 +601,13 @@ const resumeInNewTab = async (s, remote) => {
603
601
  return;
604
602
  }
605
603
  console.log(chalk.gray(`${shortId(s)} has no live terminal to attach — opening a new ${backend} tab and resuming a copy.`));
606
- const results = await openSurfaces([{ cwd, command }], { backend, packing: 'tabs' });
607
- const r = results[0];
608
- if (!r || !r.ok) {
609
- console.log(chalk.red(` failed to open — ${r?.error ?? 'unknown error'}`));
610
- console.log(chalk.gray(` try: agents sessions resume ${meta.shortId}`));
604
+ const results = await openSurfaces([{ cwd, project: cwd, command }], { backend, packing: 'tabs' });
605
+ const line = describeLaunch(results[0], { verb: 'Resumed', label: shortId(s) });
606
+ if (results[0].ok)
607
+ console.log(line);
608
+ else {
609
+ console.error(chalk.red(line));
610
+ console.error(chalk.gray(` Resume it in this terminal instead: agents sessions resume ${meta.id}`));
611
+ process.exitCode = 1;
611
612
  }
612
613
  };
@@ -79,7 +79,7 @@ export async function gatherLiveTargets(local, opts = {}) {
79
79
  const remote = await gatherRemoteActive(opts.hosts, {
80
80
  earlyExit: liveSelectorEarlyExit(opts.selector),
81
81
  });
82
- active = dedupeByMachineSession([...localActive, ...remote.sessions]);
82
+ active = dedupeByMachineSession([...localActive, ...remote.sessions], remote.answered);
83
83
  }
84
84
  catch { }
85
85
  }
@@ -249,7 +249,7 @@ async function focusEditorTab(tab) {
249
249
  return false;
250
250
  }
251
251
  }
252
- console.log(chalk.gray(`Sent ${shortId(tab)} → ${sessionHeadline(tab) || tab.terminalId} (${path.basename(tab.workspaceDir)}) to ${variant.label}.`));
252
+ console.log(`Sent focus to tab "${sessionHeadline(tab) || tab.terminalId}" in ${variant.label} window "${path.basename(tab.workspaceDir)}". ${variant.label} does not confirm a focus.`);
253
253
  return true;
254
254
  }
255
255
  export async function focusEditorTabOf(s, self) {
@@ -37,7 +37,7 @@ interface MachineGroupedLayout {
37
37
  machines: MachineGroup[];
38
38
  }
39
39
  export declare function groupSessionsByMachine(sessions: ActiveSession[], localMachine: string): MachineGroupedLayout;
40
- export declare function dedupeByMachineSession(sessions: ActiveSession[]): ActiveSession[];
40
+ export declare function dedupeByMachineSession(sessions: ActiveSession[], answered: readonly string[]): ActiveSession[];
41
41
  export declare function filterActiveSessionsByHostScope(sessions: ActiveSession[], hosts: string[] | undefined, self: string): ActiveSession[];
42
42
  export declare function gatherActiveSessions(opts?: {
43
43
  local?: boolean;
@@ -6,7 +6,7 @@ import { enumerateGhosttyTabs, assignGhosttyTabs } from '../lib/session/ghostty-
6
6
  import { mapPanesToTargets, listClients } from '../lib/tmux/session.js';
7
7
  import { resolveViewingIn, viewingInLabel } from '../lib/session/viewing-in.js';
8
8
  import { machineId, normalizeHost } from '../lib/session/sync/config.js';
9
- import { gatherRemoteActive } from '../lib/session/remote-active.js';
9
+ import { gatherRemoteActive, NO_FANOUT_ENV } from '../lib/session/remote-active.js';
10
10
  import { hostToken, remoteHostsToDial, shouldIncludeLocal } from '../lib/session/remote-list.js';
11
11
  import { loadFleetActiveSessions, loadLocalActiveSessions } from '../lib/session/session-cache.js';
12
12
  import { stringWidth, truncateToWidth, padToWidth, terminalWidth } from '../lib/session/width.js';
@@ -262,7 +262,8 @@ export function groupSessionsByMachine(sessions, localMachine) {
262
262
  }));
263
263
  return { machines };
264
264
  }
265
- export function dedupeByMachineSession(sessions) {
265
+ export function dedupeByMachineSession(sessions, answered) {
266
+ const heard = new Set(answered.map(normalizeHost));
266
267
  const seen = new Map();
267
268
  const out = [];
268
269
  for (const s of sessions) {
@@ -280,7 +281,7 @@ export function dedupeByMachineSession(sessions) {
280
281
  if (out[at].offloadedFrom && !s.offloadedFrom)
281
282
  out[at] = s;
282
283
  }
283
- return out;
284
+ return out.filter(s => !(s.sessionId && s.offloadedFrom && s.context !== 'teams' && s.machine && heard.has(normalizeHost(s.machine))));
284
285
  }
285
286
  export function filterActiveSessionsByHostScope(sessions, hosts, self) {
286
287
  if (!hosts || hosts.length === 0)
@@ -400,7 +401,8 @@ async function enrichTmuxLocators(local, surfaces = []) {
400
401
  }
401
402
  export async function gatherActiveSessions(opts = {}) {
402
403
  const forceRefresh = opts.forceRefresh === true
403
- || process.env.AGENTS_SESSIONS_FORCE_REFRESH === '1';
404
+ || process.env.AGENTS_SESSIONS_FORCE_REFRESH === '1'
405
+ || process.env[NO_FANOUT_ENV] === '1';
404
406
  const scoped = (opts.hosts?.length ?? 0) > 0;
405
407
  if (opts.local && !scoped) {
406
408
  const loaded = await loadLocalActiveSessions({ forceRefresh });
@@ -443,7 +445,7 @@ async function gatherActiveSessionsLive(opts = {}) {
443
445
  remoteDeviceCount = remote.deviceCount;
444
446
  remoteSkipped = remote.skipped;
445
447
  remoteDiscoveryFailed = remote.discoveryFailed;
446
- merged = dedupeByMachineSession([...local, ...remote.sessions]);
448
+ merged = dedupeByMachineSession([...local, ...remote.sessions], remote.answered);
447
449
  }
448
450
  }
449
451
  return {
@@ -20,3 +20,4 @@ export declare function buildResumeRunArgs(session: {
20
20
  }, prompt: string | undefined, options: StrictResumeOptions): string[];
21
21
  export declare function wantsStrictResume(prompt: string | undefined, options: StrictResumeOptions): boolean;
22
22
  export declare function runStrictResume(sessionId: string, prompt: string | undefined, options: StrictResumeOptions): Promise<void>;
23
+ export declare function stillRunningNotice(shortId: string, pid: number, host: string): string;
@@ -4,6 +4,7 @@ import { resolveSessionMetadataValue } from '../lib/session/selection.js';
4
4
  import { sessionOwnerDevice, consumeResumePinned, RESUME_PINNED_ENV } from '../lib/session/resume-owner.js';
5
5
  import { machineId } from '../lib/machine-id.js';
6
6
  import { takeOverDetachedSession } from '../lib/session/detached.js';
7
+ import { liveSessionProcesses } from '../lib/session/pid-registry.js';
7
8
  const RESUME_SOURCE_ENV = 'AGENTS_RESUME_SOURCE_JSON';
8
9
  export function resumeLocalFallbackSource(session, self = machineId()) {
9
10
  return { ...session, machine: self };
@@ -67,7 +68,6 @@ export function wantsStrictResume(prompt, options) {
67
68
  !!options.interactive ||
68
69
  !!options.headless ||
69
70
  !!options.cwd ||
70
- !!options.quiet ||
71
71
  !!options.here);
72
72
  }
73
73
  export async function runStrictResume(sessionId, prompt, options) {
@@ -122,8 +122,16 @@ export async function runStrictResume(sessionId, prompt, options) {
122
122
  }
123
123
  const localSession = pinnedHere ? resumeLocalFallbackSource(outcome.session) : outcome.session;
124
124
  await takeOverDetachedSession(localSession.id);
125
+ if (!options.quiet) {
126
+ for (const running of liveSessionProcesses(localSession.id)) {
127
+ process.stderr.write(chalk.yellow(stillRunningNotice(localSession.shortId, running.pid, machineId())));
128
+ }
129
+ }
125
130
  process.exitCode = await delegateLocalResume(localSession, prompt, options);
126
131
  }
132
+ export function stillRunningNotice(shortId, pid, host) {
133
+ return `An older copy of ${shortId} is still running on ${host} (pid ${pid}). It was left alone.\n`;
134
+ }
127
135
  async function delegateLocalResume(session, prompt, options) {
128
136
  const args = buildResumeRunArgs(session, prompt, options);
129
137
  const child = spawn(process.execPath, [process.argv[1], ...args], {
@@ -8,7 +8,7 @@ import { multiItemPicker, itemPicker } from '../lib/picker.js';
8
8
  import { buildPreview } from './sessions-picker.js';
9
9
  import { formatPickerLabel, pickerColumnsFor } from '../lib/session/presentation.js';
10
10
  import { parseAgentFilter, resolveSessionMetadataValue, sessionMatchesQuery } from '../lib/session/selection.js';
11
- import { openSurfaces, availableBackends, detectCurrentBackend, currentContext, shellQuote, } from '../lib/terminal/index.js';
11
+ import { openSurfaces, describeLaunch, availableBackends, detectCurrentBackend, currentContext, shellQuote, } from '../lib/terminal/index.js';
12
12
  import { isInteractiveTerminal, isPromptCancelled, normalizeSingleDeviceOption } from './utils.js';
13
13
  import { setHelpSections } from '../lib/help.js';
14
14
  import { confirm } from '@inquirer/prompts';
@@ -16,8 +16,9 @@ import { spawn } from 'node:child_process';
16
16
  import { looksLikeSessionId } from '../lib/session/discover.js';
17
17
  import { machineId } from '../lib/session/sync/config.js';
18
18
  import { sessionOriginDevice, sessionRecoveryDestinationMatches, sessionRecoveryPeer, sessionTranscriptReadable } from '../lib/session/recovery.js';
19
- import { buildResumeRemoteArgs, runStrictResume, wantsStrictResume } from './resume.js';
20
- import { toRemotePortable } from '../lib/project-root.js';
19
+ import { buildResumeRemoteArgs, runStrictResume, stillRunningNotice, wantsStrictResume } from './resume.js';
20
+ import { localProjectFolder, toRemotePortable } from '../lib/project-root.js';
21
+ import { liveSessionProcesses } from '../lib/session/pid-registry.js';
21
22
  import { attachLocalLiveSelector } from '../lib/session/local-tmux-attach.js';
22
23
  import { sessionHeadline } from '../lib/session/title.js';
23
24
  import { stripRoutingFlags } from '../lib/hosts/remote-cmd.js';
@@ -241,11 +242,33 @@ export async function sessionsResumeAction(query, prompt, options) {
241
242
  process.exitCode = 1;
242
243
  return;
243
244
  }
244
- const items = resumable.map((session) => buildSelectedResumeSurface(session, prompt, options));
245
+ let items = resumable.map((session) => buildSelectedResumeSurface(session, prompt, options));
245
246
  const ctx = currentContext();
246
247
  const backend = await resolveBackend(options, ctx, items.length);
247
248
  if (backend === 'cancel')
248
249
  return;
250
+ if (backend === 'vscodium-agent' && !options.device) {
251
+ const pending = [];
252
+ for (const it of items) {
253
+ if (!it.project && it.session.project) {
254
+ const { editorFolderNamed, storageJsonFor, vscodiumAgentBackend } = await import('../lib/terminal/backends/vscodium-agent.js');
255
+ const folder = editorFolderNamed(it.session.project, storageJsonFor(vscodiumAgentBackend.variant));
256
+ if (folder)
257
+ Object.assign(it, { project: folder, cwd: fs.existsSync(it.cwd) && it.cwd !== process.cwd() ? it.cwd : folder });
258
+ }
259
+ if (!it.project) {
260
+ console.error(chalk.red(`Can't open ${sessionLabel(it.session)}: no local folder matches ${it.session.cwd ?? `project "${it.session.project ?? 'unknown'}"`}, so there is no VSCodium window to put it in.`));
261
+ console.error(chalk.gray(` Resume it in this terminal instead: agents sessions resume ${it.session.id}`));
262
+ process.exitCode = 1;
263
+ continue;
264
+ }
265
+ await reportLiveProcesses(it.session);
266
+ pending.push(it);
267
+ }
268
+ items = pending;
269
+ if (items.length === 0)
270
+ return;
271
+ }
249
272
  if (items.length > CONFIRM_THRESHOLD) {
250
273
  const proceed = await confirm({
251
274
  message: `Open ${items.length} live sessions at once?`,
@@ -263,33 +286,32 @@ export async function sessionsResumeAction(query, prompt, options) {
263
286
  return;
264
287
  }
265
288
  const packing = resolveResumePacking(options);
266
- const where = options.device ? `${backend} on ${options.device}` : backend;
267
289
  if (backend === 'terminal' && packing === 'two-per-tab') {
268
290
  console.log(chalk.yellow('Terminal.app cannot split panes — opening one tab per session instead.'));
269
291
  }
270
- console.log(chalk.gray(`Opening ${items.length} session${items.length === 1 ? '' : 's'} in ${where} (${packing})…`));
271
292
  const results = await openSurfaces(items.map((it) => ({
272
293
  cwd: it.cwd,
273
294
  command: it.command,
274
295
  agent: it.session.agent || undefined,
275
296
  sessionId: it.session.id || undefined,
276
297
  title: sessionHeadline(it.session),
298
+ project: it.project,
277
299
  })), { backend, host: options.device, packing });
278
- let opened = 0;
279
300
  results.forEach((r, i) => {
280
301
  const s = items[i].session;
302
+ const line = describeLaunch(r, { verb: 'Resumed', label: sessionLabel(s) });
281
303
  if (r.ok) {
282
- opened++;
283
- const shape = r.request.layout === 'tab' ? 'tab' : 'split';
284
- console.log(chalk.green(` opened ${s.shortId}`) + chalk.gray(` — ${shape} — ${items[i].command.join(' ')}`));
285
- }
286
- else {
287
- console.log(chalk.red(` failed ${s.shortId} — ${r.error}`));
304
+ console.log(line);
305
+ return;
288
306
  }
289
- });
290
- console.log(chalk.gray(`\nOpened ${opened}/${items.length} in ${where}.`));
291
- if (opened !== items.length)
307
+ console.error(chalk.red(line));
308
+ console.error(chalk.gray(` Resume it in this terminal instead: agents sessions resume ${s.id}`));
292
309
  process.exitCode = 1;
310
+ });
311
+ }
312
+ function sessionLabel(s) {
313
+ const headline = sessionHeadline(s);
314
+ return `${s.shortId}${headline ? ` "${headline}"` : ''}${s.machine ? ` (${s.machine})` : ''}`;
293
315
  }
294
316
  const RUN_RESUME_PICKER_SPECS = [
295
317
  { long: 'all', takesValue: false },
@@ -407,15 +429,40 @@ export function buildSelectedResumeSurface(session, prompt, options) {
407
429
  if (options.device && !requestedCwd) {
408
430
  throw new Error(`Cannot open ${session.shortId} on ${options.device} without a recorded working directory. Pass --cwd <path>.`);
409
431
  }
432
+ const project = options.device ? undefined : localProjectFolder(requestedCwd);
410
433
  const cwd = options.device
411
434
  ? requestedCwd
412
- : requestedCwd && fs.existsSync(requestedCwd) ? requestedCwd : process.cwd();
435
+ : requestedCwd && fs.existsSync(requestedCwd) ? requestedCwd : project ?? process.cwd();
413
436
  return {
414
437
  session,
415
438
  cwd,
416
- command: ['agents', ...buildSelectedResumeArgs(session.id, prompt, options)].map(shellQuote),
439
+ project,
440
+ command: ['agents', ...inTabArgs(buildSelectedResumeArgs(session.id, prompt, options), options)].map(shellQuote),
417
441
  };
418
442
  }
443
+ async function reportLiveProcesses(session) {
444
+ const self = machineId();
445
+ const host = session.machine && session.machine !== self ? session.machine : undefined;
446
+ let pids;
447
+ if (!host) {
448
+ pids = liveSessionProcesses(session.id).map((p) => p.pid);
449
+ }
450
+ else {
451
+ const { gatherRemoteActive } = await import('../lib/session/remote-active.js');
452
+ const remote = await gatherRemoteActive([host], { quiet: true }).catch(() => undefined);
453
+ pids = (remote?.sessions ?? [])
454
+ .filter((a) => a.sessionId === session.id && a.pidAlive !== false && typeof a.pid === 'number')
455
+ .map((a) => a.pid);
456
+ }
457
+ for (const pid of pids)
458
+ process.stdout.write(chalk.yellow(stillRunningNotice(session.shortId, pid, host ?? self)));
459
+ }
460
+ function inTabArgs(args, options) {
461
+ if (options.attachOnly || args.includes('--quiet'))
462
+ return args;
463
+ const boundary = args.indexOf('--');
464
+ return boundary < 0 ? [...args, '--quiet'] : [...args.slice(0, boundary), '--quiet', ...args.slice(boundary)];
465
+ }
419
466
  export function resumeHostMismatch(session, requestedHost, self = machineId()) {
420
467
  const origin = sessionOriginDevice(session, self);
421
468
  return sessionRecoveryDestinationMatches(session, requestedHost, self)
@@ -14,8 +14,9 @@ export async function openSetupTerminal(tool, terminal, installOnly = false) {
14
14
  cwd: os.homedir(),
15
15
  sessions,
16
16
  ctx: currentContext(),
17
+ label: `agents setup ${tool}`,
17
18
  });
18
19
  if (!result.ok)
19
- throw new Error(result.error ?? 'Could not open a terminal for setup.');
20
- console.log(result.description ?? 'Setup opened in a terminal.');
20
+ throw new Error(result.description ?? result.error ?? 'Could not open a terminal for setup.');
21
+ console.log(result.description);
21
22
  }
package/dist/lib/exec.js CHANGED
@@ -3,7 +3,8 @@ import { spawn } from 'child_process';
3
3
  import { randomUUID } from 'crypto';
4
4
  import * as fs from 'fs';
5
5
  import * as path from 'path';
6
- import { ALL_MODES, REMOTE_INTERACTIVE_ENV } from './types.js';
6
+ import { ALL_MODES, PEER_HOP_ENV, REMOTE_INTERACTIVE_ENV } from './types.js';
7
+ import { LAUNCH_LOG_ENV, markAgentStarted } from './launch-log.js';
7
8
  import { AGENTS, agentConfigDirName, findInPath } from './agents.js';
8
9
  import { parseTimeout } from './scheduling/routines.js';
9
10
  import { compareVersions, getBinaryPath, getVersionHomePath, isVersionInstalled, listInstalledVersions, resolveVersion } from './installations/versions.js';
@@ -246,6 +247,8 @@ export function buildExecEnv(options) {
246
247
  delete result.AGENTS_SESSION_ID;
247
248
  delete result.AGENTS_MAILBOX_DIR;
248
249
  delete result.AGENT_TERMINAL_ID;
250
+ delete result[PEER_HOP_ENV];
251
+ delete result[LAUNCH_LOG_ENV];
249
252
  const launchIdentity = launchIdentityEnv();
250
253
  Object.assign(result, launchIdentity);
251
254
  if (options.sessionId && isValidMailboxId(options.sessionId)) {
@@ -727,6 +730,7 @@ async function execShimPassthroughLeased(agent, rawArgs, cwd, pinnedVersion) {
727
730
  await emitRunLaunch({ agent, version, resolvedVia: 'shim' });
728
731
  return new Promise((resolve) => {
729
732
  const child = spawn(command, args, { cwd, stdio: 'inherit', env, shell });
733
+ markAgentStarted();
730
734
  if (child.pid) {
731
735
  const passthroughSessionId = extractSessionIdArg(rawArgs);
732
736
  writePidSessionEntry({
@@ -1247,6 +1251,7 @@ async function spawnAgentLeased(options) {
1247
1251
  env: buildExecEnv(options),
1248
1252
  shell: useShell,
1249
1253
  });
1254
+ markAgentStarted();
1250
1255
  writePidSessionEntry({
1251
1256
  pid: child.pid ?? 0,
1252
1257
  agent: options.agent,
@@ -67,11 +67,12 @@ interface ReconnectTargetInputs {
67
67
  }
68
68
  export declare function pickReconnectTarget(inputs: ReconnectTargetInputs): ReconnectTarget | undefined;
69
69
  export declare function reattachRemoteCommand(target: ReconnectTarget): string;
70
+ export declare function reattachRemoteSession(host: Host, target: ReconnectTarget): ReconnectOutcome;
70
71
  interface ReconnectLoopOpts {
71
- host: Host;
72
+ hostName: string;
72
73
  target: ReconnectTarget;
73
74
  initialExit: number;
74
- reattach?: (host: Host, target: ReconnectTarget) => ReconnectOutcome;
75
+ reattach: () => ReconnectOutcome;
75
76
  wait?: (ms: number) => Promise<'elapsed' | 'interrupted'>;
76
77
  write?: (s: string) => void;
77
78
  }
@@ -117,7 +117,7 @@ export function reattachRemoteCommand(target) {
117
117
  .join(' ');
118
118
  return wrapRemoteExitCode(inner);
119
119
  }
120
- function reattachRemoteSession(host, target) {
120
+ export function reattachRemoteSession(host, target) {
121
121
  const sshTarget = sshTargetFor(host);
122
122
  const extraSshArgs = hostIdentityArgs(host);
123
123
  const probe = sshExec(sshTarget, 'true', { multiplex: false, extraSshArgs });
@@ -146,7 +146,6 @@ async function waitOrInterrupt(ms) {
146
146
  export async function reconnectInteractiveSession(opts) {
147
147
  const write = opts.write ?? ((s) => process.stderr.write(s));
148
148
  const wait = opts.wait ?? waitOrInterrupt;
149
- const reattach = opts.reattach ?? reattachRemoteSession;
150
149
  let state = initialReconnectState();
151
150
  let outcome = { code: opts.initialExit, connected: true, heldMs: 0 };
152
151
  for (;;) {
@@ -154,23 +153,23 @@ export async function reconnectInteractiveSession(opts) {
154
153
  if (decision.action === 'stop') {
155
154
  if (decision.code === SSH_CONN_FAILURE) {
156
155
  write(outcome.connected
157
- ? unstableNotice(opts.target, opts.host.name)
158
- : exhaustedNotice(opts.target, opts.host.name));
156
+ ? unstableNotice(opts.target, opts.hostName)
157
+ : exhaustedNotice(opts.target, opts.hostName));
159
158
  }
160
159
  else if (decision.code === REMOTE_EXIT_255_REMAPPED) {
161
- write(remoteExitNotice(opts.target, opts.host.name));
160
+ write(remoteExitNotice(opts.target, opts.hostName));
162
161
  }
163
162
  else {
164
- write(connectionEndedNotice(opts.target, opts.host.name));
163
+ write(connectionEndedNotice(opts.target, opts.hostName));
165
164
  }
166
165
  return decision.code;
167
166
  }
168
- write(reconnectNotice(opts.target, opts.host.name, decision.state.attempt, decision.waitMs, decision.remainingMs));
167
+ write(reconnectNotice(opts.target, opts.hostName, decision.state.attempt, decision.waitMs, decision.remainingMs));
169
168
  if (await wait(decision.waitMs) === 'interrupted') {
170
- write(interruptedNotice(opts.target, opts.host.name));
169
+ write(interruptedNotice(opts.target, opts.hostName));
171
170
  return 130;
172
171
  }
173
172
  state = decision.state;
174
- outcome = reattach(opts.host, opts.target);
173
+ outcome = opts.reattach();
175
174
  }
176
175
  }
@@ -0,0 +1,15 @@
1
+ export declare const LAUNCH_LOG_ENV = "AGENTS_LAUNCH_LOG";
2
+ export interface LaunchFailure {
3
+ status: 'failed';
4
+ cause: string;
5
+ log: string;
6
+ exitCode: number;
7
+ at: string;
8
+ }
9
+ export declare function launchesDir(): string;
10
+ export declare function launchFailurePath(sessionId: string): string;
11
+ export declare function launchSessionId(argv: string[]): string | undefined;
12
+ export declare function launchesAgent(argv: string[]): boolean;
13
+ export declare function markAgentStarted(env?: NodeJS.ProcessEnv): void;
14
+ export declare function failureCause(log: string): string;
15
+ export declare function startQuietLaunch(argv: string[], env?: NodeJS.ProcessEnv): string;