@phnx-labs/agents-cli 1.23.17 → 1.23.18

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 (204) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +140 -165
  3. package/dist/bootstrap.js +10 -16
  4. package/dist/cli/command-registry.d.ts +1 -2
  5. package/dist/cli/command-registry.js +1 -10
  6. package/dist/commands/accounts.js +7 -7
  7. package/dist/commands/cloud-transcripts.d.ts +0 -1
  8. package/dist/commands/cloud-transcripts.js +2 -2
  9. package/dist/commands/cloud.js +1 -1
  10. package/dist/commands/config.js +0 -4
  11. package/dist/commands/cost.js +1 -1
  12. package/dist/commands/daemon-index.js +0 -1
  13. package/dist/commands/detach.d.ts +1 -1
  14. package/dist/commands/detach.js +5 -5
  15. package/dist/commands/exec.js +10 -22
  16. package/dist/commands/feed.d.ts +1 -1
  17. package/dist/commands/feed.js +3 -3
  18. package/dist/commands/focus.d.ts +1 -4
  19. package/dist/commands/focus.js +12 -13
  20. package/dist/commands/fork.d.ts +0 -1
  21. package/dist/commands/fork.js +7 -16
  22. package/dist/commands/harness-wizard.js +1 -1
  23. package/dist/commands/harness.js +1 -1
  24. package/dist/commands/insights.d.ts +0 -1
  25. package/dist/commands/insights.js +3 -7
  26. package/dist/commands/open.js +1 -1
  27. package/dist/commands/output.js +1 -1
  28. package/dist/commands/profiles.d.ts +1 -1
  29. package/dist/commands/profiles.js +2 -2
  30. package/dist/commands/projects.js +1 -1
  31. package/dist/commands/prune.js +1 -1
  32. package/dist/commands/ps.d.ts +0 -1
  33. package/dist/commands/ps.js +63 -18
  34. package/dist/commands/routines.js +1 -1
  35. package/dist/commands/send.js +1 -1
  36. package/dist/commands/sessions-backfill.d.ts +0 -1
  37. package/dist/commands/sessions-backfill.js +3 -6
  38. package/dist/commands/sessions-browser.d.ts +0 -10
  39. package/dist/commands/sessions-browser.js +19 -25
  40. package/dist/commands/sessions-migrate.d.ts +2 -2
  41. package/dist/commands/sessions-migrate.js +13 -13
  42. package/dist/commands/sessions-optimize.d.ts +0 -1
  43. package/dist/commands/sessions-optimize.js +0 -3
  44. package/dist/commands/sessions-picker.js +11 -11
  45. package/dist/commands/sessions-resume.d.ts +16 -15
  46. package/dist/commands/sessions-resume.js +101 -269
  47. package/dist/commands/sessions-stats.d.ts +0 -1
  48. package/dist/commands/sessions-stats.js +5 -8
  49. package/dist/commands/sessions-stop.d.ts +1 -1
  50. package/dist/commands/sessions-stop.js +6 -6
  51. package/dist/commands/sessions-trace.d.ts +1 -1
  52. package/dist/commands/sessions-trace.js +40 -17
  53. package/dist/commands/sessions-watch.js +2 -2
  54. package/dist/commands/sessions.test-fixture.d.ts +1 -0
  55. package/dist/commands/sessions.test-fixture.js +14 -0
  56. package/dist/commands/setup-browser.js +4 -4
  57. package/dist/commands/setup-computer.js +4 -4
  58. package/dist/commands/setup-fleet.js +1 -1
  59. package/dist/commands/setup-preferences.js +1 -1
  60. package/dist/commands/{sessions-backup-setup.d.ts → setup-session-backup.d.ts} +2 -2
  61. package/dist/commands/{sessions-backup-setup.js → setup-session-backup.js} +8 -8
  62. package/dist/commands/setup.js +3 -1
  63. package/dist/commands/ssh.js +4 -5
  64. package/dist/commands/sync.js +1 -1
  65. package/dist/commands/teams.js +2 -2
  66. package/dist/commands/utils.d.ts +0 -1
  67. package/dist/commands/utils.js +0 -10
  68. package/dist/index.js +0 -71
  69. package/dist/lib/analytics/mix-commands.js +1 -1
  70. package/dist/lib/auth-mint.js +2 -2
  71. package/dist/lib/browser-client.d.ts +0 -1
  72. package/dist/lib/browser-client.js +0 -3
  73. package/dist/lib/cloud/antigravity.js +1 -1
  74. package/dist/lib/cloud/cursor.js +3 -3
  75. package/dist/lib/cloudflare/creds.js +2 -2
  76. package/dist/lib/computer/context.d.ts +4 -21
  77. package/dist/lib/computer/context.js +3 -24
  78. package/dist/lib/computer/policy.d.ts +0 -10
  79. package/dist/lib/computer/policy.js +0 -28
  80. package/dist/lib/computer-client.d.ts +0 -44
  81. package/dist/lib/computer-client.js +17 -121
  82. package/dist/lib/config-keys.d.ts +1 -1
  83. package/dist/lib/config-keys.js +0 -3
  84. package/dist/lib/crabbox/cli.js +1 -1
  85. package/dist/lib/device-config.js +5 -28
  86. package/dist/lib/devices/connect.d.ts +1 -1
  87. package/dist/lib/devices/connect.js +3 -6
  88. package/dist/lib/devices/doctor-findings.d.ts +2 -1
  89. package/dist/lib/devices/doctor-findings.js +4 -4
  90. package/dist/lib/exec.js +1 -1
  91. package/dist/lib/feed/activity.js +1 -1
  92. package/dist/lib/fleet/apply.js +1 -1
  93. package/dist/lib/help.d.ts +0 -1
  94. package/dist/lib/help.js +2 -10
  95. package/dist/lib/hosts/option.js +1 -1
  96. package/dist/lib/hosts/passthrough.d.ts +0 -1
  97. package/dist/lib/hosts/passthrough.js +2 -26
  98. package/dist/lib/hosts/reconnect.js +5 -5
  99. package/dist/lib/hosts/remote-cmd.d.ts +3 -5
  100. package/dist/lib/hosts/remote-cmd.js +15 -20
  101. package/dist/lib/hosts/remote-session-id.js +1 -1
  102. package/dist/lib/installations/active-check.js +1 -1
  103. package/dist/lib/installations/migrate.js +4 -15
  104. package/dist/lib/installations/versions.js +1 -1
  105. package/dist/lib/launch-log.js +3 -6
  106. package/dist/lib/owner-notify.d.ts +1 -6
  107. package/dist/lib/owner-notify.js +0 -2
  108. package/dist/lib/paths.d.ts +0 -1
  109. package/dist/lib/paths.js +0 -8
  110. package/dist/lib/permissions.js +1 -1
  111. package/dist/lib/redact.d.ts +0 -1
  112. package/dist/lib/redact.js +0 -4
  113. package/dist/lib/remote-agents-json.d.ts +3 -1
  114. package/dist/lib/remote-agents-json.js +8 -6
  115. package/dist/lib/reserved-stores.js +1 -1
  116. package/dist/lib/scheduling/routines.d.ts +0 -1
  117. package/dist/lib/scheduling/routines.js +1 -1
  118. package/dist/lib/session/active.d.ts +1 -1
  119. package/dist/lib/session/db.js +3 -3
  120. package/dist/lib/session/detached.d.ts +0 -1
  121. package/dist/lib/session/detached.js +0 -23
  122. package/dist/lib/session/discover.d.ts +2 -2
  123. package/dist/lib/session/presentation.d.ts +0 -7
  124. package/dist/lib/session/presentation.js +4 -4
  125. package/dist/lib/session/projection.js +1 -1
  126. package/dist/lib/session/remote/remote-list.d.ts +2 -0
  127. package/dist/lib/session/remote/remote-list.js +3 -2
  128. package/dist/lib/session/remote/watch.js +4 -5
  129. package/dist/lib/session/remote-active.js +1 -1
  130. package/dist/lib/session/resume-command.d.ts +0 -1
  131. package/dist/lib/session/resume-command.js +1 -4
  132. package/dist/lib/session/resume-owner.d.ts +0 -2
  133. package/dist/lib/session/resume-owner.js +0 -6
  134. package/dist/lib/session/selection.d.ts +4 -5
  135. package/dist/lib/session/selection.js +2 -2
  136. package/dist/lib/session/sync/config.d.ts +0 -25
  137. package/dist/lib/session/sync/config.js +0 -62
  138. package/dist/lib/session/sync/managed-config.d.ts +0 -1
  139. package/dist/lib/session/sync/managed-config.js +0 -3
  140. package/dist/lib/session/sync/worker-template.js +1 -1
  141. package/dist/lib/sessions-client.d.ts +0 -16
  142. package/dist/lib/sessions-client.js +1 -187
  143. package/dist/lib/startup/command-registry.d.ts +2 -0
  144. package/dist/lib/startup/command-registry.js +36 -3
  145. package/dist/lib/startup/root-command.d.ts +0 -1
  146. package/dist/lib/startup/root-command.js +0 -21
  147. package/dist/lib/sync-umbrella.js +1 -1
  148. package/dist/lib/terminal/resolve.js +1 -1
  149. package/dist/lib/watchdog/rotate.js +1 -1
  150. package/dist/lib/watchdog/watchdog.d.ts +1 -1
  151. package/dist/lib/watchdog/watchdog.js +2 -2
  152. package/package.json +1 -1
  153. package/dist/commands/browser.d.ts +0 -7
  154. package/dist/commands/browser.js +0 -139
  155. package/dist/commands/computer.d.ts +0 -48
  156. package/dist/commands/computer.js +0 -244
  157. package/dist/commands/resume.d.ts +0 -23
  158. package/dist/commands/resume.js +0 -158
  159. package/dist/commands/secrets-passthrough.d.ts +0 -3
  160. package/dist/commands/secrets-passthrough.js +0 -52
  161. package/dist/commands/sessions-bookmark.d.ts +0 -2
  162. package/dist/commands/sessions-bookmark.js +0 -92
  163. package/dist/commands/sessions-export.d.ts +0 -31
  164. package/dist/commands/sessions-export.js +0 -409
  165. package/dist/commands/sessions-import.d.ts +0 -6
  166. package/dist/commands/sessions-import.js +0 -343
  167. package/dist/commands/sessions-inject.d.ts +0 -14
  168. package/dist/commands/sessions-inject.js +0 -143
  169. package/dist/commands/sessions-picker-factory.d.ts +0 -24
  170. package/dist/commands/sessions-picker-factory.js +0 -59
  171. package/dist/commands/sessions-render.d.ts +0 -11
  172. package/dist/commands/sessions-render.js +0 -119
  173. package/dist/commands/sessions-share.d.ts +0 -15
  174. package/dist/commands/sessions-share.js +0 -171
  175. package/dist/commands/sessions.d.ts +0 -122
  176. package/dist/commands/sessions.js +0 -1760
  177. package/dist/lib/address.d.ts +0 -39
  178. package/dist/lib/address.js +0 -128
  179. package/dist/lib/computer/record.d.ts +0 -6
  180. package/dist/lib/computer/record.js +0 -25
  181. package/dist/lib/openclaw-keychain.d.ts +0 -43
  182. package/dist/lib/openclaw-keychain.js +0 -227
  183. package/dist/lib/session/bundle.d.ts +0 -76
  184. package/dist/lib/session/bundle.js +0 -146
  185. package/dist/lib/session/remote/remote-bundle.d.ts +0 -7
  186. package/dist/lib/session/remote/remote-bundle.js +0 -40
  187. package/dist/lib/session/remote/remote.d.ts +0 -35
  188. package/dist/lib/session/remote/remote.js +0 -198
  189. package/dist/lib/session/remote-bundle.d.ts +0 -1
  190. package/dist/lib/session/remote-bundle.js +0 -1
  191. package/dist/lib/session/remote.d.ts +0 -1
  192. package/dist/lib/session/remote.js +0 -1
  193. package/dist/lib/session/sync/agents.d.ts +0 -24
  194. package/dist/lib/session/sync/agents.js +0 -0
  195. package/dist/lib/session/sync/backend.d.ts +0 -22
  196. package/dist/lib/session/sync/backend.js +0 -44
  197. package/dist/lib/session/sync/managed-key.d.ts +0 -5
  198. package/dist/lib/session/sync/managed-key.js +0 -87
  199. package/dist/lib/session/sync/net-client.d.ts +0 -29
  200. package/dist/lib/session/sync/net-client.js +0 -87
  201. package/dist/lib/session/sync/r2.d.ts +0 -20
  202. package/dist/lib/session/sync/r2.js +0 -103
  203. package/dist/lib/session/sync/transcript-crypto.d.ts +0 -41
  204. package/dist/lib/session/sync/transcript-crypto.js +0 -115
@@ -1,52 +0,0 @@
1
- import chalk from 'chalk';
2
- import { spawnSync } from 'node:child_process';
3
- import { buildServeEnv, invocation, resolveSecretsBin, SecretsClientError } from '../lib/secrets-client.js';
4
- import { flagValue } from '../lib/hosts/routing-flag.js';
5
- import { stripRoutingFlags } from '../lib/hosts/remote-cmd.js';
6
- import { resolveRemoteDevice } from '../lib/ssh-tunnel.js';
7
- import { SECRETS_CLI_INSTALL_HINT } from '../lib/secrets-cli.js';
8
- import { forwardsHelp } from '../lib/help.js';
9
- export async function rewriteDeviceToHost(argv) {
10
- if (flagValue(argv, 'host', 'H') !== undefined)
11
- return argv;
12
- const device = flagValue(argv, 'device', 'D');
13
- if (device === undefined)
14
- return argv;
15
- const resolved = await resolveRemoteDevice(device, {});
16
- const stripped = stripRoutingFlags(argv, [{ long: 'device', short: 'D', takesValue: true }]);
17
- return [...stripped, '--host', `ssh://${resolved.target}`];
18
- }
19
- export function registerSecretsCommands(program) {
20
- forwardsHelp(program
21
- .command('secrets')
22
- .description('Named bundles of env variables — passthrough to the standalone `secrets` CLI. Run `agents secrets --help` (or `agents setup secrets`) for the full subcommand list.')
23
- .allowUnknownOption()
24
- .allowExcessArguments()
25
- .action(async () => {
26
- let bin;
27
- try {
28
- bin = resolveSecretsBin();
29
- }
30
- catch (err) {
31
- if (err instanceof SecretsClientError && err.code === 'SECRETS_BIN_MISSING') {
32
- console.error(chalk.red('The standalone `secrets` CLI is not installed.'));
33
- console.error(chalk.gray(`Install it, then re-run this command:`));
34
- console.error(chalk.cyan(` ${SECRETS_CLI_INSTALL_HINT}`));
35
- process.exit(1);
36
- }
37
- throw err;
38
- }
39
- const secretsIndex = process.argv.indexOf('secrets');
40
- const forwarded = await rewriteDeviceToHost(secretsIndex >= 0 ? process.argv.slice(secretsIndex + 1) : []);
41
- const { command, prefix } = invocation(bin);
42
- const res = spawnSync(command, [...prefix, ...forwarded], {
43
- stdio: 'inherit',
44
- env: buildServeEnv(),
45
- });
46
- if (res.error) {
47
- console.error(chalk.red(`Failed to run \`secrets\`: ${res.error.message}`));
48
- process.exit(1);
49
- }
50
- process.exit(res.status ?? 1);
51
- }));
52
- }
@@ -1,2 +0,0 @@
1
- import type { Command } from 'commander';
2
- export declare function registerSessionsBookmarkCommand(sessionsCmd: Command): void;
@@ -1,92 +0,0 @@
1
- import chalk from 'chalk';
2
- import { setHelpSections } from '../lib/help.js';
3
- import { findSessionsById } from '../lib/session/db.js';
4
- import { isCompleteSessionId } from '../lib/session/discover.js';
5
- import { isBookmarked, listBookmarks, setBookmark } from '../lib/session/bookmarks.js';
6
- function resolveBookmarkTarget(idQuery) {
7
- const matches = findSessionsById(idQuery);
8
- if (matches.length === 0) {
9
- return isCompleteSessionId(idQuery.trim())
10
- ? { id: idQuery.trim() }
11
- : { error: `No session matches "${idQuery}".` };
12
- }
13
- if (matches.length > 1) {
14
- const ids = matches.slice(0, 5).map((m) => m.shortId).join(', ');
15
- return { error: `"${idQuery}" matches ${matches.length} sessions (${ids}…) — use a longer id.` };
16
- }
17
- return { id: matches[0].id };
18
- }
19
- export function registerSessionsBookmarkCommand(sessionsCmd) {
20
- const cmd = sessionsCmd
21
- .command('bookmark')
22
- .argument('[ids...]', 'Session ids to bookmark (full or short id prefix)')
23
- .description('Bookmark sessions so they are easy to find again — list them with --bookmarks, or `b` in the browser.')
24
- .option('--remove', 'Remove the given sessions from bookmarks instead of adding them')
25
- .option('--list', 'List the bookmarked sessions (the default when no ids are given)')
26
- .option('--json', 'Output JSON');
27
- setHelpSections(cmd, {
28
- examples: `
29
- # Bookmark a session by its short id (the 8 chars the listing prints)
30
- agents sessions bookmark 26c27162
31
-
32
- # See what is bookmarked
33
- agents sessions bookmark --list
34
-
35
- # Browse only the bookmarked ones
36
- agents sessions --bookmarks
37
-
38
- # Remove it from bookmarks again
39
- agents sessions bookmark 26c27162 --remove
40
- `,
41
- notes: `
42
- In the interactive browser (\`agents sessions\`), \`*\` bookmarks the highlighted
43
- session and \`b\` filters the list down to the bookmarked ones.
44
-
45
- Bookmarks live in ~/.agents/.history/bookmarks.json, keyed by session id, so
46
- they survive a reindex of the session cache. They are per-machine: session
47
- sync carries transcripts, not this file.
48
- `,
49
- });
50
- cmd.action((ids, options, self) => {
51
- const json = self.optsWithGlobals().json === true;
52
- if (options.list || ids.length === 0) {
53
- const bookmarked = [...listBookmarks()].sort();
54
- if (json) {
55
- process.stdout.write(JSON.stringify({ bookmarks: bookmarked }, null, 2) + '\n');
56
- return;
57
- }
58
- if (bookmarked.length === 0) {
59
- console.log(chalk.gray('No bookmarked sessions. Bookmark one with `agents sessions bookmark <id>`.'));
60
- return;
61
- }
62
- for (const id of bookmarked)
63
- console.log(`${chalk.yellow('★')} ${id}`);
64
- console.log(chalk.gray(`\n${bookmarked.length} bookmark${bookmarked.length === 1 ? '' : 's'}.`));
65
- return;
66
- }
67
- const on = !options.remove;
68
- const results = [];
69
- for (const idQuery of ids) {
70
- const resolved = resolveBookmarkTarget(idQuery);
71
- if ('error' in resolved) {
72
- results.push({ query: idQuery, error: resolved.error });
73
- continue;
74
- }
75
- setBookmark(resolved.id, on);
76
- results.push({ query: idQuery, id: resolved.id, bookmark: isBookmarked(resolved.id) });
77
- }
78
- if (json) {
79
- process.stdout.write(JSON.stringify({ results }, null, 2) + '\n');
80
- }
81
- else {
82
- for (const r of results) {
83
- if (r.error)
84
- console.error(chalk.red(r.error));
85
- else
86
- console.log(`${r.bookmark ? chalk.yellow('★ bookmarked') : chalk.gray('☆ unbookmarked')} ${r.id}`);
87
- }
88
- }
89
- if (results.some((r) => r.error))
90
- process.exitCode = 1;
91
- });
92
- }
@@ -1,31 +0,0 @@
1
- import type { Command } from 'commander';
2
- import type { SessionMeta } from '@phnx-labs/sessions-cli/reader';
3
- import { type SessionsBackupClient } from '../lib/session/sync/net-client.js';
4
- import { type BundleHeader, type BundleRecord } from '../lib/session/bundle.js';
5
- export declare function registerSessionsExportCommand(sessionsCmd: Command): void;
6
- interface GlobalSelection {
7
- since?: string;
8
- limit?: string;
9
- all?: boolean;
10
- agent?: string;
11
- redact?: boolean;
12
- encrypt?: boolean;
13
- toR2?: boolean;
14
- byo?: boolean;
15
- output?: string;
16
- stdout?: boolean;
17
- host?: string[];
18
- claude?: boolean;
19
- codex?: boolean;
20
- kimi?: boolean;
21
- grok?: boolean;
22
- opencode?: boolean;
23
- antigravity?: boolean;
24
- }
25
- export declare function r2ExportGateError(g: Pick<GlobalSelection, 'toR2' | 'host'>, isConfigured: boolean): string | null;
26
- export declare function uploadToR2(header: BundleHeader, records: BundleRecord[], resolvedClient?: SessionsBackupClient): Promise<void>;
27
- export declare function managedUploadEncryptionError(header: BundleHeader, records: BundleRecord[]): string | null;
28
- export declare function r2KeyForRecord(rec: BundleRecord): string;
29
- export declare function resolveR2BackupKey(): Buffer | null;
30
- export declare function selectSessions(metas: SessionMeta[], selectors: string[]): SessionMeta[];
31
- export {};
@@ -1,409 +0,0 @@
1
- /**
2
- * `agents sessions export` — bundle N selected sessions into a portable,
3
- * self-describing archive (RUSH-1710).
4
- *
5
- * The successor to background R2/CRDT sync for the durable-archive / hand-off
6
- * case: instead of an always-on merge daemon, the user explicitly bundles the
7
- * sessions they want to carry to an offline box or keep as an archive. The
8
- * bundle format + placement live in ../lib/session/bundle.ts; this command owns
9
- * only the SELECTION (which sessions) and the OUTPUT (file or stdout).
10
- *
11
- * Selection flags (`--since`, `-n/--limit`, `--all`, `-a/--agent`,
12
- * `--no-redact`) are inherited from the parent `sessions` command and read via
13
- * optsWithGlobals(), so they never shadow the parent's parsing; this command
14
- * adds only the export-specific flags (`-o/--output`, `--stdout`, `--encrypt`).
15
- *
16
- * Rendered markdown/json of a single session is already served by
17
- * `agents sessions <id> --markdown|--json`; export is specifically the portable,
18
- * re-importable BUNDLE, so it does not re-expose those render formats.
19
- */
20
- import * as fs from 'fs';
21
- import * as path from 'path';
22
- import chalk from 'chalk';
23
- import { discoverSessions, resolveSessionById, looksLikeSessionId } from '../lib/session/discover.js';
24
- import { findSessionsById } from '../lib/session/db.js';
25
- import { filterSessionsByQuery, parseAgentFilter } from '../lib/session/selection.js';
26
- import { listLocalTranscripts, objectKey, SYNC_AGENTS } from '../lib/session/sync/agents.js';
27
- import { machineId } from '../lib/machine-id.js';
28
- import { getHistoryDir } from '../lib/state.js';
29
- import { isSyncConfigured, loadR2Config } from '../lib/session/sync/config.js';
30
- import { resolveSyncEncKey, generateSyncEncKey, isTranscriptEnvelope, } from '../lib/session/sync/transcript-crypto.js';
31
- import { R2Client } from '../lib/session/sync/r2.js';
32
- import { resolveSessionsBackend } from '../lib/session/sync/backend.js';
33
- import { SessionsHttpClient } from '../lib/session/sync/net-client.js';
34
- import { resolveManagedBackupKey } from '../lib/session/sync/managed-key.js';
35
- import { buildRecord, makeHeader, mergeRecords, serializeBundle, writeBundleFile, specForAgent, } from '../lib/session/bundle.js';
36
- import { knownSecretValuesFromEnv } from '../lib/redact.js';
37
- import { pullBundlesFromHosts } from '../lib/session/remote-bundle.js';
38
- import { setHelpSections } from '../lib/help.js';
39
- const DEFAULT_LIMIT = 500;
40
- export function registerSessionsExportCommand(sessionsCmd) {
41
- const cmd = sessionsCmd
42
- .command('export [selectors...]')
43
- .description('Bundle sessions (by id, query, or the parent selection flags like --since/-a) into a portable archive.')
44
- .option('-o, --output <path>', 'Write the bundle to this file')
45
- .option('--stdout', 'Write the bundle to stdout (for piping into `sessions import -`)')
46
- .option('--encrypt', 'Seal each transcript body with AES-256-GCM before writing')
47
- .option('--to-r2', 'Back the selected sessions up off-box (managed Phoenix store when signed in; your own r2.backups bucket with --byo) instead of a local file')
48
- .option('--byo', 'With --to-r2: force your own r2.backups bucket instead of the managed Phoenix store');
49
- setHelpSections(cmd, {
50
- examples: `# Bundle the last week of sessions to a file
51
- agents sessions export --since 7d -o week.bundle
52
-
53
- # Bundle two specific sessions
54
- agents sessions export 4f8a2b1c 9d3e7a55 -o pair.bundle
55
-
56
- # Encrypt + pipe straight into another machine over SSH
57
- agents sessions export --since 7d --stdout --encrypt | agents ssh boxB 'agents sessions import - --decrypt <key>'
58
-
59
- # Back the last month up off-box (managed Phoenix store — no bucket to set up)
60
- agents sessions export --since 30d --to-r2
61
-
62
- # Or to your own r2.backups bucket (R2_SYNC_ENC_KEY keeps it zero-knowledge)
63
- agents sessions export --since 30d --to-r2 --byo`,
64
- notes: `Selection uses the same flags as 'agents sessions' (--since, -n/--limit, --all,
65
- -a/--agent, --no-redact). Bundles are self-describing NDJSON: a header line + one
66
- line per transcript file. Secrets are redacted by default. Dir-shaped sessions
67
- (Kimi) carry all their files. Restore with 'agents sessions import'.
68
-
69
- --to-r2 backs each session up off-box, one encrypted object per transcript keyed
70
- by machine/agent/session. When you are signed in ('agents auth login') it uploads
71
- to the MANAGED Phoenix store — no Cloudflare or r2.backups bucket to set up — and
72
- every body is sealed with a per-account key (mandatory; never plaintext). --byo
73
- forces your own r2.backups bucket instead; with R2_SYNC_ENC_KEY, neither Phoenix
74
- nor the storage provider can decrypt it. Restore with 'agents sessions import --from-r2'.`,
75
- });
76
- cmd.action(async (selectors, _options, command) => {
77
- await runExport(selectors, command);
78
- });
79
- }
80
- async function runExport(selectors, command) {
81
- const g = command.optsWithGlobals();
82
- let sessionsClient;
83
- let managedClient;
84
- let managedBackupUserId;
85
- if (g.byo && !g.toR2) {
86
- process.stderr.write(chalk.red('--byo is only valid with --to-r2.\n'));
87
- process.exit(1);
88
- }
89
- if (g.toR2) {
90
- if (g.host && g.host.length > 0) {
91
- process.stderr.write(chalk.red("--to-r2 backs up THIS machine's sessions; it cannot be combined with --device.\n"));
92
- process.exit(1);
93
- }
94
- try {
95
- const backend = resolveSessionsBackend({ byo: g.byo });
96
- if (backend.kind === 'managed') {
97
- managedClient = new SessionsHttpClient({ baseUrl: backend.baseUrl, userId: backend.userId, token: backend.token });
98
- sessionsClient = managedClient;
99
- managedBackupUserId = backend.userId;
100
- }
101
- else {
102
- const gateErr = r2ExportGateError(g, isSyncConfigured());
103
- if (gateErr)
104
- throw new Error(gateErr);
105
- sessionsClient = new R2Client(backend.r2);
106
- }
107
- }
108
- catch (err) {
109
- process.stderr.write(chalk.red(`Session backup: ${err.message}\n`));
110
- process.exit(1);
111
- }
112
- }
113
- if (g.host && g.host.length > 0) {
114
- await runRemoteExport(g, selectors, command);
115
- return;
116
- }
117
- if (g.toR2 && (g.output || g.stdout)) {
118
- process.stderr.write(chalk.yellow('Note: --to-r2 uploads to R2; -o/--stdout are ignored.\n'));
119
- }
120
- const explicitLimit = command.parent?.getOptionValueSource?.('limit') === 'cli';
121
- const limit = explicitLimit ? Math.max(1, parseInt(String(g.limit), 10) || DEFAULT_LIMIT) : DEFAULT_LIMIT;
122
- const agentFilter = parseAgentFilter(resolveAgentShorthand(g));
123
- const metas = await discoverSessions({
124
- all: g.all !== false,
125
- agent: agentFilter.agent ?? undefined,
126
- since: g.since,
127
- limit,
128
- });
129
- const selected = selectSessions(metas, selectors);
130
- if (selected.length === 0) {
131
- process.stderr.write(chalk.yellow('No sessions matched the selection.\n'));
132
- process.exit(1);
133
- }
134
- if (!selectors.length && selected.length >= limit) {
135
- process.stderr.write(chalk.yellow(`Note: capped at ${limit} sessions. Raise -n to bundle more.\n`));
136
- }
137
- const index = buildLocalIndex();
138
- const self = machineId();
139
- const files = [];
140
- const skippedAgents = new Set();
141
- for (const meta of selected) {
142
- const spec = specForAgent(meta.agent);
143
- if (!spec) {
144
- skippedAgents.add(meta.agent);
145
- continue;
146
- }
147
- const machine = meta.machine || self;
148
- const lt = index.get(`${meta.agent}:${meta.id}`);
149
- if (lt) {
150
- for (const f of lt.files) {
151
- files.push({ agent: meta.agent, machine, sessionId: meta.id, relKey: f.relKey, absPath: f.absPath, label: meta.label });
152
- }
153
- }
154
- else if (meta.filePath && fs.existsSync(meta.filePath)) {
155
- const relKey = relKeyFromPath(meta.filePath, meta.agent, machine, spec.subdir);
156
- files.push({ agent: meta.agent, machine, sessionId: meta.id, relKey, absPath: meta.filePath, label: meta.label });
157
- }
158
- }
159
- if (skippedAgents.size > 0) {
160
- process.stderr.write(chalk.yellow(`Skipped agents with no portable format: ${[...skippedAgents].sort().join(', ')}.\n`));
161
- }
162
- if (files.length === 0) {
163
- process.stderr.write(chalk.red('Selected sessions have no exportable transcript files.\n'));
164
- process.exit(1);
165
- }
166
- // Managed off-box backup requires client-side AES-GCM; BYO storage without a key warns explicitly.
167
- let encryptKey;
168
- if (g.toR2 && managedBackupUserId) {
169
- encryptKey = await resolveManagedBackupKey(managedClient, managedBackupUserId);
170
- }
171
- else if (g.toR2) {
172
- encryptKey = resolveR2BackupKey();
173
- }
174
- else if (g.encrypt) {
175
- encryptKey = resolveExportKey();
176
- }
177
- else {
178
- encryptKey = null;
179
- }
180
- const redact = g.redact !== false;
181
- const knownSecrets = redact ? knownSecretValuesFromEnv() : undefined;
182
- const records = [];
183
- for (const f of files) {
184
- try {
185
- records.push(buildRecord(f, { redact, encryptKey, knownSecrets }));
186
- }
187
- catch (err) {
188
- process.stderr.write(chalk.yellow(`Skipped ${f.agent}/${f.sessionId} (${f.relKey}): ${err.message}\n`));
189
- }
190
- }
191
- if (records.length === 0) {
192
- process.stderr.write(chalk.red('Nothing to export after reading files.\n'));
193
- process.exit(1);
194
- }
195
- const header = makeHeader({
196
- origin: self,
197
- exportedAt: new Date().toISOString(),
198
- encrypted: encryptKey !== null,
199
- redacted: redact,
200
- records,
201
- });
202
- if (g.toR2) {
203
- await uploadToR2(header, records, sessionsClient);
204
- return;
205
- }
206
- emitBundle(header, records, g);
207
- }
208
- export function r2ExportGateError(g, isConfigured) {
209
- if (!g.toR2)
210
- return null;
211
- if (g.host && g.host.length > 0) {
212
- return "--to-r2 backs up THIS machine's sessions; it cannot be combined with --device.";
213
- }
214
- if (!isConfigured) {
215
- return ('R2 backup is not configured: the r2.backups secrets bundle is missing or locked.\n' +
216
- 'Add it with: agents secrets add r2.backups R2_ACCOUNT_ID R2_BUCKET_NAME R2_ACCESS_KEY_ID R2_SECRET_ACCESS_KEY\n' +
217
- '(optionally R2_SYNC_ENC_KEY for client-side encryption).');
218
- }
219
- return null;
220
- }
221
- export async function uploadToR2(header, records, resolvedClient) {
222
- let client;
223
- if (resolvedClient) {
224
- client = resolvedClient;
225
- }
226
- else {
227
- try {
228
- client = new R2Client(loadR2Config());
229
- }
230
- catch (err) {
231
- process.stderr.write(chalk.red(`R2 backup: ${err.message}\n`));
232
- process.exit(1);
233
- }
234
- }
235
- const encryptionError = client.kind === 'managed'
236
- ? managedUploadEncryptionError(header, records)
237
- : null;
238
- if (encryptionError) {
239
- process.stderr.write(chalk.red(`${encryptionError}\n`));
240
- process.exit(1);
241
- }
242
- let uploaded = 0;
243
- for (const rec of records) {
244
- const recHeader = makeHeader({
245
- origin: header.origin,
246
- exportedAt: header.exportedAt,
247
- encrypted: rec.encrypted,
248
- redacted: header.redacted,
249
- records: [rec],
250
- });
251
- const key = r2KeyForRecord(rec);
252
- try {
253
- await client.put(key, serializeBundle(recHeader, [rec]), 'application/json');
254
- }
255
- catch (err) {
256
- process.stderr.write(chalk.red(`R2 backup failed at ${key}: ${err.message}\n`));
257
- process.exit(1);
258
- }
259
- uploaded++;
260
- }
261
- process.stderr.write(chalk.green(`Backed up ${header.sessions} session${header.sessions === 1 ? '' : 's'} ` +
262
- `(${uploaded} object${uploaded === 1 ? '' : 's'}${header.encrypted ? ', encrypted' : ', UNENCRYPTED'}) → ` +
263
- `${client.kind === 'managed' ? 'managed Phoenix store' : 'R2'}.\n`));
264
- }
265
- export function managedUploadEncryptionError(header, records) {
266
- if (!header.encrypted ||
267
- records.some(record => !record.encrypted || !isTranscriptEnvelope(record.body))) {
268
- return 'Managed session backups require AES-256-GCM envelopes; refusing to upload plaintext.';
269
- }
270
- return null;
271
- }
272
- export function r2KeyForRecord(rec) {
273
- const spec = specForAgent(rec.agent);
274
- const relKey = spec?.dirShaped ? rec.relKey : undefined;
275
- return objectKey(rec.machine, rec.agent, rec.sessionId, relKey);
276
- }
277
- export function resolveR2BackupKey() {
278
- const key = resolveSyncEncKey(loadR2Config());
279
- if (key)
280
- return key;
281
- process.stderr.write(chalk.yellow('R2_SYNC_ENC_KEY is not set in the r2.backups bundle — objects are stored WITHOUT client-side\n' +
282
- 'encryption (R2 server-side only). Add a shared key so backups are zero-knowledge:\n' +
283
- ' agents secrets add r2.backups R2_SYNC_ENC_KEY # value: openssl rand -base64 32\n'));
284
- return null;
285
- }
286
- // Remote pull is SSH-only and never combines per-host encryption keys.
287
- async function runRemoteExport(g, selectors, command) {
288
- if (g.encrypt) {
289
- process.stderr.write(chalk.yellow('Note: --encrypt is ignored with --device (the SSH stream is already encrypted). Encrypt a local bundle instead.\n'));
290
- }
291
- const { bundles, errors } = await pullBundlesFromHosts(g.host, forwardExportArgs(g, selectors, command));
292
- for (const e of errors)
293
- process.stderr.write(chalk.yellow(` ${e}\n`));
294
- const records = mergeRecords(bundles.map(b => b.records));
295
- if (records.length === 0) {
296
- process.stderr.write(chalk.red('No sessions pulled from the given host(s).\n'));
297
- process.exit(1);
298
- }
299
- const header = makeHeader({
300
- origin: g.host.join(','),
301
- exportedAt: new Date().toISOString(),
302
- encrypted: false,
303
- redacted: g.redact !== false,
304
- records,
305
- });
306
- emitBundle(header, records, g);
307
- }
308
- function forwardExportArgs(g, selectors, command) {
309
- const args = [...selectors];
310
- if (g.since)
311
- args.push('--since', g.since);
312
- const agent = resolveAgentShorthand(g);
313
- if (agent)
314
- args.push('-a', agent);
315
- if (g.all !== false)
316
- args.push('--all');
317
- if (g.redact === false)
318
- args.push('--no-redact');
319
- if (command.parent?.getOptionValueSource?.('limit') === 'cli' && g.limit)
320
- args.push('-n', String(g.limit));
321
- return args;
322
- }
323
- function emitBundle(header, records, g) {
324
- const wire = serializeBundle(header, records);
325
- if (g.stdout) {
326
- process.stdout.write(wire);
327
- return;
328
- }
329
- const outPath = g.output || defaultBundlePath();
330
- writeBundleFile(outPath, wire);
331
- process.stderr.write(chalk.green(`Exported ${header.sessions} session${header.sessions === 1 ? '' : 's'} ` +
332
- `(${header.count} file${header.count === 1 ? '' : 's'}${header.encrypted ? ', encrypted' : ''}${header.redacted ? ', redacted' : ''}) ` +
333
- `→ ${outPath}\n`));
334
- }
335
- function resolveAgentShorthand(g) {
336
- if (g.agent)
337
- return g.agent;
338
- if (g.claude)
339
- return 'claude';
340
- if (g.codex)
341
- return 'codex';
342
- if (g.kimi)
343
- return 'kimi';
344
- if (g.grok)
345
- return 'grok';
346
- if (g.opencode)
347
- return 'opencode';
348
- if (g.antigravity)
349
- return 'antigravity';
350
- return undefined;
351
- }
352
- // An id-shaped selector that misses selects nothing; never widen it to content search and export unrelated transcripts.
353
- export function selectSessions(metas, selectors) {
354
- if (selectors.length === 0)
355
- return metas;
356
- const byId = [];
357
- const unmatched = [];
358
- for (const sel of selectors) {
359
- const trimmed = sel.trim();
360
- const hits = resolveSessionById(metas, trimmed);
361
- const resolved = hits.length > 0 || !looksLikeSessionId(trimmed) ? hits : findSessionsById(trimmed);
362
- if (resolved.length > 0)
363
- byId.push(...resolved);
364
- else
365
- unmatched.push(trimmed);
366
- }
367
- if (byId.length > 0 && unmatched.length === 0) {
368
- const seen = new Set();
369
- return byId.filter(s => (seen.has(s.id) ? false : (seen.add(s.id), true)));
370
- }
371
- const missingIds = unmatched.filter(looksLikeSessionId);
372
- if (missingIds.length > 0) {
373
- process.stderr.write(chalk.red(`No session with id ${missingIds.join(', ')} on this machine.\n`));
374
- return [];
375
- }
376
- return filterSessionsByQuery(metas, selectors.join(' '));
377
- }
378
- function buildLocalIndex() {
379
- const index = new Map();
380
- for (const spec of SYNC_AGENTS) {
381
- for (const lt of listLocalTranscripts(spec)) {
382
- index.set(`${spec.id}:${lt.sessionId}`, lt);
383
- }
384
- }
385
- return index;
386
- }
387
- function relKeyFromPath(filePath, agent, machine, subdir) {
388
- const prefix = path.join(getHistoryDir(), 'backups', agent, machine, subdir) + path.sep;
389
- if (filePath.startsWith(prefix))
390
- return filePath.slice(prefix.length);
391
- return path.basename(filePath);
392
- }
393
- function resolveExportKey() {
394
- try {
395
- const key = resolveSyncEncKey(loadR2Config());
396
- if (key)
397
- return key;
398
- }
399
- catch {
400
- }
401
- const b64 = generateSyncEncKey();
402
- process.stderr.write(chalk.yellow(`Bundle encrypted with a fresh key (not in the bundle). Decrypt with:\n` +
403
- ` agents sessions import <bundle> --decrypt ${b64}\n`));
404
- return Buffer.from(b64, 'base64');
405
- }
406
- function defaultBundlePath() {
407
- const stamp = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').slice(0, 19);
408
- return path.join(process.cwd(), `agents-sessions-${stamp}.bundle`);
409
- }
@@ -1,6 +0,0 @@
1
- import type { Command } from 'commander';
2
- import { type SessionsBackupClient } from '../lib/session/sync/net-client.js';
3
- import { type ParsedBundle } from '../lib/session/bundle.js';
4
- export declare function registerSessionsImportCommand(sessionsCmd: Command): void;
5
- export declare function r2ImportGateError(fromR2: boolean, isConfigured: boolean): string | null;
6
- export declare function pullFromR2(resolvedClient?: SessionsBackupClient): Promise<ParsedBundle>;