@phnx-labs/agents-cli 1.22.107 → 1.22.109

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 (38) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/commands/daemon.js +45 -40
  3. package/dist/commands/doctor.js +7 -0
  4. package/dist/commands/exec.js +4 -2
  5. package/dist/commands/monitors.js +15 -2
  6. package/dist/commands/routines.js +46 -6
  7. package/dist/commands/sessions-backup-setup.d.ts +12 -0
  8. package/dist/commands/sessions-backup-setup.js +65 -0
  9. package/dist/commands/sessions-resume.d.ts +14 -1
  10. package/dist/commands/sessions-resume.js +56 -9
  11. package/dist/commands/sessions.js +2 -0
  12. package/dist/commands/share.js +15 -2
  13. package/dist/commands/sync.js +30 -1
  14. package/dist/lib/accounts/slots.js +7 -0
  15. package/dist/lib/agent-spec/agents.d.ts +60 -8
  16. package/dist/lib/agent-spec/agents.js +118 -45
  17. package/dist/lib/daemon/daemon.d.ts +34 -1
  18. package/dist/lib/daemon/daemon.js +63 -9
  19. package/dist/lib/daemon/leaked-daemons.d.ts +60 -0
  20. package/dist/lib/daemon/leaked-daemons.js +180 -0
  21. package/dist/lib/devices/doctor-findings.d.ts +7 -1
  22. package/dist/lib/devices/doctor-findings.js +32 -1
  23. package/dist/lib/hooks/install.js +70 -63
  24. package/dist/lib/models.js +76 -5
  25. package/dist/lib/session/cloud.js +3 -1
  26. package/dist/lib/session/parse.d.ts +1 -0
  27. package/dist/lib/session/parse.js +136 -2
  28. package/dist/lib/session/recovery.d.ts +9 -1
  29. package/dist/lib/session/recovery.js +14 -4
  30. package/dist/lib/session/tool-calls.d.ts +1 -1
  31. package/dist/lib/session/tool-calls.js +40 -5
  32. package/dist/lib/share/backend.d.ts +23 -0
  33. package/dist/lib/share/backend.js +24 -0
  34. package/dist/lib/share/provision.d.ts +12 -0
  35. package/dist/lib/share/provision.js +30 -0
  36. package/dist/lib/share/worker-template.js +273 -0
  37. package/dist/lib/terminal/engine.js +13 -1
  38. package/package.json +1 -1
@@ -10,13 +10,13 @@ import { formatBytes } from '../lib/format.js';
10
10
  import { Argument, Option } from 'commander';
11
11
  import chalk from 'chalk';
12
12
  import { DEFAULT_BUCKET_NAME, DEFAULT_CF_BUNDLE, DEFAULT_SHARE_DOMAIN, DEFAULT_WORKER_NAME, generateWriteToken, readCloudflareCreds, readShareConfig, readWriteToken, readWriteTokenEnv, readWriteTokenFromBundle, storeWriteToken, writeShareConfig, } from '../lib/share/config.js';
13
- import { addCustomDomain, configureBucketLifecycle, createBucket, deployWorker, enableWorkersDev, findZoneId, hashWorkerScript, putWorkerSecret, updateWorker, WORKER_PHOENIX_ID_BASE_SECRET, setWorkerSecret, } from '../lib/share/provision.js';
13
+ import { addCustomDomain, configureBucketLifecycle, createBucket, deployWorker, enableWorkersDev, findZoneId, hashWorkerScript, putWorkerSecret, updateWorker, WORKER_PHOENIX_ID_BASE_SECRET, WORKER_COLLAB_BASE_SECRET, WORKER_COLLAB_SERVICE_TOKEN_SECRET, setWorkerSecret, } from '../lib/share/provision.js';
14
14
  import { publishFile, resolveShareUsername, parseMetaEntries, sanitizeLabel, scanShareContent, formatSensitiveContentError, unlistedNotPrivateWarning, SHARE_VISIBILITY_LEVELS, PUBLISH_VISIBILITY_LEVELS, } from '../lib/share/publish.js';
15
15
  import { deleteShare, resolveDeleteTarget } from '../lib/share/delete.js';
16
16
  import { renderWorkerBundle } from '../lib/share/worker-template.js';
17
17
  import { analyticsEnabled } from '../lib/share/analytics.js';
18
18
  import { extractShareHttpError, formatShareHttpErrorDetail } from '../lib/share/http-error.js';
19
- import { phoenixIdBaseForDeploy, resolveShareBackend, shouldUseManaged, } from '../lib/share/backend.js';
19
+ import { collabConfigForDeploy, phoenixIdBaseForDeploy, resolveShareBackend, shouldUseManaged, } from '../lib/share/backend.js';
20
20
  import { publishVisibility } from '../lib/storage/visibility.js';
21
21
  import { resolveGitHubUsername } from '../lib/git.js';
22
22
  import { refreshSessionAvatar } from '../lib/identity/index.js';
@@ -1271,6 +1271,15 @@ export async function runShareProvision(opts) {
1271
1271
  await putWorkerSecret(apiToken, accountId, workerName, WORKER_PHOENIX_ID_BASE_SECRET, phoenixIdBase, provisionOpts);
1272
1272
  spin.text = `Worker '${workerName}' Phoenix ID base set`;
1273
1273
  }
1274
+ // Managed collaboration backend (PHNX-3835). Dormant unless BOTH
1275
+ // PRIX_ARTIFACT_COLLAB_BASE and ARTIFACT_COLLAB_SERVICE_TOKEN are set in the
1276
+ // deploy env; the service token rides the Secrets API, never rendered HTML.
1277
+ const collab = collabConfigForDeploy({ managed: opts.managed }, { baseUrl, domain });
1278
+ if (collab.collabBase && collab.collabServiceToken) {
1279
+ await putWorkerSecret(apiToken, accountId, workerName, WORKER_COLLAB_BASE_SECRET, collab.collabBase, provisionOpts);
1280
+ await putWorkerSecret(apiToken, accountId, workerName, WORKER_COLLAB_SERVICE_TOKEN_SECRET, collab.collabServiceToken, provisionOpts);
1281
+ spin.text = `Worker '${workerName}' collaboration backend set`;
1282
+ }
1274
1283
  spin.succeed('Provisioned');
1275
1284
  const cfg = {
1276
1285
  baseUrl,
@@ -1336,10 +1345,14 @@ export async function runShareUpdate(opts = {}) {
1336
1345
  }
1337
1346
  const writeToken = readWriteToken();
1338
1347
  const phoenixIdBase = phoenixIdBaseForDeploy({ managed: opts.managed }, cfg);
1348
+ const collab = collabConfigForDeploy({ managed: opts.managed }, cfg);
1339
1349
  const provisionOpts = {
1340
1350
  ...(opts.request ? { request: opts.request } : {}),
1341
1351
  force: opts.force,
1342
1352
  ...(phoenixIdBase !== undefined ? { phoenixIdBase } : {}),
1353
+ ...(collab.collabBase !== undefined
1354
+ ? { collabBase: collab.collabBase, collabServiceToken: collab.collabServiceToken }
1355
+ : {}),
1343
1356
  };
1344
1357
  const result = await updateWorker(apiToken, accountId, cfg.workerName, cfg.bucketName, worker, writeToken, cfg.templateHash, provisionOpts);
1345
1358
  if (!result.skipped) {
@@ -190,7 +190,7 @@ export function registerSyncCommand(program) {
190
190
  .option('-y, --yes', 'Skip the interactive preview and auto-sync all detected resources', false)
191
191
  .option('--force', 'Re-sync even if no changes are detected since the last sync', false)
192
192
  .option('--quiet', 'Suppress all output (exit code indicates success)', false)
193
- .option('--dry-run', 'Show what would be synced without making any changes', false)
193
+ .option('--dry-run', 'Show what would be synced without making any changes — requires an agent scope (e.g. agents sync claude --dry-run); the umbrella verb refuses it', false)
194
194
  .option('--allow-exec-surfaces', 'Allow syncing plugin exec surfaces (scripts, binaries) — off by default for safety', false)
195
195
  .option('--json', 'Emit machine-readable JSON (also accepted so fleet fan-out via --device all can parse each peer)', false)
196
196
  // Umbrella verb (no agent given): make this machine current.
@@ -480,6 +480,35 @@ function evictCentralBrowserProfilesForSync(quiet, json, outLog, errLog) {
480
480
  * a one-line summary. Stage failures are non-fatal and surfaced as warnings.
481
481
  */
482
482
  async function runUmbrella(opts, quiet, outLog, errLog, json = false) {
483
+ // `--dry-run` on the umbrella verb is NOT supported and must fail LOUD before
484
+ // touching anything (PHNX-3923). The umbrella composes stages that only exist
485
+ // as mutating operations — repo `git pull`, a full `refresh()` reconcile into
486
+ // every installed version home, central browser-profile eviction, device sync,
487
+ // and `repairAfterSync` — none of which carry a non-mutating preview mode. The
488
+ // old code ignored `opts.dryRun` entirely, ran `runUmbrellaSync` + evict +
489
+ // repair, and so MUTATED every native home despite `--dry-run`. Rather than
490
+ // ship a partial preview that silently skips the stages it cannot model (a
491
+ // lying "would sync" that contradicts the flag's promise), refuse here and
492
+ // point at the scoped path, which DOES honor `--dry-run` non-destructively.
493
+ if (opts.dryRun) {
494
+ const installed = MANAGED_AGENT_IDS.filter((id) => listInstalledVersions(id).length > 0);
495
+ const example = installed[0] ?? 'claude';
496
+ const error = '`agents sync --dry-run` has no umbrella preview: the machine-wide sync pulls repos, ' +
497
+ 'reconciles every installed version, syncs devices, and repairs homes — stages that ' +
498
+ 'cannot be previewed without making changes.';
499
+ const hint = `Preview one agent instead (this is non-destructive): agents sync ${example} --dry-run [--repo <repo>]`;
500
+ if (json) {
501
+ emitJson({ ok: false, mode: 'umbrella', dryRun: true, error, hint, installedAgents: installed });
502
+ }
503
+ else {
504
+ errLog(chalk.red(error));
505
+ errLog(chalk.gray(hint));
506
+ if (installed.length > 0)
507
+ errLog(chalk.gray(`Installed agents: ${installed.join(', ')}`));
508
+ }
509
+ process.exitCode = 1;
510
+ return;
511
+ }
483
512
  // Interactive bare `agents sync` (a TTY, no --yes, no scope flag) drops into
484
513
  // the two-checklist picker: which repos to sync from, which agents to sync
485
514
  // into. Any explicit flag, --yes, or --json keeps the non-interactive path.
@@ -15,6 +15,7 @@ import * as fs from 'node:fs';
15
15
  import * as path from 'node:path';
16
16
  import { agentConfigDirName } from '../agents.js';
17
17
  import { harnessAuth, harnessWorkerIsPerDevice } from '../harness-auth-capabilities.js';
18
+ import { installSessionTrackerHookSync } from '../hooks/install.js';
18
19
  import { getGlobalDefault, getVersionHomePath, listInstalledVersions } from '../installations/store.js';
19
20
  import { carryForwardSettings } from '../settings-manifest.js';
20
21
  import { getHistoryDir, readMeta, updateMeta } from '../state.js';
@@ -71,6 +72,12 @@ function projectResources(harness, version, destHome, fromHome) {
71
72
  continue;
72
73
  writer.write({ version, versionHome: destHome, selection: names, cwd });
73
74
  }
75
+ if (supports(harness, 'hooks', version).ok) {
76
+ const tracker = installSessionTrackerHookSync(harness, version, destHome);
77
+ if (!tracker.installed && tracker.error) {
78
+ console.warn(`agents: SessionStart hook not installed for ${harness} account home ${destHome}: ${tracker.error}`);
79
+ }
80
+ }
74
81
  }
75
82
  /**
76
83
  * Remove slot artifacts whose source name is gone. Only the name-keyed kinds
@@ -355,25 +355,77 @@ export declare function antigravityOsKeyringProbe(platform?: NodeJS.Platform): {
355
355
  } | null;
356
356
  /** @internal test hook — clear the per-process keyring probe cache. */
357
357
  export declare function __resetAntigravityKeychainCacheForTest(): void;
358
+ /** The XDG base dirs OpenCode reads, and the env var that overrides each. */
359
+ declare const OPENCODE_XDG_DIRS: {
360
+ readonly data: {
361
+ readonly env: "XDG_DATA_HOME";
362
+ readonly fallback: readonly [".local", "share"];
363
+ };
364
+ readonly state: {
365
+ readonly env: "XDG_STATE_HOME";
366
+ readonly fallback: readonly [".local", "state"];
367
+ };
368
+ };
369
+ /**
370
+ * Resolve one of OpenCode's (sst/opencode) XDG-rooted files.
371
+ *
372
+ * OpenCode keeps provider credentials under `$XDG_DATA_HOME/opencode/` and TUI
373
+ * state under `$XDG_STATE_HOME/opencode/`, defaulting to `~/.local/share` and
374
+ * `~/.local/state` on EVERY platform — its `xdg-basedir` dependency does not
375
+ * special-case macOS, so there is no `~/Library/Application Support` variant.
376
+ * Both roots are account-global (not per-version), matching how
377
+ * `session/discover.ts` already resolves `~/.local/share/opencode/opencode.db`.
378
+ *
379
+ * Resolution order, first existing wins:
380
+ * 1. `<base>/<fallback>/opencode/<file>` — the passed per-version home. This is
381
+ * primarily a test hook (suites write a hermetic file under a temp home)
382
+ * but also covers any relocated install.
383
+ * 2. `$XDG_<KIND>_HOME/opencode/<file>` — an explicit XDG override, exactly
384
+ * what OpenCode itself honours.
385
+ * 3. `<realHome>/<fallback>/opencode/<file>` — the active default, under
386
+ * `AGENTS_REAL_HOME` or `os.homedir()`, so every installed version reflects
387
+ * the one account-global state (same fallback shape as
388
+ * resolveAccountCredentialPath).
389
+ * Returns the first existing path, or null. Never throws.
390
+ */
391
+ export declare function resolveOpenCodeXdgPath(base: string, kind: keyof typeof OPENCODE_XDG_DIRS, file: string): string | null;
392
+ /** OpenCode's signed-in identity, as far as `auth.json` can describe it. */
393
+ export interface OpenCodeIdentity {
394
+ /** Sorted, "+"-joined provider ids holding a valid credential. */
395
+ providers: string;
396
+ /** Account email, when some OAuth credential's token carries the claim. */
397
+ email: string | null;
398
+ /** Plan tier from the same token (e.g. `Pro`), when present. */
399
+ plan: string | null;
400
+ }
358
401
  /**
359
- * OpenCode's account identity: the sorted, "+"-joined list of provider ids
360
- * that hold a valid credential in `auth.json` (e.g. `"anthropic+muse-spark"`).
361
- * `auth.json` carries no email/identity claim (see `isValidOpenCodeCredential`),
362
- * so this join is the closest thing to "which account is this" available — the
363
- * same value `agents view`/`agents doctor` show for OpenCode's signed-in state.
402
+ * OpenCode's account identity, read from `auth.json`.
403
+ *
404
+ * The provider join (`"meta+openai+opencode-go"`) is the stable key: OpenCode is
405
+ * a multi-provider harness, so "which providers are configured" is what actually
406
+ * identifies an install, and `session/discover.ts` indexes sessions by it.
407
+ * Providers that sign in over OAuth additionally hand OpenCode a token with real
408
+ * identity claims, so the email and plan are surfaced alongside it instead of
409
+ * leaving `agents view` showing a bare `id:` key for a login that knows exactly
410
+ * whose it is. Providers are walked in sorted order so a multi-OAuth install
411
+ * resolves to the same email on every machine.
364
412
  *
365
413
  * This is the ONLY correct source for an OpenCode "account". OpenCode's SQLite
366
414
  * `opencode.db` also carries `account`/`account_state`/`control_account` tables,
367
415
  * but on a real, actively-used install (yosemite-s1, 1.16.0, 35 applied
368
416
  * migrations) all three are permanently empty — no migration ever populates
369
417
  * them, and no session has ever written a row. Reading from them instead of
370
- * `auth.json` always yields `undefined`, credential or not; `session/discover.ts`
371
- * uses this function rather than duplicating a sqlite lookup against those
372
- * dead tables.
418
+ * `auth.json` always yields `undefined`, credential or not.
373
419
  *
374
420
  * Sync (`fs.readFileSync`), no network. Returns undefined when `auth.json` is
375
421
  * missing, unreadable, or carries no valid credential.
376
422
  */
423
+ export declare function resolveOpenCodeIdentity(base: string): OpenCodeIdentity | undefined;
424
+ /**
425
+ * The provider join alone — the value `session/discover.ts` indexes sessions by,
426
+ * kept as its own entry point so callers that only need the key do not have to
427
+ * know about the OAuth claim walk.
428
+ */
377
429
  export declare function resolveOpenCodeAccountId(base: string): string | undefined;
378
430
  /**
379
431
  * Whether a Claude version home's credential file is present but carries no
@@ -1692,34 +1692,41 @@ async function antigravityKeychainSignedIn() {
1692
1692
  }
1693
1693
  return cachedAgyKeychainSignedIn;
1694
1694
  }
1695
+ /** The XDG base dirs OpenCode reads, and the env var that overrides each. */
1696
+ const OPENCODE_XDG_DIRS = {
1697
+ data: { env: 'XDG_DATA_HOME', fallback: ['.local', 'share'] },
1698
+ state: { env: 'XDG_STATE_HOME', fallback: ['.local', 'state'] },
1699
+ };
1695
1700
  /**
1696
- * OpenCode (sst/opencode) stores provider credentials in a single JSON file at
1697
- * `$XDG_DATA_HOME/opencode/auth.json`, defaulting to
1698
- * `~/.local/share/opencode/auth.json` on EVERY platform — its `xdg-basedir`
1699
- * dependency does not special-case macOS, so there is no
1700
- * `~/Library/Application Support` variant. The path is account-global (not
1701
- * per-version), matching how `session/discover.ts` already resolves
1702
- * `~/.local/share/opencode/opencode.db`.
1701
+ * Resolve one of OpenCode's (sst/opencode) XDG-rooted files.
1702
+ *
1703
+ * OpenCode keeps provider credentials under `$XDG_DATA_HOME/opencode/` and TUI
1704
+ * state under `$XDG_STATE_HOME/opencode/`, defaulting to `~/.local/share` and
1705
+ * `~/.local/state` on EVERY platform — its `xdg-basedir` dependency does not
1706
+ * special-case macOS, so there is no `~/Library/Application Support` variant.
1707
+ * Both roots are account-global (not per-version), matching how
1708
+ * `session/discover.ts` already resolves `~/.local/share/opencode/opencode.db`.
1703
1709
  *
1704
1710
  * Resolution order, first existing wins:
1705
- * 1. `<base>/.local/share/opencode/auth.json` — the passed per-version home.
1706
- * This is primarily a test hook (suites write a hermetic auth file under a
1707
- * temp home) but also covers any relocated install.
1708
- * 2. `$XDG_DATA_HOME/opencode/auth.json` — an explicit XDG override, exactly
1711
+ * 1. `<base>/<fallback>/opencode/<file>` — the passed per-version home. This is
1712
+ * primarily a test hook (suites write a hermetic file under a temp home)
1713
+ * but also covers any relocated install.
1714
+ * 2. `$XDG_<KIND>_HOME/opencode/<file>` — an explicit XDG override, exactly
1709
1715
  * what OpenCode itself honours.
1710
- * 3. `<realHome>/.local/share/opencode/auth.json` — the active default, under
1716
+ * 3. `<realHome>/<fallback>/opencode/<file>` — the active default, under
1711
1717
  * `AGENTS_REAL_HOME` or `os.homedir()`, so every installed version reflects
1712
- * the one account-global login (same fallback shape as
1718
+ * the one account-global state (same fallback shape as
1713
1719
  * resolveAccountCredentialPath).
1714
1720
  * Returns the first existing path, or null. Never throws.
1715
1721
  */
1716
- function resolveOpenCodeAuthPath(base) {
1717
- const candidates = [path.join(base, '.local', 'share', 'opencode', 'auth.json')];
1718
- const xdgData = process.env.XDG_DATA_HOME;
1719
- if (xdgData)
1720
- candidates.push(path.join(xdgData, 'opencode', 'auth.json'));
1722
+ export function resolveOpenCodeXdgPath(base, kind, file) {
1723
+ const { env, fallback } = OPENCODE_XDG_DIRS[kind];
1724
+ const candidates = [path.join(base, ...fallback, 'opencode', file)];
1725
+ const override = process.env[env];
1726
+ if (override)
1727
+ candidates.push(path.join(override, 'opencode', file));
1721
1728
  const realHome = process.env.AGENTS_REAL_HOME || os.homedir();
1722
- candidates.push(path.join(realHome, '.local', 'share', 'opencode', 'auth.json'));
1729
+ candidates.push(path.join(realHome, ...fallback, 'opencode', file));
1723
1730
  for (const candidate of candidates) {
1724
1731
  try {
1725
1732
  if (fs.existsSync(candidate))
@@ -1729,6 +1736,9 @@ function resolveOpenCodeAuthPath(base) {
1729
1736
  }
1730
1737
  return null;
1731
1738
  }
1739
+ function resolveOpenCodeAuthPath(base) {
1740
+ return resolveOpenCodeXdgPath(base, 'data', 'auth.json');
1741
+ }
1732
1742
  /**
1733
1743
  * Validate one OpenCode auth.json entry against its discriminated union
1734
1744
  * (`type: 'oauth' | 'api' | 'wellknown'`) and confirm the credential actually
@@ -1751,25 +1761,58 @@ function isValidOpenCodeCredential(value) {
1751
1761
  }
1752
1762
  }
1753
1763
  /**
1754
- * OpenCode's account identity: the sorted, "+"-joined list of provider ids
1755
- * that hold a valid credential in `auth.json` (e.g. `"anthropic+muse-spark"`).
1756
- * `auth.json` carries no email/identity claim (see `isValidOpenCodeCredential`),
1757
- * so this join is the closest thing to "which account is this" available — the
1758
- * same value `agents view`/`agents doctor` show for OpenCode's signed-in state.
1764
+ * The human identity an OpenCode `type: 'oauth'` credential carries in its
1765
+ * access token, when that token is a JWT. Provider-agnostic by shape: the
1766
+ * OpenAI-issued token OpenCode stores under its `openai` provider carries the
1767
+ * same namespaced claims Codex's own `auth.json` does (`…/profile.email`,
1768
+ * `…/auth.chatgpt_plan_type`), so the extraction is shared with `case 'codex'`
1769
+ * rather than reinvented. A plain `email` claim is accepted too, for providers
1770
+ * that issue an ordinary OIDC token.
1771
+ *
1772
+ * Only claims are read — the token itself is never returned or logged. A
1773
+ * non-JWT credential (Anthropic's `sk-ant-oat…` opaque token, any `type: 'api'`
1774
+ * key) simply yields nothing.
1775
+ */
1776
+ function openCodeOauthIdentity(cred) {
1777
+ const access = cred?.access;
1778
+ if (typeof access !== 'string' || access.length === 0)
1779
+ return { email: null, plan: null };
1780
+ const claims = decodeJwtPayload(access);
1781
+ if (!claims)
1782
+ return { email: null, plan: null };
1783
+ const profile = claims['https://api.openai.com/profile'] || {};
1784
+ const auth = claims['https://api.openai.com/auth'] || {};
1785
+ const rawEmail = profile.email ?? claims.email;
1786
+ const email = typeof rawEmail === 'string' && rawEmail.includes('@') ? rawEmail : null;
1787
+ const rawPlan = auth.chatgpt_plan_type;
1788
+ const plan = typeof rawPlan === 'string' && rawPlan
1789
+ ? rawPlan.charAt(0).toUpperCase() + rawPlan.slice(1)
1790
+ : null;
1791
+ return { email, plan };
1792
+ }
1793
+ /**
1794
+ * OpenCode's account identity, read from `auth.json`.
1795
+ *
1796
+ * The provider join (`"meta+openai+opencode-go"`) is the stable key: OpenCode is
1797
+ * a multi-provider harness, so "which providers are configured" is what actually
1798
+ * identifies an install, and `session/discover.ts` indexes sessions by it.
1799
+ * Providers that sign in over OAuth additionally hand OpenCode a token with real
1800
+ * identity claims, so the email and plan are surfaced alongside it instead of
1801
+ * leaving `agents view` showing a bare `id:` key for a login that knows exactly
1802
+ * whose it is. Providers are walked in sorted order so a multi-OAuth install
1803
+ * resolves to the same email on every machine.
1759
1804
  *
1760
1805
  * This is the ONLY correct source for an OpenCode "account". OpenCode's SQLite
1761
1806
  * `opencode.db` also carries `account`/`account_state`/`control_account` tables,
1762
1807
  * but on a real, actively-used install (yosemite-s1, 1.16.0, 35 applied
1763
1808
  * migrations) all three are permanently empty — no migration ever populates
1764
1809
  * them, and no session has ever written a row. Reading from them instead of
1765
- * `auth.json` always yields `undefined`, credential or not; `session/discover.ts`
1766
- * uses this function rather than duplicating a sqlite lookup against those
1767
- * dead tables.
1810
+ * `auth.json` always yields `undefined`, credential or not.
1768
1811
  *
1769
1812
  * Sync (`fs.readFileSync`), no network. Returns undefined when `auth.json` is
1770
1813
  * missing, unreadable, or carries no valid credential.
1771
1814
  */
1772
- export function resolveOpenCodeAccountId(base) {
1815
+ export function resolveOpenCodeIdentity(base) {
1773
1816
  const authPath = resolveOpenCodeAuthPath(base);
1774
1817
  if (!authPath)
1775
1818
  return undefined;
@@ -1777,16 +1820,34 @@ export function resolveOpenCodeAccountId(base) {
1777
1820
  const data = JSON.parse(fs.readFileSync(authPath, 'utf-8'));
1778
1821
  if (!data || typeof data !== 'object')
1779
1822
  return undefined;
1780
- const providers = Object.entries(data)
1823
+ const valid = Object.entries(data)
1781
1824
  .filter(([, cred]) => isValidOpenCodeCredential(cred))
1782
- .map(([id]) => id)
1783
- .sort();
1784
- return providers.length ? providers.join('+') : undefined;
1825
+ .sort(([a], [b]) => a.localeCompare(b));
1826
+ if (valid.length === 0)
1827
+ return undefined;
1828
+ let email = null;
1829
+ let plan = null;
1830
+ for (const [, cred] of valid) {
1831
+ const claimed = openCodeOauthIdentity(cred);
1832
+ email ??= claimed.email;
1833
+ plan ??= claimed.plan;
1834
+ if (email && plan)
1835
+ break;
1836
+ }
1837
+ return { providers: valid.map(([id]) => id).join('+'), email, plan };
1785
1838
  }
1786
1839
  catch {
1787
1840
  return undefined;
1788
1841
  }
1789
1842
  }
1843
+ /**
1844
+ * The provider join alone — the value `session/discover.ts` indexes sessions by,
1845
+ * kept as its own entry point so callers that only need the key do not have to
1846
+ * know about the OAuth claim walk.
1847
+ */
1848
+ export function resolveOpenCodeAccountId(base) {
1849
+ return resolveOpenCodeIdentity(base)?.providers;
1850
+ }
1790
1851
  /**
1791
1852
  * Whether a Muse Code `~/.config/muse/auth.json` document holds any usable
1792
1853
  * access token. Live shape from `muse login` (device OAuth, Muse Code 0.1.0):
@@ -1972,6 +2033,11 @@ export async function getAccountInfo(agentId, home) {
1972
2033
  claude: path.join(base, '.claude.json'),
1973
2034
  codex: path.join(base, '.codex', 'auth.json'),
1974
2035
  gemini: path.join(base, '.gemini', 'google_accounts.json'),
2036
+ // OpenCode keeps every session in ONE sqlite file rather than a directory of
2037
+ // per-session transcripts, so the session-file walk resolveLastActive runs
2038
+ // for other agents finds nothing. Its mtime fallback is the right read here:
2039
+ // opencode.db is written on every turn, so it tracks real activity.
2040
+ opencode: resolveOpenCodeXdgPath(base, 'data', 'opencode.db') ?? undefined,
1975
2041
  };
1976
2042
  const lastActive = resolveLastActive(agentId, base, configFiles[agentId]);
1977
2043
  try {
@@ -2238,20 +2304,27 @@ export async function getAccountInfo(agentId, home) {
2238
2304
  }
2239
2305
  case 'opencode': {
2240
2306
  // OpenCode's auth.json is a record keyed by provider id ->
2241
- // { type: 'oauth'|'api'|'wellknown', ...secret fields }. There is no
2242
- // email/identity claim to surface, so — like antigravity/kimi — we
2243
- // report signed-in state plus the NON-SECRET provider metadata (which
2244
- // provider ids hold a valid credential) and never read the tokens/keys
2245
- // themselves. The user's complaint was the row read "not signed in"
2246
- // despite a live login; a valid provider entry now shows e.g.
2247
- // "id:muse-spark" so they can see exactly which provider is configured.
2248
- // resolveOpenCodeAccountId is the single source of truth for this join —
2249
- // session/discover.ts reuses it for the indexed `account` field.
2250
- const accountId = resolveOpenCodeAccountId(base);
2251
- if (!accountId)
2307
+ // { type: 'oauth'|'api'|'wellknown', ...secret fields }. The provider
2308
+ // join is the identity key (see resolveOpenCodeIdentity), and an OAuth
2309
+ // provider's token additionally carries the real account email and plan
2310
+ // — so the row shows who is signed in rather than only a bare `id:` key.
2311
+ // Secrets are never read out; only JWT claims are.
2312
+ const identity = resolveOpenCodeIdentity(base);
2313
+ if (!identity)
2252
2314
  return { ...empty, lastActive };
2253
- const accountKey = buildIdentityKey(agentId, [['providers', accountId]]);
2254
- return { ...empty, signedIn: true, accountId, accountKey, lastActive };
2315
+ // Keyed on providers, not email: OpenCode bills through whichever
2316
+ // provider credentials are configured, so two installs sharing one
2317
+ // email but different provider sets are genuinely different accounts.
2318
+ const accountKey = buildIdentityKey(agentId, [['providers', identity.providers]]);
2319
+ return {
2320
+ ...empty,
2321
+ signedIn: true,
2322
+ accountId: identity.providers,
2323
+ accountKey,
2324
+ email: identity.email,
2325
+ plan: identity.plan,
2326
+ lastActive,
2327
+ };
2255
2328
  }
2256
2329
  case 'muse': {
2257
2330
  // Muse Code authenticates with META_API_KEY (env, highest priority) or
@@ -11,6 +11,17 @@ import { getAgentsBinPath } from '../cli-entry.js';
11
11
  import type { ServiceHealth } from './service.js';
12
12
  /** Health for every service currently registered on the live supervisor, or `null` if the daemon isn't running in this process. */
13
13
  export declare function getServiceSupervisorHealth(): Record<string, ServiceHealth> | null;
14
+ /**
15
+ * The service-manager identifiers of the REAL install's daemon — never
16
+ * namespaced. A caller under a redirected HOME (a test/e2e harness) uses these
17
+ * to recognize the box's production daemon as owned, where
18
+ * `daemonSystemdUnitName()`/`daemonServiceLabel()` would name only its own
19
+ * sandbox job (W4, PHNX-3736).
20
+ */
21
+ export declare function productionDaemonServiceNames(): {
22
+ systemdUnit: string;
23
+ launchdLabel: string;
24
+ };
14
25
  /**
15
26
  * RUSH-2639 (residual): launchd/systemd route `unload`/`load`/`list` by the
16
27
  * service identifier ALONE, never by the plist/unit file's path. Baking the
@@ -96,7 +107,7 @@ export declare function singleShot(fn: () => Promise<void>): () => Promise<void>
96
107
  */
97
108
  export declare function getDaemonLogPath(): string;
98
109
  /** Read the stored daemon PID from disk. Returns null if not present or invalid. */
99
- export declare function readDaemonPid(): number | null;
110
+ export declare function readDaemonPid(daemonDir?: string): number | null;
100
111
  /** Write the daemon PID to the pid file. */
101
112
  export declare function writeDaemonPid(pid: number): void;
102
113
  /** Remove the daemon PID file. */
@@ -286,6 +297,28 @@ export declare function generateLaunchdPlist(agentsBin?: string): string;
286
297
  */
287
298
  export declare function generateSystemdUnit(agentsBin?: string): string;
288
299
  export { getAgentsBinPath };
300
+ /**
301
+ * Ask the service manager for the daemon's live PID. Used as a fallback when
302
+ * the daemon hasn't yet written its pid file but launchd/systemd already report
303
+ * it running — so a start never has to surface a null PID for a daemon that is
304
+ * in fact up. Returns null when the service isn't running or the query fails.
305
+ *
306
+ * `names` defaults to THIS process's (possibly sandbox-namespaced) job; a
307
+ * caller under a redirected HOME passes `productionDaemonServiceNames()` to
308
+ * ask after the real install's unit instead. Read-only either way.
309
+ */
310
+ export declare function readServiceManagerPid(platform?: NodeJS.Platform, names?: {
311
+ systemdUnit: string;
312
+ launchdLabel: string;
313
+ }): number | null;
314
+ /**
315
+ * Thrown when a daemon LAUNCH is attempted under a redirected HOME without the
316
+ * explicit test opt-in (W4, PHNX-3736). `bootstrap.ts` prints the message
317
+ * without a stack — this is user-actionable, not an engineering bug.
318
+ */
319
+ export declare class RedirectedHomeDaemonError extends Error {
320
+ name: string;
321
+ }
289
322
  /** Start the daemon via launchd, systemd, or as a detached process. */
290
323
  export declare function startDaemon(agentsBin?: string): {
291
324
  pid: number | null;
@@ -77,6 +77,16 @@ const LOG_MAX_SIZE = 5 * 1024 * 1024; // 5 MB
77
77
  const LOG_ROTATE_COUNT = 3;
78
78
  const PLIST_NAME = 'com.phnx-labs.agents-daemon';
79
79
  const SYSTEMD_UNIT = 'agents-daemon.service';
80
+ /**
81
+ * The service-manager identifiers of the REAL install's daemon — never
82
+ * namespaced. A caller under a redirected HOME (a test/e2e harness) uses these
83
+ * to recognize the box's production daemon as owned, where
84
+ * `daemonSystemdUnitName()`/`daemonServiceLabel()` would name only its own
85
+ * sandbox job (W4, PHNX-3736).
86
+ */
87
+ export function productionDaemonServiceNames() {
88
+ return { systemdUnit: SYSTEMD_UNIT, launchdLabel: PLIST_NAME };
89
+ }
80
90
  /**
81
91
  * RUSH-2639 (residual): launchd/systemd route `unload`/`load`/`list` by the
82
92
  * service identifier ALONE, never by the plist/unit file's path. Baking the
@@ -286,8 +296,8 @@ function getSystemdUnitPath() {
286
296
  return path.join(os.homedir(), '.config', 'systemd', 'user', daemonSystemdUnitName());
287
297
  }
288
298
  /** Read the stored daemon PID from disk. Returns null if not present or invalid. */
289
- export function readDaemonPid() {
290
- const pidPath = getPidPath();
299
+ export function readDaemonPid(daemonDir) {
300
+ const pidPath = daemonDir ? path.join(daemonDir, PID_FILE) : getPidPath();
291
301
  if (!fs.existsSync(pidPath))
292
302
  return null;
293
303
  try {
@@ -1655,19 +1665,27 @@ export { getAgentsBinPath };
1655
1665
  * the daemon hasn't yet written its pid file but launchd/systemd already report
1656
1666
  * it running — so a start never has to surface a null PID for a daemon that is
1657
1667
  * in fact up. Returns null when the service isn't running or the query fails.
1668
+ *
1669
+ * `names` defaults to THIS process's (possibly sandbox-namespaced) job; a
1670
+ * caller under a redirected HOME passes `productionDaemonServiceNames()` to
1671
+ * ask after the real install's unit instead. Read-only either way.
1658
1672
  */
1659
- function readServiceManagerPid(platform = os.platform()) {
1660
- const reg = serviceManagerRegistrationAllowed();
1661
- if (!reg.allowed)
1673
+ export function readServiceManagerPid(platform = os.platform(), names) {
1674
+ const resolved = names ?? { systemdUnit: daemonSystemdUnitName(), launchdLabel: daemonServiceLabel() };
1675
+ // The registration gate exists because a sandboxed process must not REGISTER
1676
+ // or tear down jobs in the real per-user service manager. Asking after an
1677
+ // explicitly named job is read-only — in particular the production unit from
1678
+ // a redirected-HOME caller (W4) — and mutates nothing, so it is let through.
1679
+ if (names === undefined && !serviceManagerRegistrationAllowed().allowed)
1662
1680
  return null;
1663
1681
  try {
1664
1682
  if (platform === 'linux') {
1665
- const out = execFileSync('systemctl', ['--user', 'show', '-p', 'MainPID', '--value', daemonSystemdUnitName()], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
1683
+ const out = execFileSync('systemctl', ['--user', 'show', '-p', 'MainPID', '--value', resolved.systemdUnit], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
1666
1684
  const pid = parseInt(out, 10);
1667
1685
  return !isNaN(pid) && pid > 0 ? pid : null;
1668
1686
  }
1669
1687
  if (platform === 'darwin') {
1670
- const out = execFileSync('launchctl', ['list', daemonServiceLabel()], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] });
1688
+ const out = execFileSync('launchctl', ['list', resolved.launchdLabel], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] });
1671
1689
  const m = out.match(/"PID"\s*=\s*(\d+)/);
1672
1690
  if (m) {
1673
1691
  const pid = parseInt(m[1], 10);
@@ -1678,12 +1696,47 @@ function readServiceManagerPid(platform = os.platform()) {
1678
1696
  catch { /* not running / manager unavailable */ }
1679
1697
  return null;
1680
1698
  }
1699
+ /**
1700
+ * Thrown when a daemon LAUNCH is attempted under a redirected HOME without the
1701
+ * explicit test opt-in (W4, PHNX-3736). `bootstrap.ts` prints the message
1702
+ * without a stack — this is user-actionable, not an engineering bug.
1703
+ */
1704
+ export class RedirectedHomeDaemonError extends Error {
1705
+ name = 'RedirectedHomeDaemonError';
1706
+ }
1707
+ /**
1708
+ * W4 (PHNX-3736): never LAUNCH a daemon under a redirected (sandbox/test) HOME
1709
+ * without an explicit opt-in. A daemon started there keeps its own pid file
1710
+ * under the temp home, so the real install's pid-file takeover can never see
1711
+ * it — the leaked `HOME=/tmp/pin-e2e-<pid>` daemon that ran 4+ days on
1712
+ * yosemite-s1 was launched exactly this way by a headless e2e session that
1713
+ * never cleaned up. RUSH-3021 closed this for `ensureDaemonStarted`'s
1714
+ * AUTO-start path but left the explicit `startDaemon()` open, which is the
1715
+ * path the e2e harness took.
1716
+ *
1717
+ * Placed after the `already-running` early-return: reporting a live daemon (so
1718
+ * `daemon stop` can still kill a leaked one) must stay possible under any
1719
+ * HOME. `AGENTS_ALLOW_TEST_DAEMON=1` is the deliberate test/e2e seam — a
1720
+ * harness that sets it owns stopping what it starts.
1721
+ */
1722
+ function assertDaemonLaunchHomeAllowed() {
1723
+ const suffix = isolatedHomeSuffix();
1724
+ if (!suffix)
1725
+ return;
1726
+ if (process.env.AGENTS_ALLOW_TEST_DAEMON === '1')
1727
+ return;
1728
+ throw new RedirectedHomeDaemonError(`refusing to start the daemon under a redirected HOME (sandbox-${suffix}): ` +
1729
+ `a daemon launched here keeps its own pid file under ${process.env.HOME}, invisible to the real ` +
1730
+ `install's pid-file takeover, and outlives whatever launched it (PHNX-3736). ` +
1731
+ `For a deliberate test/e2e launch set AGENTS_ALLOW_TEST_DAEMON=1 — and stop the daemon when done.`);
1732
+ }
1681
1733
  /** Start the daemon via launchd, systemd, or as a detached process. */
1682
1734
  export function startDaemon(agentsBin) {
1683
1735
  if (isDaemonRunning()) {
1684
1736
  const pid = readDaemonPid();
1685
1737
  return { pid, method: 'already-running' };
1686
1738
  }
1739
+ assertDaemonLaunchHomeAllowed();
1687
1740
  const releaseLock = acquireStartLock();
1688
1741
  if (!releaseLock) {
1689
1742
  // Another process is already starting the daemon
@@ -1769,8 +1822,9 @@ export function ensureDaemonStarted() {
1769
1822
  // recursive teardown rm (ENOTEMPTY). Placed after the already-running branch
1770
1823
  // — reporting a live daemon stays allowed, same as the circuit breaker.
1771
1824
  // AGENTS_SERVICE_MANAGER_ALLOW_REDIRECTED_HOME=1 is the test seam for suites
1772
- // that exercise daemon startup deliberately; `agents daemon start` remains
1773
- // the operator override.
1825
+ // that exercise daemon startup deliberately. The explicit `agents daemon
1826
+ // start` path is gated separately by startDaemon's own redirected-HOME
1827
+ // refusal (AGENTS_ALLOW_TEST_DAEMON=1, W4/PHNX-3736).
1774
1828
  if (!serviceManagerRegistrationAllowed().allowed)
1775
1829
  return null;
1776
1830
  // RUSH-2418: the auto-start circuit breaker. A daemon that dies during