@phnx-labs/agents-cli 1.20.92 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/CHANGELOG.md +385 -0
  2. package/README.md +3 -0
  3. package/dist/bin/agents +0 -0
  4. package/dist/commands/beta.js +3 -5
  5. package/dist/commands/doctor.js +23 -0
  6. package/dist/commands/events.js +91 -1
  7. package/dist/commands/exec.js +13 -0
  8. package/dist/commands/mailboxes.js +39 -1
  9. package/dist/commands/message.js +12 -1
  10. package/dist/commands/packages.js +14 -5
  11. package/dist/commands/projects.d.ts +38 -0
  12. package/dist/commands/projects.js +355 -48
  13. package/dist/commands/routines.js +27 -1
  14. package/dist/commands/rules.js +6 -0
  15. package/dist/commands/secrets.d.ts +17 -0
  16. package/dist/commands/secrets.js +198 -7
  17. package/dist/commands/send.d.ts +14 -12
  18. package/dist/commands/send.js +105 -35
  19. package/dist/commands/sessions.d.ts +17 -0
  20. package/dist/commands/sessions.js +16 -8
  21. package/dist/commands/setup-browser.js +5 -1
  22. package/dist/commands/setup-fleet.js +5 -0
  23. package/dist/commands/setup-preferences.d.ts +53 -0
  24. package/dist/commands/setup-preferences.js +142 -0
  25. package/dist/commands/setup.js +8 -9
  26. package/dist/commands/ssh.js +220 -10
  27. package/dist/commands/sync.d.ts +2 -2
  28. package/dist/commands/sync.js +13 -12
  29. package/dist/commands/view.js +4 -0
  30. package/dist/commands/watchdog.js +26 -3
  31. package/dist/index.js +38 -6
  32. package/dist/lib/activity.d.ts +15 -0
  33. package/dist/lib/activity.js +26 -2
  34. package/dist/lib/auto-dispatch.d.ts +6 -1
  35. package/dist/lib/auto-dispatch.js +7 -2
  36. package/dist/lib/beta.d.ts +1 -1
  37. package/dist/lib/beta.js +1 -1
  38. package/dist/lib/channels/send.d.ts +83 -0
  39. package/dist/lib/channels/send.js +112 -0
  40. package/dist/lib/daemon.d.ts +13 -0
  41. package/dist/lib/daemon.js +80 -60
  42. package/dist/lib/device-config.d.ts +82 -0
  43. package/dist/lib/device-config.js +296 -0
  44. package/dist/lib/event-provenance.d.ts +19 -0
  45. package/dist/lib/event-provenance.js +48 -0
  46. package/dist/lib/events-ingest.d.ts +46 -0
  47. package/dist/lib/events-ingest.js +182 -0
  48. package/dist/lib/events.d.ts +17 -5
  49. package/dist/lib/events.js +59 -56
  50. package/dist/lib/feed.d.ts +1 -1
  51. package/dist/lib/feed.js +2 -0
  52. package/dist/lib/git.d.ts +13 -2
  53. package/dist/lib/git.js +38 -6
  54. package/dist/lib/linear-project-counts.d.ts +129 -0
  55. package/dist/lib/linear-project-counts.js +206 -0
  56. package/dist/lib/linear-projects.d.ts +62 -0
  57. package/dist/lib/linear-projects.js +144 -0
  58. package/dist/lib/mailbox-gc.js +30 -7
  59. package/dist/lib/mailbox.d.ts +14 -1
  60. package/dist/lib/mailbox.js +35 -3
  61. package/dist/lib/menubar/MenubarHelper.app/Contents/CodeResources +0 -0
  62. package/dist/lib/menubar/MenubarHelper.app/Contents/MacOS/MenubarHelper +0 -0
  63. package/dist/lib/menubar/install-menubar.d.ts +5 -21
  64. package/dist/lib/menubar/install-menubar.js +35 -44
  65. package/dist/lib/menubar/notify-desktop.d.ts +17 -2
  66. package/dist/lib/menubar/notify-desktop.js +8 -2
  67. package/dist/lib/migrate.js +1 -1
  68. package/dist/lib/models.js +21 -11
  69. package/dist/lib/overdue.d.ts +1 -1
  70. package/dist/lib/overdue.js +54 -19
  71. package/dist/lib/project-import.d.ts +96 -0
  72. package/dist/lib/project-import.js +171 -0
  73. package/dist/lib/project-probe.d.ts +75 -0
  74. package/dist/lib/project-probe.js +160 -0
  75. package/dist/lib/project-resources.d.ts +8 -0
  76. package/dist/lib/project-resources.js +31 -3
  77. package/dist/lib/project-status.d.ts +32 -1
  78. package/dist/lib/project-status.js +82 -1
  79. package/dist/lib/projects.d.ts +6 -0
  80. package/dist/lib/projects.js +12 -0
  81. package/dist/lib/remote-agents-json.d.ts +14 -1
  82. package/dist/lib/remote-agents-json.js +21 -3
  83. package/dist/lib/routine-notify.d.ts +11 -0
  84. package/dist/lib/routine-notify.js +22 -0
  85. package/dist/lib/routines.d.ts +53 -0
  86. package/dist/lib/routines.js +105 -4
  87. package/dist/lib/rules/run-sync.d.ts +18 -0
  88. package/dist/lib/rules/run-sync.js +92 -0
  89. package/dist/lib/run-notify.js +3 -0
  90. package/dist/lib/scheduler.js +12 -2
  91. package/dist/lib/secrets/Agents CLI.app/Contents/CodeResources +0 -0
  92. package/dist/lib/secrets/Agents CLI.app/Contents/MacOS/Agents CLI +0 -0
  93. package/dist/lib/secrets/audit.d.ts +1 -1
  94. package/dist/lib/secrets/audit.js +53 -10
  95. package/dist/lib/secrets/index.d.ts +4 -5
  96. package/dist/lib/secrets/index.js +4 -5
  97. package/dist/lib/secrets/list-filter.d.ts +20 -5
  98. package/dist/lib/secrets/list-filter.js +22 -6
  99. package/dist/lib/secrets/usage-db.d.ts +106 -0
  100. package/dist/lib/secrets/usage-db.js +236 -0
  101. package/dist/lib/session/active.d.ts +16 -2
  102. package/dist/lib/session/active.js +8 -4
  103. package/dist/lib/session/bundle.js +5 -1
  104. package/dist/lib/session/remote-active.d.ts +5 -1
  105. package/dist/lib/session/remote-active.js +4 -1
  106. package/dist/lib/session/remote-list.d.ts +1 -15
  107. package/dist/lib/session/remote-list.js +22 -111
  108. package/dist/lib/session/sync/config.d.ts +13 -5
  109. package/dist/lib/session/sync/config.js +21 -13
  110. package/dist/lib/sqlite.js +28 -1
  111. package/dist/lib/startup/command-registry.d.ts +0 -2
  112. package/dist/lib/startup/command-registry.js +1 -5
  113. package/dist/lib/state.d.ts +19 -2
  114. package/dist/lib/state.js +99 -10
  115. package/dist/lib/sync-umbrella.d.ts +11 -23
  116. package/dist/lib/sync-umbrella.js +14 -45
  117. package/dist/lib/teams/agents.d.ts +35 -3
  118. package/dist/lib/teams/agents.js +52 -8
  119. package/dist/lib/teams/scheduler.d.ts +29 -2
  120. package/dist/lib/teams/scheduler.js +60 -16
  121. package/dist/lib/types.d.ts +22 -5
  122. package/dist/lib/versions.d.ts +6 -0
  123. package/dist/lib/versions.js +6 -4
  124. package/package.json +1 -2
  125. package/dist/commands/drive.d.ts +0 -10
  126. package/dist/commands/drive.js +0 -183
  127. package/dist/commands/hq.d.ts +0 -2
  128. package/dist/commands/hq.js +0 -58
  129. package/dist/commands/sessions-sync.d.ts +0 -17
  130. package/dist/commands/sessions-sync.js +0 -135
  131. package/dist/commands/sync-provision.d.ts +0 -23
  132. package/dist/commands/sync-provision.js +0 -107
  133. package/dist/lib/drive-sync.d.ts +0 -45
  134. package/dist/lib/drive-sync.js +0 -238
  135. package/dist/lib/hq/floor.d.ts +0 -87
  136. package/dist/lib/hq/floor.js +0 -243
  137. package/dist/lib/session/sync/crdt.d.ts +0 -44
  138. package/dist/lib/session/sync/crdt.js +0 -119
  139. package/dist/lib/session/sync/manifest.d.ts +0 -62
  140. package/dist/lib/session/sync/manifest.js +0 -100
  141. package/dist/lib/session/sync/provision.d.ts +0 -49
  142. package/dist/lib/session/sync/provision.js +0 -91
  143. package/dist/lib/session/sync/r2.d.ts +0 -32
  144. package/dist/lib/session/sync/r2.js +0 -121
  145. package/dist/lib/session/sync/sync.d.ts +0 -106
  146. package/dist/lib/session/sync/sync.js +0 -374
@@ -1,58 +0,0 @@
1
- import chalk from 'chalk';
2
- import { getActiveSessions } from '../lib/session/active.js';
3
- import { AgentManager } from '../lib/teams/agents.js';
4
- import { handleStatus, handleTasks } from '../lib/teams/api.js';
5
- import { listAskStats, listBlocks } from '../lib/feed.js';
6
- import { buildSessionSignals, synthesizeControlCards } from '../lib/feed-ranking.js';
7
- import { discoverSessions } from '../lib/session/discover.js';
8
- import { buildHqFloor } from '../lib/hq/floor.js';
9
- import { die } from '../lib/format.js';
10
- async function collectFloorSnapshot() {
11
- const manager = new AgentManager();
12
- const [sessions, tasksResult] = await Promise.all([
13
- getActiveSessions(),
14
- handleTasks(manager, 1000),
15
- ]);
16
- const teammatesByTeam = new Map();
17
- await Promise.all(tasksResult.tasks.map(async (team) => {
18
- const status = await handleStatus(manager, team.task_name, 'all');
19
- teammatesByTeam.set(team.task_name, status.agents);
20
- }));
21
- const sessionMetas = sessions.length > 0 ? await discoverSessions({ all: true, limit: 5000 }) : [];
22
- const blocks = [
23
- ...listBlocks(),
24
- ...synthesizeControlCards(buildSessionSignals(sessions, sessionMetas), listAskStats()),
25
- ];
26
- return buildHqFloor({
27
- sessions,
28
- teams: tasksResult.tasks,
29
- teammatesByTeam,
30
- blocks,
31
- });
32
- }
33
- export function registerHqCommand(program) {
34
- const hq = program
35
- .command('hq')
36
- .description('Machine-readable bridge for Agents HQ floor management.');
37
- hq
38
- .command('floor')
39
- .description('Emit the live floor snapshot: rooms, agents, ambient events, and runnable actions.')
40
- .option('--json', 'Output machine-readable JSON')
41
- .action(async (opts) => {
42
- try {
43
- const snapshot = await collectFloorSnapshot();
44
- if (opts.json || !process.stdout.isTTY) {
45
- console.log(JSON.stringify(snapshot, null, 2));
46
- return;
47
- }
48
- console.log(chalk.bold('Agents HQ floor'));
49
- console.log(chalk.gray(`${snapshot.counters.agents} agents, ${snapshot.counters.rooms} rooms, ${snapshot.counters.needsInput} need input`));
50
- for (const room of snapshot.rooms) {
51
- console.log(`${chalk.cyan(room.name)} ${chalk.gray(`${room.counts.agents} agents, ${room.counts.running} running, ${room.counts.needsInput} need input`)}`);
52
- }
53
- }
54
- catch (err) {
55
- die(err.message);
56
- }
57
- });
58
- }
@@ -1,17 +0,0 @@
1
- /**
2
- * `agents sessions sync` — push this machine's transcripts to R2 and pull every
3
- * other machine's, merging copies of the same session via CRDT union. The local
4
- * sessions index is rebuilt from the synced-in mirror by the normal scanner.
5
- */
6
- import type { Command } from 'commander';
7
- interface SyncCmdOptions {
8
- verbose?: boolean;
9
- json?: boolean;
10
- enable?: boolean;
11
- disable?: boolean;
12
- status?: boolean;
13
- setup?: boolean;
14
- }
15
- export declare function runSessionsSync(options: SyncCmdOptions): Promise<void>;
16
- export declare function registerSessionsSyncCommand(sessionsCmd: Command): void;
17
- export {};
@@ -1,135 +0,0 @@
1
- /**
2
- * `agents sessions sync` — push this machine's transcripts to R2 and pull every
3
- * other machine's, merging copies of the same session via CRDT union. The local
4
- * sessions index is rebuilt from the synced-in mirror by the normal scanner.
5
- */
6
- import chalk from 'chalk';
7
- import { setHelpSections } from '../lib/help.js';
8
- import { isSyncConfigured, SYNC_BUNDLE } from '../lib/session/sync/config.js';
9
- import { isBetaEnabled, setBetaEnabled, betaEnableHint } from '../lib/beta.js';
10
- import { syncSessions } from '../lib/session/sync/sync.js';
11
- /** The daemon's automatic session sync is gated by this beta feature. */
12
- const SYNC_BETA = 'session-sync';
13
- export async function runSessionsSync(options) {
14
- // Toggle / status delegate to the `session-sync` beta feature — the single
15
- // source of truth for whether the daemon auto-syncs (opt-in, off by default).
16
- // These short-circuit before any network cycle.
17
- if (options.disable) {
18
- setBetaEnabled([SYNC_BETA], false);
19
- console.log(chalk.yellow('Automatic session sync disabled') +
20
- chalk.dim(' — the daemon stops pushing/pulling within ~90s. (Same as: agents beta disable session-sync)'));
21
- return;
22
- }
23
- if (options.enable) {
24
- setBetaEnabled([SYNC_BETA], true);
25
- console.log(chalk.green('Automatic session sync enabled') +
26
- chalk.dim(' — the daemon resumes on its next cycle. (Same as: agents beta enable session-sync)'));
27
- return;
28
- }
29
- if (options.setup) {
30
- const { promptAndProvisionSessionSync } = await import('./sync-provision.js');
31
- await promptAndProvisionSessionSync({ explicit: true });
32
- return;
33
- }
34
- if (options.status) {
35
- const enabled = isBetaEnabled(SYNC_BETA);
36
- const configured = isSyncConfigured();
37
- if (options.json) {
38
- console.log(JSON.stringify({ enabled, configured }, null, 2));
39
- }
40
- else {
41
- console.log(`automatic sync: ${enabled ? chalk.green('enabled (beta)') : chalk.yellow('disabled')}` +
42
- chalk.dim(' · ') +
43
- `credentials: ${configured ? chalk.green('configured') : chalk.yellow(`missing (${SYNC_BUNDLE})`)}`);
44
- if (!enabled)
45
- console.log(chalk.dim(` ${betaEnableHint(SYNC_BETA)}`));
46
- }
47
- return;
48
- }
49
- if (!isSyncConfigured()) {
50
- console.error(chalk.red(`Sessions sync is not configured.`) +
51
- `\nAdd R2 credentials to the '${SYNC_BUNDLE}' bundle:\n` +
52
- ` agents secrets add ${SYNC_BUNDLE} R2_ACCOUNT_ID\n` +
53
- ` agents secrets add ${SYNC_BUNDLE} R2_BUCKET_NAME\n` +
54
- ` agents secrets add ${SYNC_BUNDLE} R2_ACCESS_KEY_ID\n` +
55
- ` agents secrets add ${SYNC_BUNDLE} R2_SECRET_ACCESS_KEY\n` +
56
- chalk.dim('\nOr let a guided prompt mint the bundle for you: ') + chalk.cyan('agents sessions sync --setup'));
57
- process.exitCode = 1;
58
- return;
59
- }
60
- try {
61
- const result = await syncSessions({
62
- verbose: options.verbose,
63
- log: msg => console.error(chalk.dim(msg)),
64
- });
65
- if (options.json) {
66
- console.log(JSON.stringify(result, null, 2));
67
- }
68
- else {
69
- const parts = [
70
- `pushed ${result.pushed}`,
71
- `pulled ${result.pulled}`,
72
- result.merged > 0 ? `merged ${result.merged}` : null,
73
- ].filter(Boolean);
74
- console.log(chalk.green('synced') + ` ${result.machine}: ` + parts.join(', ') +
75
- chalk.dim(` (${result.pushSkipped + result.pullSkipped} unchanged)`));
76
- }
77
- if (!options.json && result.warnings.length > 0) {
78
- for (const w of result.warnings)
79
- console.error(chalk.yellow(` warning: ${w}`));
80
- }
81
- if (result.errors.length > 0) {
82
- for (const e of result.errors)
83
- console.error(chalk.yellow(` ! ${e}`));
84
- process.exitCode = 1;
85
- }
86
- }
87
- catch (err) {
88
- console.error(chalk.red(`sync failed: ${err.message}`));
89
- process.exitCode = 1;
90
- }
91
- }
92
- export function registerSessionsSyncCommand(sessionsCmd) {
93
- const syncCmd = sessionsCmd
94
- .command('sync')
95
- .description('Sync session transcripts across machines via R2 (CRDT merge). Claude, Codex, Droid, Grok, Kimi, and OpenCode.')
96
- .option('-v, --verbose', 'Log each pushed and pulled session')
97
- .option('--json', 'Output the sync result as JSON')
98
- .option('--setup', 'Guided provisioning: mint the r2.backups bundle, verify connectivity, and enable sync')
99
- .option('--enable', 'Opt in to automatic background sync (beta; alias for: agents beta enable session-sync)')
100
- .option('--disable', 'Opt out of automatic background sync (alias for: agents beta disable session-sync)')
101
- .option('--status', 'Show whether automatic sync is opted-in (beta) and configured');
102
- setHelpSections(syncCmd, {
103
- examples: `
104
- # Guided first-time setup (mint R2 bundle, verify, enable)
105
- agents sessions sync --setup
106
-
107
- # One sync cycle (push local changes, pull + merge from other machines)
108
- agents sessions sync
109
-
110
- # See exactly what moved
111
- agents sessions sync --verbose
112
-
113
- # Stop this machine's daemon from auto-syncing (prefer on-demand --host reads)
114
- agents sessions sync --disable
115
-
116
- # Check the current switch + credential state
117
- agents sessions sync --status
118
- `,
119
- notes: `
120
- - Credentials come from the '${SYNC_BUNDLE}' secrets bundle (R2 S3 API, read+write).
121
- - Each machine writes only its own prefix; conflicts are impossible by construction.
122
- - Sessions present locally always win; synced-in copies fill in other machines' sessions.
123
- - Automatic background sync is an opt-in BETA feature, OFF by default. The daemon only
124
- syncs (~90s) once you opt in via 'agents beta enable session-sync' (or the --enable
125
- alias here). A bare 'agents sessions sync' always forces a manual one-shot cycle
126
- regardless of the beta opt-in.
127
- `,
128
- });
129
- // `--json` is also declared on the parent `sessions` command, so a bare
130
- // `options` arg would miss it (Commander binds the shared flag to the parent).
131
- // optsWithGlobals() merges ancestor + local options so --json resolves here.
132
- syncCmd.action(async (_options, cmd) => {
133
- await runSessionsSync(cmd.optsWithGlobals());
134
- });
135
- }
@@ -1,23 +0,0 @@
1
- /**
2
- * Interactive provisioning flow for cross-machine session sync. Collects R2
3
- * credentials, writes the `r2.backups` bundle (via the pure lib helper), probes
4
- * connectivity, and opts the machine into the `session-sync` beta. Shared by
5
- * `agents setup` (offered, opt-in) and `agents sessions sync --setup` (explicit).
6
- *
7
- * The prompt/UI lives here in the command layer; the credential-writing and
8
- * connectivity logic is the pure, unit-tested `lib/session/sync/provision.ts`.
9
- */
10
- export interface ProvisionFlowOptions {
11
- /**
12
- * True when invoked explicitly (`agents sessions sync --setup`): we go straight
13
- * into provisioning. False when offered inside `agents setup`: we ask first,
14
- * default to No, and silently skip when already configured.
15
- */
16
- explicit?: boolean;
17
- }
18
- /**
19
- * Run the guided session-sync setup. Never throws for expected outcomes
20
- * (non-interactive shell, user declines, cancels, or a failed probe) — returns
21
- * quietly so a first-run `agents setup` is never blocked by the optional step.
22
- */
23
- export declare function promptAndProvisionSessionSync(opts?: ProvisionFlowOptions): Promise<void>;
@@ -1,107 +0,0 @@
1
- /**
2
- * Interactive provisioning flow for cross-machine session sync. Collects R2
3
- * credentials, writes the `r2.backups` bundle (via the pure lib helper), probes
4
- * connectivity, and opts the machine into the `session-sync` beta. Shared by
5
- * `agents setup` (offered, opt-in) and `agents sessions sync --setup` (explicit).
6
- *
7
- * The prompt/UI lives here in the command layer; the credential-writing and
8
- * connectivity logic is the pure, unit-tested `lib/session/sync/provision.ts`.
9
- */
10
- import chalk from 'chalk';
11
- import ora from 'ora';
12
- import { isInteractiveTerminal, isPromptCancelled } from './utils.js';
13
- import { isSyncConfigured } from '../lib/session/sync/config.js';
14
- import { writeSyncBundle, probeR2Connectivity, readStoredEncKey } from '../lib/session/sync/provision.js';
15
- import { setBetaEnabled } from '../lib/beta.js';
16
- const SYNC_BETA = 'session-sync';
17
- const nonEmpty = (v) => (v.trim().length > 0 ? true : 'required');
18
- /**
19
- * Run the guided session-sync setup. Never throws for expected outcomes
20
- * (non-interactive shell, user declines, cancels, or a failed probe) — returns
21
- * quietly so a first-run `agents setup` is never blocked by the optional step.
22
- */
23
- export async function promptAndProvisionSessionSync(opts = {}) {
24
- if (!isInteractiveTerminal()) {
25
- if (opts.explicit)
26
- console.error(chalk.red('Session-sync setup needs an interactive terminal.'));
27
- return;
28
- }
29
- const alreadyConfigured = isSyncConfigured();
30
- const { confirm, input, password } = await import('@inquirer/prompts');
31
- try {
32
- if (!opts.explicit) {
33
- if (alreadyConfigured)
34
- return; // first-run setup: nothing to do
35
- const want = await confirm({
36
- message: 'Set up cross-machine session sync (encrypted transcripts via Cloudflare R2)?',
37
- default: false,
38
- });
39
- if (!want)
40
- return;
41
- }
42
- else if (alreadyConfigured) {
43
- const reconfigure = await confirm({
44
- message: 'Session sync is already configured. Re-enter R2 credentials?',
45
- default: false,
46
- });
47
- if (!reconfigure) {
48
- const key = readStoredEncKey();
49
- if (key) {
50
- console.log(chalk.dim('\nShared encryption key (paste on every other machine you sync):'));
51
- console.log(' ' + chalk.cyan(key));
52
- }
53
- return;
54
- }
55
- }
56
- console.log(chalk.dim('\nR2 credentials — Cloudflare dashboard > R2 > Manage API Tokens (needs read+write):'));
57
- const accountId = (await input({ message: 'R2 account ID:', validate: nonEmpty })).trim();
58
- const bucketName = (await input({ message: 'R2 bucket name:', validate: nonEmpty })).trim();
59
- const accessKeyId = (await password({ message: 'R2 access key ID:', mask: true })).trim();
60
- const secretAccessKey = (await password({ message: 'R2 secret access key:', mask: true })).trim();
61
- const endpoint = (await input({
62
- message: 'S3 endpoint override (blank = Cloudflare R2):',
63
- default: '',
64
- })).trim();
65
- // Encryption key: the first machine mints one; every other machine pastes it
66
- // so the whole fabric shares a single key (and can decrypt each other).
67
- const firstMachine = await confirm({ message: 'Is this the FIRST machine in your sync fabric?', default: true });
68
- let encKey;
69
- if (!firstMachine) {
70
- encKey = (await password({
71
- message: 'Paste the shared R2_SYNC_ENC_KEY from your first machine:',
72
- mask: true,
73
- validate: nonEmpty,
74
- })).trim();
75
- }
76
- const { encKeyAction } = writeSyncBundle({
77
- accountId, bucketName, accessKeyId, secretAccessKey,
78
- endpoint: endpoint || undefined,
79
- encKey: encKey || undefined,
80
- });
81
- const spinner = ora('Validating R2 read+write...').start();
82
- const probe = await probeR2Connectivity();
83
- if (!probe.ok) {
84
- spinner.fail(`R2 probe failed: ${probe.error}`);
85
- console.log(chalk.yellow('Credentials were saved to the r2.backups bundle but not verified. Fix them and re-run ' +
86
- '`agents sessions sync --setup`, or rotate one key with `agents secrets rotate r2.backups <KEY>`.'));
87
- return; // do not auto-enable sync against credentials that don't work
88
- }
89
- spinner.succeed('R2 read+write verified.');
90
- setBetaEnabled([SYNC_BETA], true);
91
- console.log(chalk.green('\nSession sync configured and enabled') + chalk.dim(' (the daemon syncs every ~90s).'));
92
- if (encKeyAction === 'generated') {
93
- const key = readStoredEncKey();
94
- console.log(chalk.bold('\nShared encryption key — paste this on every OTHER machine you sync:'));
95
- console.log(' ' + chalk.cyan(key ?? '(unavailable)'));
96
- console.log(chalk.dim('Anyone with this key can decrypt your transcripts. Keep it secret.'));
97
- }
98
- console.log(chalk.dim('\nSync now with: agents sessions sync'));
99
- }
100
- catch (err) {
101
- if (isPromptCancelled(err)) {
102
- console.log(chalk.yellow('\nSession-sync setup cancelled.'));
103
- return;
104
- }
105
- throw err;
106
- }
107
- }
@@ -1,45 +0,0 @@
1
- /**
2
- * Remote drive sync for agent sessions and config.
3
- *
4
- * Provides rsync-based push/pull between the local ~/.agents/drive/
5
- * directory and a remote host, plus attach/detach to swap the active
6
- * agent's config directory symlink to the drive directory (for working
7
- * with a remote machine's session data locally).
8
- */
9
- /** Persisted drive configuration stored at ~/.agents/drive/config.json. */
10
- export interface DriveConfig {
11
- remote: string | null;
12
- attached: boolean;
13
- previousTargets: {
14
- configDir: string;
15
- homeFiles: Record<string, string>;
16
- } | null;
17
- lastPull: string | null;
18
- lastPush: string | null;
19
- }
20
- /** Read drive config from disk, returning defaults if missing. */
21
- export declare function readDriveConfig(): DriveConfig;
22
- /** Write drive config to disk. */
23
- export declare function writeDriveConfig(config: DriveConfig): void;
24
- /** Set the remote target (user@host) for rsync operations. */
25
- export declare function setRemote(target: string): void;
26
- /** Pull drive data from the remote host via rsync. */
27
- export declare function pull(): Promise<void>;
28
- /** Push local drive data to the remote host via rsync. */
29
- export declare function push(): Promise<void>;
30
- /** Attach drive by swapping the agent's config directory symlink to the drive directory. */
31
- export declare function attach(): void;
32
- /** Detach drive by restoring the agent's config directory to its previous symlink target. */
33
- export declare function detach(): void;
34
- /** Current drive state for display purposes. */
35
- export interface DriveStatus {
36
- remote: string | null;
37
- attached: boolean;
38
- lastPull: string | null;
39
- lastPush: string | null;
40
- driveDir: string;
41
- configDirTarget: string | null;
42
- homeFileTargets: Record<string, string | null>;
43
- }
44
- /** Gather current drive status by inspecting config, symlinks, and timestamps. */
45
- export declare function getDriveStatus(): DriveStatus;
@@ -1,238 +0,0 @@
1
- /**
2
- * Remote drive sync for agent sessions and config.
3
- *
4
- * Provides rsync-based push/pull between the local ~/.agents/drive/
5
- * directory and a remote host, plus attach/detach to swap the active
6
- * agent's config directory symlink to the drive directory (for working
7
- * with a remote machine's session data locally).
8
- */
9
- import * as fs from 'fs';
10
- import * as path from 'path';
11
- import * as os from 'os';
12
- import { execFile } from 'child_process';
13
- import { promisify } from 'util';
14
- import { getDriveDir } from './state.js';
15
- import { AGENTS } from './agents.js';
16
- import { sshExec } from './ssh-exec.js';
17
- const execFileAsync = promisify(execFile);
18
- // `remote` flows from disk into rsync/ssh argv. Use a strict regex so a
19
- // tampered ~/.agents/drive/config.json can't sneak shell metacharacters or
20
- // argv flags (leading -) past the boundary.
21
- const REMOTE_RE = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+$/;
22
- function assertValidRemote(remote) {
23
- if (!REMOTE_RE.test(remote)) {
24
- throw new Error(`Invalid drive remote: ${JSON.stringify(remote)}. Expected: user@host`);
25
- }
26
- }
27
- const AGENT = 'claude';
28
- function configPath() {
29
- return path.join(getDriveDir(), 'config.json');
30
- }
31
- /** Read drive config from disk, returning defaults if missing. */
32
- export function readDriveConfig() {
33
- const p = configPath();
34
- if (fs.existsSync(p)) {
35
- try {
36
- const parsed = JSON.parse(fs.readFileSync(p, 'utf-8'));
37
- // Re-validate `remote` on every read. setRemote validates on write, but
38
- // the file can be tampered with out-of-band (a malicious skill, a synced
39
- // config from a hostile repo, etc.) and pull/push shell out with the value.
40
- if (parsed.remote != null) {
41
- assertValidRemote(parsed.remote);
42
- }
43
- return parsed;
44
- }
45
- catch (err) {
46
- // If the config is malformed or has a tainted remote, fail closed rather
47
- // than silently fall back to defaults — a tainted remote that fell back
48
- // to null would mask the attack.
49
- if (err instanceof SyntaxError) {
50
- // Bad JSON: fall through to defaults.
51
- }
52
- else {
53
- throw err;
54
- }
55
- }
56
- }
57
- return { remote: null, attached: false, previousTargets: null, lastPull: null, lastPush: null };
58
- }
59
- /** Write drive config to disk. */
60
- export function writeDriveConfig(config) {
61
- const dir = getDriveDir();
62
- if (!fs.existsSync(dir)) {
63
- fs.mkdirSync(dir, { recursive: true });
64
- }
65
- fs.writeFileSync(configPath(), JSON.stringify(config, null, 2));
66
- }
67
- /** Set the remote target (user@host) for rsync operations. */
68
- export function setRemote(target) {
69
- assertValidRemote(target);
70
- const config = readDriveConfig();
71
- config.remote = target;
72
- writeDriveConfig(config);
73
- }
74
- /** Pull drive data from the remote host via rsync. */
75
- export async function pull() {
76
- const config = readDriveConfig();
77
- if (!config.remote)
78
- throw new Error('No remote configured. Run: agents drive remote <user@host>');
79
- assertValidRemote(config.remote);
80
- const localDir = getDriveDir() + '/';
81
- const remoteSpec = `${config.remote}:~/.agents/drive/`;
82
- // Argv form: no shell, no interpolation — even a tainted `config.remote` that
83
- // somehow got past the regex cannot escape into command syntax.
84
- await execFileAsync('rsync', ['-az', '--exclude=config.json', remoteSpec, localDir]);
85
- config.lastPull = new Date().toISOString();
86
- writeDriveConfig(config);
87
- }
88
- /** Push local drive data to the remote host via rsync. */
89
- export async function push() {
90
- const config = readDriveConfig();
91
- if (!config.remote)
92
- throw new Error('No remote configured. Run: agents drive remote <user@host>');
93
- assertValidRemote(config.remote);
94
- const localDir = getDriveDir() + '/';
95
- const remoteSpec = `${config.remote}:~/.agents/drive/`;
96
- // Ensure remote directory exists via the shared hardened SSH primitive.
97
- const mkdir = sshExec(config.remote, 'mkdir -p ~/.agents/drive', { timeoutMs: 30_000 });
98
- if (mkdir.code !== 0) {
99
- throw new Error(`Failed to prepare remote drive directory on ${config.remote}${mkdir.stderr.trim() ? `: ${mkdir.stderr.trim()}` : ''}`);
100
- }
101
- await execFileAsync('rsync', ['-az', '--exclude=config.json', localDir, remoteSpec]);
102
- config.lastPush = new Date().toISOString();
103
- writeDriveConfig(config);
104
- }
105
- /** Attach drive by swapping the agent's config directory symlink to the drive directory. */
106
- export function attach() {
107
- const config = readDriveConfig();
108
- if (config.attached)
109
- throw new Error('Drive is already attached');
110
- const home = os.homedir();
111
- const agentConfig = AGENTS[AGENT];
112
- const driveDir = getDriveDir();
113
- const configDirPath = agentConfig.configDir; // ~/.claude
114
- const driveConfigDir = path.join(driveDir, `.${AGENT}`); // ~/.agents/drive/.claude
115
- // Read current symlink target
116
- let prevConfigDir = null;
117
- try {
118
- const stat = fs.lstatSync(configDirPath);
119
- if (stat.isSymbolicLink()) {
120
- prevConfigDir = fs.readlinkSync(configDirPath);
121
- }
122
- }
123
- catch {
124
- // Path doesn't exist
125
- }
126
- if (!prevConfigDir) {
127
- throw new Error(`${configDirPath} is not a symlink. Run 'agents use claude' first.`);
128
- }
129
- // Save previous targets for home files
130
- const prevHomeFiles = {};
131
- for (const hf of agentConfig.homeFiles || []) {
132
- const hfPath = path.join(home, hf);
133
- try {
134
- const stat = fs.lstatSync(hfPath);
135
- if (stat.isSymbolicLink()) {
136
- prevHomeFiles[hf] = fs.readlinkSync(hfPath);
137
- }
138
- }
139
- catch {
140
- // File doesn't exist
141
- }
142
- }
143
- config.previousTargets = {
144
- configDir: prevConfigDir,
145
- homeFiles: prevHomeFiles,
146
- };
147
- // Ensure drive config dir exists
148
- if (!fs.existsSync(driveConfigDir)) {
149
- fs.mkdirSync(driveConfigDir, { recursive: true });
150
- }
151
- // Swap config dir symlink
152
- fs.unlinkSync(configDirPath);
153
- fs.symlinkSync(driveConfigDir, configDirPath);
154
- // Swap home files
155
- for (const hf of agentConfig.homeFiles || []) {
156
- const hfPath = path.join(home, hf);
157
- const driveHfPath = path.join(driveDir, hf);
158
- if (!fs.existsSync(driveHfPath)) {
159
- fs.writeFileSync(driveHfPath, '{}');
160
- }
161
- try {
162
- fs.unlinkSync(hfPath);
163
- }
164
- catch { /* doesn't exist */ }
165
- fs.symlinkSync(driveHfPath, hfPath);
166
- }
167
- config.attached = true;
168
- writeDriveConfig(config);
169
- }
170
- /** Detach drive by restoring the agent's config directory to its previous symlink target. */
171
- export function detach() {
172
- const config = readDriveConfig();
173
- if (!config.attached)
174
- throw new Error('Drive is not attached');
175
- if (!config.previousTargets)
176
- throw new Error('No previous targets saved');
177
- const home = os.homedir();
178
- const agentConfig = AGENTS[AGENT];
179
- // Restore config dir symlink
180
- const configDirPath = agentConfig.configDir;
181
- fs.unlinkSync(configDirPath);
182
- fs.symlinkSync(config.previousTargets.configDir, configDirPath);
183
- // Restore home files
184
- for (const hf of agentConfig.homeFiles || []) {
185
- const hfPath = path.join(home, hf);
186
- const prevTarget = config.previousTargets.homeFiles[hf];
187
- if (prevTarget) {
188
- try {
189
- fs.unlinkSync(hfPath);
190
- }
191
- catch { /* doesn't exist */ }
192
- fs.symlinkSync(prevTarget, hfPath);
193
- }
194
- }
195
- config.attached = false;
196
- config.previousTargets = null;
197
- writeDriveConfig(config);
198
- }
199
- /** Gather current drive status by inspecting config, symlinks, and timestamps. */
200
- export function getDriveStatus() {
201
- const config = readDriveConfig();
202
- const home = os.homedir();
203
- const agentConfig = AGENTS[AGENT];
204
- let configDirTarget = null;
205
- try {
206
- const stat = fs.lstatSync(agentConfig.configDir);
207
- if (stat.isSymbolicLink()) {
208
- configDirTarget = fs.readlinkSync(agentConfig.configDir);
209
- }
210
- }
211
- catch {
212
- // Not a symlink or doesn't exist
213
- }
214
- const homeFileTargets = {};
215
- for (const hf of agentConfig.homeFiles || []) {
216
- try {
217
- const stat = fs.lstatSync(path.join(home, hf));
218
- if (stat.isSymbolicLink()) {
219
- homeFileTargets[hf] = fs.readlinkSync(path.join(home, hf));
220
- }
221
- else {
222
- homeFileTargets[hf] = null;
223
- }
224
- }
225
- catch {
226
- homeFileTargets[hf] = null;
227
- }
228
- }
229
- return {
230
- remote: config.remote,
231
- attached: config.attached,
232
- lastPull: config.lastPull,
233
- lastPush: config.lastPush,
234
- driveDir: getDriveDir(),
235
- configDirTarget,
236
- homeFileTargets,
237
- };
238
- }