@phnx-labs/agents-cli 1.20.51 → 1.20.52

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 (62) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/commands/browser.js +215 -7
  3. package/dist/commands/cloud.js +6 -0
  4. package/dist/commands/events.d.ts +1 -1
  5. package/dist/commands/events.js +2 -3
  6. package/dist/commands/exec.js +17 -2
  7. package/dist/commands/factory.js +8 -0
  8. package/dist/commands/feed.d.ts +9 -0
  9. package/dist/commands/feed.js +69 -0
  10. package/dist/commands/logs.d.ts +5 -1
  11. package/dist/commands/logs.js +248 -3
  12. package/dist/commands/mcp.js +7 -0
  13. package/dist/commands/secrets.d.ts +22 -0
  14. package/dist/commands/secrets.js +173 -42
  15. package/dist/commands/teams.js +4 -0
  16. package/dist/index.js +6 -2
  17. package/dist/lib/browser/login-detection.d.ts +94 -0
  18. package/dist/lib/browser/login-detection.js +274 -0
  19. package/dist/lib/browser/profiles.d.ts +17 -8
  20. package/dist/lib/browser/profiles.js +27 -8
  21. package/dist/lib/browser/secret-ref.d.ts +10 -0
  22. package/dist/lib/browser/secret-ref.js +14 -0
  23. package/dist/lib/browser/service.js +14 -12
  24. package/dist/lib/cloud/rush.d.ts +15 -0
  25. package/dist/lib/cloud/rush.js +7 -1
  26. package/dist/lib/crabbox/lease.d.ts +6 -0
  27. package/dist/lib/crabbox/lease.js +11 -9
  28. package/dist/lib/crabbox/runtimes.d.ts +38 -1
  29. package/dist/lib/crabbox/runtimes.js +98 -5
  30. package/dist/lib/daemon.d.ts +12 -9
  31. package/dist/lib/daemon.js +32 -17
  32. package/dist/lib/events.d.ts +31 -5
  33. package/dist/lib/events.js +288 -101
  34. package/dist/lib/exec.js +1 -0
  35. package/dist/lib/feed.d.ts +56 -0
  36. package/dist/lib/feed.js +251 -0
  37. package/dist/lib/hooks.js +7 -2
  38. package/dist/lib/hosts/passthrough.js +1 -0
  39. package/dist/lib/rotate.js +2 -0
  40. package/dist/lib/secrets/Agents CLI.app/Contents/CodeResources +0 -0
  41. package/dist/lib/secrets/Agents CLI.app/Contents/MacOS/Agents CLI +0 -0
  42. package/dist/lib/secrets/agent.d.ts +21 -0
  43. package/dist/lib/secrets/agent.js +63 -1
  44. package/dist/lib/secrets/bundles.d.ts +33 -1
  45. package/dist/lib/secrets/bundles.js +38 -8
  46. package/dist/lib/secrets/icloud-import.d.ts +70 -0
  47. package/dist/lib/secrets/icloud-import.js +173 -0
  48. package/dist/lib/secrets/index.d.ts +36 -0
  49. package/dist/lib/secrets/index.js +99 -9
  50. package/dist/lib/secrets/remote.js +1 -1
  51. package/dist/lib/secrets/sync.js +1 -1
  52. package/dist/lib/session/discover.js +1 -2
  53. package/dist/lib/session/state.js +13 -1
  54. package/dist/lib/startup/command-registry.d.ts +1 -0
  55. package/dist/lib/startup/command-registry.js +2 -0
  56. package/dist/lib/state.d.ts +2 -0
  57. package/dist/lib/state.js +25 -8
  58. package/dist/lib/teams/agents.js +6 -3
  59. package/dist/lib/types.d.ts +10 -0
  60. package/dist/lib/whats-new.d.ts +5 -3
  61. package/dist/lib/whats-new.js +25 -5
  62. package/package.json +1 -1
@@ -5,6 +5,7 @@ import { addHostOption } from '../lib/hosts/option.js';
5
5
  import * as path from 'path';
6
6
  import { AgentManager, checkCliSignedIn, collectTeamsDoctorData, getAgentsDir, VALID_TASK_TYPES, } from '../lib/teams/agents.js';
7
7
  import { resolveProvider } from '../lib/cloud/registry.js';
8
+ import { emit } from '../lib/events.js';
8
9
  import { runSupervisor } from '../lib/teams/supervisor.js';
9
10
  import { debug } from '../lib/teams/debug.js';
10
11
  import { runPrWatch, DEFAULT_MAX_WAVES, } from '../lib/teams/pr-watch.js';
@@ -1317,6 +1318,7 @@ export function registerTeamsCommands(program) {
1317
1318
  }
1318
1319
  try {
1319
1320
  const result = await handleSpawn(mgr, team, agent, effectiveTask, cwd, opts.mode, opts.effort, null, cwd, version, opts.name ?? null, after, opts.model ?? null, envOverrides ?? null, taskType, cloudProviderId, cloudSessionId, opts.repo ?? null, opts.branch ?? null, worktreeName, worktreePath, profileName, hostName, hostTarget, hostRepoPath);
1321
+ emit('teams.add', { module: 'teams', team, agent, name: result.name, agent_id: result.agent_id, status: result.status });
1320
1322
  if (isJsonMode(opts)) {
1321
1323
  console.log(JSON.stringify(result, null, 2));
1322
1324
  return;
@@ -1487,6 +1489,7 @@ export function registerTeamsCommands(program) {
1487
1489
  await warnUnsignedTeammates(mgr, team);
1488
1490
  await warnThrottledTeammates(mgr, team);
1489
1491
  }
1492
+ emit('teams.start', { module: 'teams', team, watch: Boolean(opts.watch) });
1490
1493
  if (!opts.watch) {
1491
1494
  await runOneWave(mgr, team, Boolean(opts.json));
1492
1495
  return;
@@ -1526,6 +1529,7 @@ export function registerTeamsCommands(program) {
1526
1529
  },
1527
1530
  });
1528
1531
  const elapsed = Math.floor(result.elapsed_ms / 1000);
1532
+ emit('teams.complete', { module: 'teams', team, stoppedBy: result.stoppedBy, waves: result.waves, durationMs: result.elapsed_ms });
1529
1533
  if (result.stoppedBy === 'drained') {
1530
1534
  console.log(chalk.green(`Factory drained in ${elapsed}s (${result.waves} waves).`));
1531
1535
  }
package/dist/index.js CHANGED
@@ -50,7 +50,7 @@ if (IS_DEV_BUILD) {
50
50
  // module on each invocation (which loaded the whole ~50-module tree before the
51
51
  // first byte of output), the registry maps a command name to a thunk that
52
52
  // imports only what that command needs. See src/lib/startup/command-registry.ts.
53
- import { COMMAND_LOADERS, LAZY_COMMAND_NAMES, loadView, loadInspect, loadFeedback, loadCommands, loadHooks, loadSkills, loadRules, loadPermissions, loadMcp, loadCli, loadSubagents, loadPlugins, loadWorkflows, loadWorktree, loadVersions, loadImport, loadPackages, loadDaemon, loadRoutines, loadRun, loadDefaults, loadModels, loadPrune, loadTrash, loadRestore, loadDoctor, loadCheck, loadStatus, loadProfiles, loadSecrets, loadWallet, loadHelper, loadMenubar, loadBeta, loadSync, loadLock, loadRefreshRules, loadDrive, loadFactory, loadUsage, loadCost, loadBudget, loadAlias, loadPty, loadTmux, loadWatchdog, loadBrowser, loadComputer, loadHosts, loadLogs, loadEvents, loadAudit, loadSsh, loadPull, loadPush, loadRepo, loadSetup, } from './lib/startup/command-registry.js';
53
+ import { COMMAND_LOADERS, LAZY_COMMAND_NAMES, loadView, loadInspect, loadFeedback, loadCommands, loadHooks, loadSkills, loadRules, loadPermissions, loadMcp, loadCli, loadSubagents, loadPlugins, loadWorkflows, loadWorktree, loadVersions, loadImport, loadPackages, loadDaemon, loadRoutines, loadRun, loadDefaults, loadModels, loadPrune, loadTrash, loadRestore, loadDoctor, loadCheck, loadStatus, loadProfiles, loadSecrets, loadWallet, loadHelper, loadMenubar, loadBeta, loadSync, loadLock, loadRefreshRules, loadDrive, loadFactory, loadUsage, loadCost, loadBudget, loadAlias, loadPty, loadTmux, loadWatchdog, loadBrowser, loadComputer, loadHosts, loadLogs, loadEvents, loadAudit, loadSsh, loadPull, loadPush, loadRepo, loadSetup, loadFeed, } from './lib/startup/command-registry.js';
54
54
  import { applyGlobalHelpConventions } from './lib/help.js';
55
55
  import { renderWhatsNew } from './lib/whats-new.js';
56
56
  import { emit, redactArgs } from './lib/events.js';
@@ -101,7 +101,10 @@ program.hook('preAction', (_thisCommand, actionCommand) => {
101
101
  emit('command.start', {
102
102
  module: parts[0],
103
103
  command: parts.join(' '),
104
- args: redactArgs(actionCommand.args),
104
+ // Commander exposes positional operands in actionCommand.args but omits
105
+ // parsed option values. Audit the real argv so sensitive flags are seen
106
+ // and redacted instead of silently bypassing the policy.
107
+ args: redactArgs(process.argv.slice(2, 22)),
105
108
  cwd: process.cwd(),
106
109
  });
107
110
  }
@@ -704,6 +707,7 @@ async function registerAllEagerCommands() {
704
707
  await reg(loadLogs);
705
708
  await reg(loadEvents);
706
709
  await reg(loadAudit);
710
+ await reg(loadFeed);
707
711
  await reg(loadSsh);
708
712
  registerJobsCronAliasCommand(program, 'jobs');
709
713
  registerJobsCronAliasCommand(program, 'cron');
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Best-effort login-state detection for browser profiles.
3
+ *
4
+ * Reads a profile's Chromium cookie store (presence only — never decrypts the
5
+ * Keychain-encrypted values) to tell which login-gated services have a live
6
+ * session in that profile. Powers the `agents browser start` guardrail (warn
7
+ * when an agent opens a logged-out profile for a login-gated URL) and the
8
+ * `agents browser profiles logins` view.
9
+ *
10
+ * Everything here is advisory: any failure (missing DB, locked file, unknown
11
+ * schema) degrades to "no known session" and NEVER throws to callers — browser
12
+ * start must not slow down or break because cookie inspection hiccuped.
13
+ */
14
+ /** A login-gated service signature: host substrings + the auth-cookie names
15
+ * whose presence indicates a live session, plus optional login metadata. */
16
+ interface ServiceSignature {
17
+ hosts: string[];
18
+ cookies: string[];
19
+ /**
20
+ * Where an interactive login for this service starts, and the bundle key
21
+ * PREFIX its credentials live under. By convention a profile's `--secrets`
22
+ * bundle holds `<PREFIX>_USERNAME` / `<PREFIX>_PASSWORD` (see
23
+ * `credKeysForService`). The prefix is explicit — never string-munged from the
24
+ * service id — so e.g. `x` → `X`, `google` → `GOOGLE`.
25
+ */
26
+ login?: {
27
+ loginUrl: string;
28
+ keyPrefix: string;
29
+ };
30
+ }
31
+ /**
32
+ * Known login-gated services. Presence of ANY listed cookie on a matching host
33
+ * (unexpired, or a session cookie) = logged in. Deliberately conservative: a
34
+ * service absent from this map simply never triggers a warning — we do not
35
+ * guess. Each cookie name here is the definitive authenticated-session token for
36
+ * that service (e.g. LinkedIn's `li_at` is only set for a signed-in member;
37
+ * visitor cookies like `bcookie`/`JSESSIONID` are NOT auth). Services whose
38
+ * session is not reliably expressed as a recognizable cookie (e.g. Attio, whose
39
+ * only same-site cookies are third-party analytics) are deliberately omitted so
40
+ * we never emit a false "logged out" warning. Extend as needed.
41
+ */
42
+ export declare const AUTH_SIGNATURES: Record<string, ServiceSignature>;
43
+ /**
44
+ * The bundle keys a profile's `--secrets` bundle should hold to log into
45
+ * `service`: `<PREFIX>_USERNAME` / `<PREFIX>_PASSWORD`. Null for services with no
46
+ * login metadata. Feed a resolved value to the page with
47
+ * `agents browser type <ref> --secret <bundle>/<KEY>` (never printed).
48
+ */
49
+ export declare function credKeysForService(service: string): {
50
+ user: string;
51
+ pass: string;
52
+ } | null;
53
+ /** The interactive login URL for a service, or null. */
54
+ export declare function loginUrlForService(service: string): string | null;
55
+ export interface CookieRow {
56
+ host_key: string;
57
+ name: string;
58
+ }
59
+ /**
60
+ * Pure core: given a profile's (already expiry-filtered) cookie rows, return the
61
+ * services with a live session. Exported for direct unit testing without disk.
62
+ */
63
+ export declare function detectServices(rows: CookieRow[]): string[];
64
+ /** Map a URL to a known login-gated service key, or null. */
65
+ export declare function serviceForUrl(url: string): string | null;
66
+ /** A saved-login row from Chromium `Login Data` (username plaintext; password
67
+ * encrypted and never read). */
68
+ export interface LoginRow {
69
+ origin_url: string;
70
+ username_value: string;
71
+ signon_realm: string;
72
+ }
73
+ /**
74
+ * Map a profile's saved logins to service → account username (identity, not
75
+ * session). Best-effort; `{}` if `Login Data` is unreadable. The first non-empty
76
+ * username per service wins.
77
+ */
78
+ export declare function accountsForProfile(profileName: string): Promise<Record<string, string>>;
79
+ /**
80
+ * For each service with a LIVE session in the profile (cookie-gated), the
81
+ * account it is signed in as (from saved logins). Intersecting with live
82
+ * sessions means a stale saved-login for a service you've since logged out of
83
+ * never shows.
84
+ */
85
+ export declare function loginsWithAccountsForProfile(profileName: string): Promise<Array<{
86
+ service: string;
87
+ username?: string;
88
+ }>>;
89
+ /** Services with a live session in the given profile (best-effort; [] if none
90
+ * detected or the cookie store is unreadable). */
91
+ export declare function loginsForProfile(profileName: string): Promise<string[]>;
92
+ /** Profile names that have a live session for the given service. */
93
+ export declare function profilesLoggedInto(service: string): Promise<string[]>;
94
+ export {};
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Best-effort login-state detection for browser profiles.
3
+ *
4
+ * Reads a profile's Chromium cookie store (presence only — never decrypts the
5
+ * Keychain-encrypted values) to tell which login-gated services have a live
6
+ * session in that profile. Powers the `agents browser start` guardrail (warn
7
+ * when an agent opens a logged-out profile for a login-gated URL) and the
8
+ * `agents browser profiles logins` view.
9
+ *
10
+ * Everything here is advisory: any failure (missing DB, locked file, unknown
11
+ * schema) degrades to "no known session" and NEVER throws to callers — browser
12
+ * start must not slow down or break because cookie inspection hiccuped.
13
+ */
14
+ import * as fs from 'fs';
15
+ import * as os from 'os';
16
+ import * as path from 'path';
17
+ import Database from '../sqlite.js';
18
+ import { getBrowserRuntimeDir, listProfiles } from './profiles.js';
19
+ /**
20
+ * Known login-gated services. Presence of ANY listed cookie on a matching host
21
+ * (unexpired, or a session cookie) = logged in. Deliberately conservative: a
22
+ * service absent from this map simply never triggers a warning — we do not
23
+ * guess. Each cookie name here is the definitive authenticated-session token for
24
+ * that service (e.g. LinkedIn's `li_at` is only set for a signed-in member;
25
+ * visitor cookies like `bcookie`/`JSESSIONID` are NOT auth). Services whose
26
+ * session is not reliably expressed as a recognizable cookie (e.g. Attio, whose
27
+ * only same-site cookies are third-party analytics) are deliberately omitted so
28
+ * we never emit a false "logged out" warning. Extend as needed.
29
+ */
30
+ export const AUTH_SIGNATURES = {
31
+ linkedin: {
32
+ hosts: ['linkedin.com'],
33
+ cookies: ['li_at'],
34
+ login: { loginUrl: 'https://www.linkedin.com/login', keyPrefix: 'LINKEDIN' },
35
+ },
36
+ google: {
37
+ hosts: ['google.com'],
38
+ cookies: ['SID', 'SAPISID', '__Secure-1PSID', '__Secure-3PSID'],
39
+ login: { loginUrl: 'https://accounts.google.com/', keyPrefix: 'GOOGLE' },
40
+ },
41
+ x: {
42
+ hosts: ['x.com', 'twitter.com'],
43
+ cookies: ['auth_token'],
44
+ login: { loginUrl: 'https://x.com/login', keyPrefix: 'X' },
45
+ },
46
+ reddit: {
47
+ hosts: ['reddit.com'],
48
+ cookies: ['reddit_session', 'token_v2'],
49
+ login: { loginUrl: 'https://www.reddit.com/login', keyPrefix: 'REDDIT' },
50
+ },
51
+ github: {
52
+ hosts: ['github.com'],
53
+ cookies: ['user_session'],
54
+ login: { loginUrl: 'https://github.com/login', keyPrefix: 'GITHUB' },
55
+ },
56
+ };
57
+ /**
58
+ * The bundle keys a profile's `--secrets` bundle should hold to log into
59
+ * `service`: `<PREFIX>_USERNAME` / `<PREFIX>_PASSWORD`. Null for services with no
60
+ * login metadata. Feed a resolved value to the page with
61
+ * `agents browser type <ref> --secret <bundle>/<KEY>` (never printed).
62
+ */
63
+ export function credKeysForService(service) {
64
+ const login = AUTH_SIGNATURES[service]?.login;
65
+ if (!login)
66
+ return null;
67
+ return { user: `${login.keyPrefix}_USERNAME`, pass: `${login.keyPrefix}_PASSWORD` };
68
+ }
69
+ /** The interactive login URL for a service, or null. */
70
+ export function loginUrlForService(service) {
71
+ return AUTH_SIGNATURES[service]?.login?.loginUrl ?? null;
72
+ }
73
+ /**
74
+ * Current time as microseconds since 1601-01-01 (Chromium's `expires_utc`
75
+ * epoch), as a BigInt. Chromium expiries routinely exceed 2^53, so this is
76
+ * bound into SQL as a BigInt and the comparison happens IN SQLite — the huge
77
+ * integer never marshals back to JS (node:sqlite throws RangeError if it does).
78
+ * 11644473600000 = ms between 1601-01-01 and 1970-01-01.
79
+ */
80
+ function chromeNowMicrosBigInt() {
81
+ return (BigInt(Date.now()) + 11644473600000n) * 1000n;
82
+ }
83
+ function hostMatches(hostKey, host) {
84
+ return hostKey === host || hostKey === '.' + host || hostKey.endsWith('.' + host);
85
+ }
86
+ /**
87
+ * Pure core: given a profile's (already expiry-filtered) cookie rows, return the
88
+ * services with a live session. Exported for direct unit testing without disk.
89
+ */
90
+ export function detectServices(rows) {
91
+ const services = [];
92
+ for (const [service, sig] of Object.entries(AUTH_SIGNATURES)) {
93
+ const found = rows.some((r) => sig.cookies.includes(r.name) && sig.hosts.some((h) => hostMatches(r.host_key, h)));
94
+ if (found)
95
+ services.push(service);
96
+ }
97
+ return services;
98
+ }
99
+ /** Map a URL to a known login-gated service key, or null. */
100
+ export function serviceForUrl(url) {
101
+ let host;
102
+ try {
103
+ host = new URL(url).hostname;
104
+ }
105
+ catch {
106
+ return null;
107
+ }
108
+ for (const [service, sig] of Object.entries(AUTH_SIGNATURES)) {
109
+ if (sig.hosts.some((h) => host === h || host.endsWith('.' + h)))
110
+ return service;
111
+ }
112
+ return null;
113
+ }
114
+ /**
115
+ * Locate candidate Chromium DBs for a profile at the given relative paths. The
116
+ * live runtime dir is keyed by the composite `<profile>@<endpoint>` name, so we
117
+ * scan the browser cache root for `<profile>` and `<profile>@*` dirs and return
118
+ * every matching DB found, most-recently-modified first.
119
+ */
120
+ function profileDbCandidates(profileName, relPaths) {
121
+ const root = getBrowserRuntimeDir();
122
+ let entries;
123
+ try {
124
+ entries = fs.readdirSync(root);
125
+ }
126
+ catch {
127
+ return [];
128
+ }
129
+ const dirs = entries.filter((e) => e === profileName || e.startsWith(profileName + '@'));
130
+ const found = [];
131
+ for (const d of dirs) {
132
+ for (const rel of relPaths) {
133
+ const p = path.join(root, d, ...rel);
134
+ try {
135
+ found.push({ p, mtime: fs.statSync(p).mtimeMs });
136
+ }
137
+ catch {
138
+ /* not present */
139
+ }
140
+ }
141
+ }
142
+ return found.sort((a, b) => b.mtime - a.mtime).map((f) => f.p);
143
+ }
144
+ function cookieDbCandidates(profileName) {
145
+ return profileDbCandidates(profileName, [
146
+ ['chrome-data', 'Default', 'Cookies'],
147
+ ['chrome-data', 'Default', 'Network', 'Cookies'],
148
+ ]);
149
+ }
150
+ function loginDbCandidates(profileName) {
151
+ return profileDbCandidates(profileName, [['chrome-data', 'Default', 'Login Data']]);
152
+ }
153
+ /**
154
+ * Open a Chromium SQLite store safely: copy the DB (and any WAL/SHM sidecars) to
155
+ * a temp dir first so a running browser's lock never blocks us and we never
156
+ * touch the live file, run `fn`, then clean up. Returns `fallback` on any error.
157
+ */
158
+ function withCopiedDb(dbPath, fn, fallback) {
159
+ let tmpDir = null;
160
+ try {
161
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agents-browserdb-'));
162
+ const tmpDb = path.join(tmpDir, 'db');
163
+ fs.copyFileSync(dbPath, tmpDb);
164
+ for (const suffix of ['-wal', '-shm']) {
165
+ if (fs.existsSync(dbPath + suffix))
166
+ fs.copyFileSync(dbPath + suffix, tmpDb + suffix);
167
+ }
168
+ const db = new Database(tmpDb);
169
+ try {
170
+ return fn(db);
171
+ }
172
+ finally {
173
+ db.close();
174
+ }
175
+ }
176
+ catch {
177
+ return fallback;
178
+ }
179
+ finally {
180
+ if (tmpDir) {
181
+ try {
182
+ fs.rmSync(tmpDir, { recursive: true, force: true });
183
+ }
184
+ catch {
185
+ /* temp cleanup best-effort */
186
+ }
187
+ }
188
+ }
189
+ }
190
+ /** Read (expiry-filtered) cookie rows from a Chromium cookie DB. [] on failure. */
191
+ function readCookieRows(dbPath) {
192
+ return withCopiedDb(dbPath, (db) => {
193
+ // Filter expiry in SQL (session cookies have expires_utc = 0; otherwise it
194
+ // must be in the future) and select only text columns, so the huge
195
+ // microsecond integer never crosses into JS.
196
+ const rows = db
197
+ .prepare('SELECT host_key, name FROM cookies WHERE expires_utc = 0 OR expires_utc > ?')
198
+ .all(chromeNowMicrosBigInt());
199
+ return rows.map((r) => ({
200
+ host_key: String(r.host_key ?? ''),
201
+ name: String(r.name ?? ''),
202
+ }));
203
+ }, []);
204
+ }
205
+ /** Read saved-login rows from a Chromium `Login Data` DB. Skips
206
+ * user-blacklisted origins ("never save"). Selects only text columns —
207
+ * `password_value` (encrypted) is never touched. [] on failure. */
208
+ function readLoginRows(dbPath) {
209
+ return withCopiedDb(dbPath, (db) => {
210
+ const rows = db
211
+ .prepare('SELECT origin_url, username_value, signon_realm FROM logins WHERE blacklisted_by_user = 0')
212
+ .all();
213
+ return rows.map((r) => ({
214
+ origin_url: String(r.origin_url ?? ''),
215
+ username_value: String(r.username_value ?? ''),
216
+ signon_realm: String(r.signon_realm ?? ''),
217
+ }));
218
+ }, []);
219
+ }
220
+ /**
221
+ * Map a profile's saved logins to service → account username (identity, not
222
+ * session). Best-effort; `{}` if `Login Data` is unreadable. The first non-empty
223
+ * username per service wins.
224
+ */
225
+ export async function accountsForProfile(profileName) {
226
+ const candidates = loginDbCandidates(profileName);
227
+ if (candidates.length === 0)
228
+ return {};
229
+ const rows = readLoginRows(candidates[0]);
230
+ const out = {};
231
+ for (const r of rows) {
232
+ if (!r.username_value)
233
+ continue;
234
+ const service = serviceForUrl(r.origin_url) ?? serviceForUrl(r.signon_realm);
235
+ if (service && !out[service])
236
+ out[service] = r.username_value;
237
+ }
238
+ return out;
239
+ }
240
+ /**
241
+ * For each service with a LIVE session in the profile (cookie-gated), the
242
+ * account it is signed in as (from saved logins). Intersecting with live
243
+ * sessions means a stale saved-login for a service you've since logged out of
244
+ * never shows.
245
+ */
246
+ export async function loginsWithAccountsForProfile(profileName) {
247
+ const active = await loginsForProfile(profileName);
248
+ if (active.length === 0)
249
+ return [];
250
+ const accounts = await accountsForProfile(profileName);
251
+ return active.map((service) => ({ service, username: accounts[service] }));
252
+ }
253
+ /** Services with a live session in the given profile (best-effort; [] if none
254
+ * detected or the cookie store is unreadable). */
255
+ export async function loginsForProfile(profileName) {
256
+ const candidates = cookieDbCandidates(profileName);
257
+ if (candidates.length === 0)
258
+ return [];
259
+ const rows = readCookieRows(candidates[0]);
260
+ if (rows.length === 0)
261
+ return [];
262
+ return detectServices(rows);
263
+ }
264
+ /** Profile names that have a live session for the given service. */
265
+ export async function profilesLoggedInto(service) {
266
+ const profiles = await listProfiles();
267
+ const out = [];
268
+ for (const p of profiles) {
269
+ const logins = await loginsForProfile(p.name);
270
+ if (logins.includes(service))
271
+ out.push(p.name);
272
+ }
273
+ return out;
274
+ }
@@ -1,20 +1,29 @@
1
1
  import type { BrowserProfile } from './types.js';
2
2
  export type { BrowserProfile } from './types.js';
3
3
  export declare const DEFAULT_BROWSER_PROFILE_NAME = "default";
4
+ /**
5
+ * The device-local configured default profile name (set via
6
+ * `agents browser profiles set-default`), or undefined when unset. When set, it
7
+ * is the profile `agents browser start` resolves to for BOTH the no-`--profile`
8
+ * path and an explicit `--profile default`. Stored per-machine — see
9
+ * `Meta.defaultBrowserProfile`.
10
+ */
11
+ export declare function getConfiguredDefaultProfileName(): string | undefined;
4
12
  export declare function getBrowserRuntimeDir(): string;
5
13
  export declare function getProfileRuntimeDir(name: string): string;
6
14
  export declare function listProfiles(): Promise<BrowserProfile[]>;
7
15
  export declare function getProfile(name: string): Promise<BrowserProfile | null>;
8
16
  /**
9
- * Ensure a `default` profile exists, auto-picking the first installed
10
- * Chromium-family browser per the platform priority list in chrome.ts.
17
+ * Resolve the profile `agents browser start` uses when no `--profile` is given.
11
18
  *
12
- * Re-uses an existing `default` profile as-is (we don't second-guess the user
13
- * if they've already customized it). On first run we walk the priority list
14
- * (macOS: chrome > brave > edge > chromium > comet; Linux: chrome > chromium >
15
- * brave > edge; Windows: edge > chrome > brave > comet) and pin the profile to the
16
- * first match. Throws an actionable error if none of those binaries are
17
- * installed so the user knows exactly which browsers we'd accept.
19
+ * Order: (1) the device-local configured default (`agents browser profiles
20
+ * set-default <name>`) when it names an existing profile; (2) an existing
21
+ * `default` profile as-is; (3) auto-pick the first installed Chromium-family
22
+ * browser per the platform priority list in chrome.ts (macOS: chrome > brave >
23
+ * edge > chromium > comet; Linux: chrome > chromium > brave > edge; Windows:
24
+ * edge > chrome > brave > comet) and pin a new `default` profile to it. Throws an
25
+ * actionable error if none of those binaries are installed. A configured default
26
+ * that no longer exists warns and falls through to (2)/(3) — never a hard fail.
18
27
  */
19
28
  export declare function ensureDefaultBrowserProfile(): Promise<BrowserProfile>;
20
29
  /**
@@ -3,6 +3,16 @@ import { getBrowserRuntimeDir as getBrowserRuntimeDirRoot, readMeta, writeMeta,
3
3
  import { findBrowserPath, findFirstInstalledBrowser, isPortInUse } from './chrome.js';
4
4
  import { DEFAULT_VIEWPORT } from './devices.js';
5
5
  export const DEFAULT_BROWSER_PROFILE_NAME = 'default';
6
+ /**
7
+ * The device-local configured default profile name (set via
8
+ * `agents browser profiles set-default`), or undefined when unset. When set, it
9
+ * is the profile `agents browser start` resolves to for BOTH the no-`--profile`
10
+ * path and an explicit `--profile default`. Stored per-machine — see
11
+ * `Meta.defaultBrowserProfile`.
12
+ */
13
+ export function getConfiguredDefaultProfileName() {
14
+ return readMeta().defaultBrowserProfile || undefined;
15
+ }
6
16
  export function getBrowserRuntimeDir() {
7
17
  return getBrowserRuntimeDirRoot();
8
18
  }
@@ -69,17 +79,26 @@ export async function getProfile(name) {
69
79
  return configToProfile(name, config);
70
80
  }
71
81
  /**
72
- * Ensure a `default` profile exists, auto-picking the first installed
73
- * Chromium-family browser per the platform priority list in chrome.ts.
82
+ * Resolve the profile `agents browser start` uses when no `--profile` is given.
74
83
  *
75
- * Re-uses an existing `default` profile as-is (we don't second-guess the user
76
- * if they've already customized it). On first run we walk the priority list
77
- * (macOS: chrome > brave > edge > chromium > comet; Linux: chrome > chromium >
78
- * brave > edge; Windows: edge > chrome > brave > comet) and pin the profile to the
79
- * first match. Throws an actionable error if none of those binaries are
80
- * installed so the user knows exactly which browsers we'd accept.
84
+ * Order: (1) the device-local configured default (`agents browser profiles
85
+ * set-default <name>`) when it names an existing profile; (2) an existing
86
+ * `default` profile as-is; (3) auto-pick the first installed Chromium-family
87
+ * browser per the platform priority list in chrome.ts (macOS: chrome > brave >
88
+ * edge > chromium > comet; Linux: chrome > chromium > brave > edge; Windows:
89
+ * edge > chrome > brave > comet) and pin a new `default` profile to it. Throws an
90
+ * actionable error if none of those binaries are installed. A configured default
91
+ * that no longer exists warns and falls through to (2)/(3) — never a hard fail.
81
92
  */
82
93
  export async function ensureDefaultBrowserProfile() {
94
+ const configured = getConfiguredDefaultProfileName();
95
+ if (configured) {
96
+ const chosen = await getProfile(configured);
97
+ if (chosen)
98
+ return chosen;
99
+ console.warn(`warning: configured default browser profile "${configured}" no longer exists; ` +
100
+ `falling back to auto-detect. Fix with: agents browser profiles set-default <name> (or --unset)`);
101
+ }
83
102
  const existing = await getProfile(DEFAULT_BROWSER_PROFILE_NAME);
84
103
  if (existing)
85
104
  return existing;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Parse a `<bundle>/<KEY>` reference (optionally `secret:<bundle>/<KEY>`) used by
3
+ * `agents browser type --secret` to feed a credential from an `agents secrets`
4
+ * bundle into a page WITHOUT the value ever crossing stdout or the transcript.
5
+ * Returns null on a malformed ref.
6
+ */
7
+ export declare function parseSecretRef(ref: string): {
8
+ bundle: string;
9
+ key: string;
10
+ } | null;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Parse a `<bundle>/<KEY>` reference (optionally `secret:<bundle>/<KEY>`) used by
3
+ * `agents browser type --secret` to feed a credential from an `agents secrets`
4
+ * bundle into a page WITHOUT the value ever crossing stdout or the transcript.
5
+ * Returns null on a malformed ref.
6
+ */
7
+ export function parseSecretRef(ref) {
8
+ const body = ref.startsWith('secret:') ? ref.slice('secret:'.length) : ref;
9
+ const slash = body.indexOf('/');
10
+ // Need a non-empty bundle before the slash and a non-empty key after it.
11
+ if (slash <= 0 || slash >= body.length - 1)
12
+ return null;
13
+ return { bundle: body.slice(0, slash), key: body.slice(slash + 1) };
14
+ }
@@ -8,7 +8,7 @@ import { getProfile, getProfileRuntimeDir, getBrowserRuntimeDir, listProfiles, e
8
8
  import { killChrome, getRunningChromeInfo, launchBrowser, allocatePort } from './chrome.js';
9
9
  import { connectLocal } from './drivers/local.js';
10
10
  import { connectSSH, shellQuote } from './drivers/ssh.js';
11
- import { clearProfileRuntime } from './runtime-state.js';
11
+ import { clearProfileRuntime, listProfileCacheDirs, readProfileRuntimeMeta, isProcessAlive } from './runtime-state.js';
12
12
  import { resolveDomainSkill } from './domain-skills.js';
13
13
  import { generateTaskId, generateShortId, generateTaskName, } from './types.js';
14
14
  import { getRefs, resolveRefToCoords, describeRefs, healRef } from './refs.js';
@@ -415,6 +415,7 @@ export class BrowserService {
415
415
  killChrome(conn.pid);
416
416
  conn.cleanup?.();
417
417
  this.connections.delete(profileName);
418
+ clearProfileRuntime(profileName);
418
419
  }
419
420
  return { ok: true, profile: profileName };
420
421
  }
@@ -442,17 +443,18 @@ export class BrowserService {
442
443
  killChrome(conn.pid);
443
444
  conn.cleanup?.();
444
445
  this.connections.delete(key);
445
- }
446
- const runtimeDir = getProfileRuntimeDir(profileName);
447
- const pidFile = path.join(runtimeDir, 'pid');
448
- const portFile = path.join(runtimeDir, 'port');
449
- if (fs.existsSync(pidFile)) {
450
- const pid = parseInt(fs.readFileSync(pidFile, 'utf-8').trim(), 10);
451
- killChrome(pid);
452
- fs.unlinkSync(pidFile);
453
- }
454
- if (fs.existsSync(portFile)) {
455
- fs.unlinkSync(portFile);
446
+ clearProfileRuntime(key);
447
+ }
448
+ // Kill stale processes and clean runtime dirs for every composite and
449
+ // fork entry belonging to this profile (including `.N` forks left by
450
+ // earlier daemon sessions that the connection loop above didn't cover).
451
+ for (const dir of listProfileCacheDirs(profileName)) {
452
+ const dirName = path.basename(dir);
453
+ const meta = readProfileRuntimeMeta(dirName);
454
+ if (meta?.pid && meta.pid !== 0 && isProcessAlive(meta.pid, meta.command)) {
455
+ killChrome(meta.pid);
456
+ }
457
+ clearProfileRuntime(dirName);
456
458
  }
457
459
  }
458
460
  async navigate(taskId, url, profileName) {
@@ -29,6 +29,21 @@ export interface AccountTokenEntry {
29
29
  /** Stringified OAuth credentials JSON (Mac: keychain blob; Linux: .credentials.json). */
30
30
  credentials_json: string;
31
31
  }
32
+ /**
33
+ * Read the raw OAuth credentials for one Claude version. On Mac, prefer the
34
+ * Keychain blob (canonical). On Linux/CI, fall back to `.claude/.credentials.json`
35
+ * inside the version home (where the Linux Claude CLI stores its OAuth).
36
+ *
37
+ * Returns null when no credentials are findable — caller treats as "version
38
+ * is installed but not signed in" and skips it from the manifest.
39
+ *
40
+ * NOTE: the darwin branch returns the UNWRAPPED oauth sub-object (what the Rush
41
+ * server re-wraps). It is NOT the shape Claude Code reads back from
42
+ * `.credentials.json`. The lease exporter (crabbox/runtimes.ts) therefore only
43
+ * reuses the Linux `.credentials.json` branch here and reads the wrapped raw
44
+ * Keychain payload itself on darwin.
45
+ */
46
+ export declare function readClaudeCredentialsBlob(home: string): Promise<string | null>;
32
47
  /**
33
48
  * Build a manifest of the user's local Claude installations to send on every
34
49
  * cloud dispatch. The manifest is the contract the server uses to detect when
@@ -170,8 +170,14 @@ function parsePromptCode(body) {
170
170
  *
171
171
  * Returns null when no credentials are findable — caller treats as "version
172
172
  * is installed but not signed in" and skips it from the manifest.
173
+ *
174
+ * NOTE: the darwin branch returns the UNWRAPPED oauth sub-object (what the Rush
175
+ * server re-wraps). It is NOT the shape Claude Code reads back from
176
+ * `.credentials.json`. The lease exporter (crabbox/runtimes.ts) therefore only
177
+ * reuses the Linux `.credentials.json` branch here and reads the wrapped raw
178
+ * Keychain payload itself on darwin.
173
179
  */
174
- async function readClaudeCredentialsBlob(home) {
180
+ export async function readClaudeCredentialsBlob(home) {
175
181
  if (process.platform === 'darwin') {
176
182
  const oauth = await loadClaudeOauth(home);
177
183
  if (oauth && oauth.accessToken) {
@@ -26,6 +26,12 @@ export interface LeaseRunOptions {
26
26
  onData?: (s: string) => void;
27
27
  /** Keep the box after the run instead of stopping it. */
28
28
  keep?: boolean;
29
+ /**
30
+ * Raw wrapped Claude OAuth payload (from `resolveClaudeCredentialsBlob`), written
31
+ * to `~/.claude/.credentials.json` on the box. The command layer resolves it
32
+ * (after consent) so this module stays free of Keychain I/O and unit-testable.
33
+ */
34
+ claudeCredentialsJson?: string | null;
29
35
  }
30
36
  export interface LeaseRunResult {
31
37
  box: CrabboxBox;