skydive-cli 0.5.0-beta.32 → 0.5.0-beta.36

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.
package/dist/js/bin.mjs CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import { A as takenAliasNames, B as name, D as dedupeAliasName, E as aliasActivationHint, F as getActiveWorkspaceId, I as getSessionIdentity, L as listWorkspaces, M as defaultInstallEnv, N as detectShell, O as installAgentAlias, P as ensureActiveOrganization, R as resolveWorkspaceId, S as themes, T as machineOsFromPlatform, V as version, a as installCrashHandler, j as SUPPORTED_SHELLS, k as slugifyAliasName, t as maybeStartProfiling, u as brandHelpArt, w as buildImportSeedPrompt, z as setActiveWorkspace } from "./profiler-CJMnC90G.mjs";
3
- import { A as getShareMachineDefault, C as getConfigPath, D as getPromptHistoryPath, E as getPreference, F as resolveAppUrl, H as saveSession, I as resolveChatAuth, L as resolveConfig, M as getStoredApiKeyWorkspaceName, N as getUpdateCheckDisabled, R as resolveManagementAuth, S as deleteConfig, T as getLastSeenVersion, V as saveConfig, W as setLastSeenVersion, _ as API_KEY_FAMILY_PREFIX, g as API_KEYS_URL, i as resolveAgent$1, j as getStoredApiKeyId, v as API_KEY_PREFIX, w as getDefaultAgent, x as PREFERENCES, y as DEFAULT_API_URL, z as resolveSession } from "./print-Clgq46GU.mjs";
2
+ import { A as installAgentAlias, B as resolveWorkspaceId, D as machineOsFromPlatform, E as buildImportSeedPrompt, F as detectShell, H as name, I as ensureActiveOrganization, L as getActiveWorkspaceId, M as takenAliasNames, N as SUPPORTED_SHELLS, O as aliasActivationHint, P as defaultInstallEnv, R as getSessionIdentity, U as version, V as setActiveWorkspace, c as getAutomaticLogsDir, j as slugifyAliasName, k as dedupeAliasName, l as maybeStartProfiling, o as brandHelpArt, t as installCrashHandler, u as profileDir, w as themes, z as listWorkspaces } from "./install-aZ751iYf.mjs";
3
+ import { A as getShareMachineDefault, C as getConfigPath, D as getPromptHistoryPath, E as getPreference, F as resolveAppUrl, H as saveSession, I as resolveChatAuth, L as resolveConfig, M as getStoredApiKeyWorkspaceName, N as getUpdateCheckDisabled, R as resolveManagementAuth, S as deleteConfig, T as getLastSeenVersion, V as saveConfig, W as setLastSeenVersion, _ as API_KEY_FAMILY_PREFIX, g as API_KEYS_URL, i as resolveAgent$1, j as getStoredApiKeyId, v as API_KEY_PREFIX, w as getDefaultAgent, x as PREFERENCES, y as DEFAULT_API_URL, z as resolveSession$1 } from "./print-h22UbIfZ.mjs";
4
4
  import { n as printError, r as printTable, t as output } from "./output-wY0VQDea.mjs";
5
5
  import { t as HttpError } from "./http-error-UHH3mVBF.mjs";
6
- import { t as createRestClient } from "./rest-C6E4mS2A.mjs";
6
+ import { t as createRestClient } from "./rest-ClVPZquN.mjs";
7
7
  import "./billing-blocked-D3l5kJlX.mjs";
8
8
  import { r as resolveMachineIdentity } from "./client-d6K9qm6B.mjs";
9
- import { i as queryDaemonStatus, l as PORTAL_DAEMON_FLAG, n as ensureDaemonRunning, s as stopDaemon, u as daemonPaths } from "./daemon-CxFxH36O.mjs";
9
+ import { i as queryDaemonStatus, l as PORTAL_DAEMON_FLAG, n as ensureDaemonRunning, s as stopDaemon, u as daemonPaths } from "./daemon-CH95gDij.mjs";
10
10
  import "./tls-cert-CV-pwxVN.mjs";
11
11
  import { i as grantPortalAccess, n as fetchPortalDevices, o as registerPortalDevice, r as findThisDevice, s as revokePortalAccess } from "./api-DQCaztBg.mjs";
12
- import { t as SandboxStream } from "./client-BTQ1fwzM.mjs";
12
+ import { a as encodeFsRequest, i as decodeFsResponse, n as SANDBOX_STREAM_PATH, r as streamSpecToQuery, t as SandboxStream } from "./client-Btq6bMzX.mjs";
13
13
  import { hideBin } from "yargs/helpers";
14
14
  import yargs from "yargs";
15
15
  import { hostname, tmpdir } from "node:os";
@@ -19,12 +19,13 @@ import { z } from "zod";
19
19
  import open from "open";
20
20
  import fs from "node:fs";
21
21
  import { spawn, spawnSync } from "node:child_process";
22
- import { createHash, randomBytes } from "node:crypto";
22
+ import { createHash } from "node:crypto";
23
23
  import zlib from "node:zlib";
24
24
  import fsp, { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
25
- import { quote } from "shell-quote";
25
+ import { WebSocket } from "ws";
26
26
  import semver from "semver";
27
27
  import { createInterface } from "node:readline";
28
+ import { createInterface as createInterface$1 } from "node:readline/promises";
28
29
 
29
30
  //#region src/types.ts
30
31
  const NON_INTERACTIVE_ENV_VARS = [
@@ -620,7 +621,7 @@ const logoutCommand = {
620
621
  const keyId = getStoredApiKeyId();
621
622
  let keyRevoked = false;
622
623
  if (keyId) {
623
- const session = resolveSession({ appUrl: argv["api-url"] });
624
+ const session = resolveSession$1({ appUrl: argv["api-url"] });
624
625
  const config = resolveConfig({ apiUrl: argv["api-url"] });
625
626
  const credential = session.isOk() ? {
626
627
  appUrl: session.value.appUrl,
@@ -651,7 +652,7 @@ const statusCommand$1 = {
651
652
  describe: "Show current authentication state",
652
653
  handler: async (argv) => {
653
654
  const apiKey = resolveConfig({ apiUrl: argv["api-url"] });
654
- const session = resolveSession({});
655
+ const session = resolveSession$1({});
655
656
  const management = resolveManagementAuth({ apiUrl: argv["api-url"] });
656
657
  const identity = session.isOk() ? (await getSessionIdentity({
657
658
  appUrl: session.value.appUrl,
@@ -1001,7 +1002,7 @@ const completionCommand = {
1001
1002
  * resolve-or-exit block isn't copy-pasted per command.
1002
1003
  */
1003
1004
  function requireSession(argv) {
1004
- const session = resolveSession({ appUrl: resolveAppUrl({ appUrl: argv["api-url"] }) });
1005
+ const session = resolveSession$1({ appUrl: resolveAppUrl({ appUrl: argv["api-url"] }) });
1005
1006
  if (session.isErr()) {
1006
1007
  printError(`${session.error.message} Run \`skydive auth login\` first, or set SKYDIVE_SESSION_TOKEN.`);
1007
1008
  process.exit(1);
@@ -1066,7 +1067,7 @@ async function resolveAgent(client, selector) {
1066
1067
  if (matches.length === 0) throw new Error(`No agent named "${selector}". Pass an id, or run \`skydive agents list\`.`);
1067
1068
  throw new Error(`Multiple agents named "${selector}". Pass the id instead:\n${matches.map((a) => ` ${a.name} ${a.id}`).join("\n")}`);
1068
1069
  }
1069
- const listCommand$5 = {
1070
+ const listCommand$6 = {
1070
1071
  command: "list",
1071
1072
  describe: "List agents in the active workspace",
1072
1073
  builder: (y) => y.option("limit", {
@@ -1290,7 +1291,7 @@ const aliasCommand = {
1290
1291
  const agentsCommand = {
1291
1292
  command: "agents",
1292
1293
  describe: "Manage agents",
1293
- builder: (y) => y.command(listCommand$5).command(getCommand$2).command(createCommand$1).command(aliasCommand).demandCommand(1, "Specify a subcommand: list, get, create, alias"),
1294
+ builder: (y) => y.command(listCommand$6).command(getCommand$2).command(createCommand$1).command(aliasCommand).demandCommand(1, "Specify a subcommand: list, get, create, alias"),
1294
1295
  handler: () => {}
1295
1296
  };
1296
1297
 
@@ -1572,20 +1573,20 @@ const importCommand = {
1572
1573
  printError(`import needs the Bun runtime and it couldn't be set up automatically. Install Bun (https://bun.sh) and run \`bun ${process.argv[1] ?? "skydive"} import\`, point SKYDIVE_BUN_PATH at an existing bun binary, or use the non-interactive \`import -p\` (runs under Node).`);
1573
1574
  process.exit(1);
1574
1575
  }
1575
- let session = resolveSession({ appUrl });
1576
+ let session = resolveSession$1({ appUrl });
1576
1577
  if (session.isErr()) {
1577
1578
  const login = await loginWithDevice({ appUrl });
1578
1579
  if (login.isErr()) {
1579
1580
  printError(login.error.message);
1580
1581
  process.exit(1);
1581
1582
  }
1582
- session = resolveSession({ appUrl });
1583
+ session = resolveSession$1({ appUrl });
1583
1584
  if (session.isErr()) {
1584
1585
  printError("Signed in, but no session was stored.");
1585
1586
  process.exit(1);
1586
1587
  }
1587
1588
  }
1588
- const { runChat } = await import("./boot-yyXrIeVy.mjs");
1589
+ const { runChat } = await import("./boot-CmInaUwJ.mjs");
1589
1590
  await runChat({
1590
1591
  appUrl,
1591
1592
  sessionToken: session.value.sessionToken,
@@ -1610,7 +1611,7 @@ const importCommand = {
1610
1611
  * (`chat -p "go ahead" --resume <id> --share-machine`) to apply it.
1611
1612
  */
1612
1613
  async function runImportPrintMode({ argv, appUrl }) {
1613
- const session = resolveSession({ appUrl });
1614
+ const session = resolveSession$1({ appUrl });
1614
1615
  if (session.isErr()) {
1615
1616
  printError(`${session.error.message} For non-interactive use, run \`skydive auth login --web\` first, or set SKYDIVE_SESSION_TOKEN.`);
1616
1617
  process.exit(1);
@@ -1623,7 +1624,7 @@ async function runImportPrintMode({ argv, appUrl }) {
1623
1624
  });
1624
1625
  const extra = (argv.print ?? "").trim();
1625
1626
  const prompt = buildImportSeedPrompt(process.cwd(), machineOsFromPlatform(process.platform)) + (extra ? `\n\nAdditional instructions: ${extra}` : "");
1626
- const { runPrint } = await import("./print-B9djx8GU.mjs");
1627
+ const { runPrint } = await import("./print-DV9L41G2.mjs");
1627
1628
  try {
1628
1629
  const result = await runPrint({
1629
1630
  appUrl,
@@ -1647,7 +1648,7 @@ async function runImportPrintMode({ argv, appUrl }) {
1647
1648
 
1648
1649
  //#endregion
1649
1650
  //#region src/commands/keys.ts
1650
- const listCommand$4 = {
1651
+ const listCommand$5 = {
1651
1652
  command: "list",
1652
1653
  describe: "List API keys for an agent",
1653
1654
  handler: async (argv) => {
@@ -1736,7 +1737,7 @@ const keysCommand = {
1736
1737
  type: "string",
1737
1738
  demandOption: true,
1738
1739
  describe: "Agent ID"
1739
- }).command(listCommand$4).command(createCommand).command(revokeCommand$1).demandCommand(1, "Specify a subcommand: list, create, revoke"),
1740
+ }).command(listCommand$5).command(createCommand).command(revokeCommand$1).demandCommand(1, "Specify a subcommand: list, create, revoke"),
1740
1741
  handler: () => {}
1741
1742
  };
1742
1743
 
@@ -1748,7 +1749,7 @@ async function readStdin() {
1748
1749
  for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1749
1750
  return Buffer.concat(chunks).toString("utf8").replace(/\n$/, "");
1750
1751
  }
1751
- const listCommand$3 = {
1752
+ const listCommand$4 = {
1752
1753
  command: "list",
1753
1754
  describe: "List secret names for an agent (values are never shown)",
1754
1755
  handler: async (argv) => {
@@ -1834,7 +1835,7 @@ const secretsCommand = {
1834
1835
  type: "string",
1835
1836
  demandOption: true,
1836
1837
  describe: "Agent ID"
1837
- }).command(listCommand$3).command(setCommand$1).command(rmCommand).demandCommand(1, "Specify a subcommand: list, set, rm"),
1838
+ }).command(listCommand$4).command(setCommand$1).command(rmCommand).demandCommand(1, "Specify a subcommand: list, set, rm"),
1838
1839
  handler: () => {}
1839
1840
  };
1840
1841
 
@@ -2030,7 +2031,7 @@ const chatCommand = {
2030
2031
  sessionToken: auth.value.token,
2031
2032
  agentSelector: argv.agent ?? null
2032
2033
  });
2033
- const { runChat } = await import("./boot-yyXrIeVy.mjs");
2034
+ const { runChat } = await import("./boot-CmInaUwJ.mjs");
2034
2035
  await runChat({
2035
2036
  appUrl: auth.value.appUrl,
2036
2037
  sessionToken: auth.value.token,
@@ -2114,7 +2115,7 @@ async function runPrintMode({ argv, appUrl }) {
2114
2115
  printError(`${auth.error.message} For non-interactive use, run \`skydive auth login\` first, or set SKYDIVE_API_KEY / SKYDIVE_SESSION_TOKEN.`);
2115
2116
  process.exit(1);
2116
2117
  }
2117
- const { runPrint, readStdin } = await import("./print-B9djx8GU.mjs");
2118
+ const { runPrint, readStdin } = await import("./print-DV9L41G2.mjs");
2118
2119
  const workspaceId = await resolveWorkspaceFlag({
2119
2120
  appUrl,
2120
2121
  sessionToken: auth.value.token,
@@ -2209,7 +2210,7 @@ const getCommand$1 = {
2209
2210
  printError(`${auth.error.message} Run \`skydive auth login\` first, or set SKYDIVE_API_KEY / SKYDIVE_SESSION_TOKEN.`);
2210
2211
  process.exit(1);
2211
2212
  }
2212
- const { messageGet } = await import("./print-B9djx8GU.mjs");
2213
+ const { messageGet } = await import("./print-DV9L41G2.mjs");
2213
2214
  try {
2214
2215
  const result = await messageGet({
2215
2216
  appUrl: auth.value.appUrl,
@@ -2256,7 +2257,7 @@ function messageToText(message) {
2256
2257
  }
2257
2258
  return chunks.join("\n").trim();
2258
2259
  }
2259
- const listCommand$2 = {
2260
+ const listCommand$3 = {
2260
2261
  command: "list",
2261
2262
  describe: "List an agent's conversations",
2262
2263
  builder: (y) => y.option("agent", {
@@ -2346,7 +2347,7 @@ const conversationsCommand = {
2346
2347
  command: "conversations",
2347
2348
  aliases: ["conv"],
2348
2349
  describe: "List and read agent conversations",
2349
- builder: (y) => y.command(listCommand$2).command(showCommand).demandCommand(1, "Specify a subcommand: list, show"),
2350
+ builder: (y) => y.command(listCommand$3).command(showCommand).demandCommand(1, "Specify a subcommand: list, show"),
2350
2351
  handler: () => {}
2351
2352
  };
2352
2353
 
@@ -2388,7 +2389,7 @@ async function runList(argv, { hint }) {
2388
2389
  ]));
2389
2390
  if (hint && !argv.quiet) console.log("\nRun `skydive workspace switch` to pick a workspace, or pass its slug directly.");
2390
2391
  }
2391
- const listCommand$1 = {
2392
+ const listCommand$2 = {
2392
2393
  command: "list",
2393
2394
  describe: "List workspaces on your account",
2394
2395
  handler: (argv) => runList(argv, { hint: false })
@@ -2412,7 +2413,7 @@ const switchCommand = {
2412
2413
  printError("The workspace picker needs the Bun runtime and it could not be set up automatically. Pass a workspace slug instead, or install Bun and retry.");
2413
2414
  process.exit(1);
2414
2415
  }
2415
- const { runWorkspacePicker } = await import("./boot-yyXrIeVy.mjs");
2416
+ const { runWorkspacePicker } = await import("./boot-CmInaUwJ.mjs");
2416
2417
  await runWorkspacePicker(session);
2417
2418
  return;
2418
2419
  }
@@ -2445,7 +2446,7 @@ const switchCommand = {
2445
2446
  const workspaceCommand = {
2446
2447
  command: "workspace",
2447
2448
  describe: "List or switch the workspace all `skydive` commands act on",
2448
- builder: (y) => y.command(listCommand$1).command(switchCommand),
2449
+ builder: (y) => y.command(listCommand$2).command(switchCommand),
2449
2450
  handler: (argv) => runList(argv, { hint: true })
2450
2451
  };
2451
2452
 
@@ -2491,7 +2492,7 @@ const openCommand = {
2491
2492
  const agent = argv.agent ? resolveAgent$1((await fetchPortalDevices(session)).agents, argv.agent) : null;
2492
2493
  const cwd = argv.cwd ? path.resolve(argv.cwd) : process.cwd();
2493
2494
  const { machineName } = await resolveMachineIdentity(null);
2494
- const { PortalDaemonClient } = await import("./daemon-client-1Qfc_Y3J.mjs");
2495
+ const { PortalDaemonClient } = await import("./daemon-client-CC9sxWac.mjs");
2495
2496
  let lastLine = "";
2496
2497
  let signalConnected;
2497
2498
  const connected = new Promise((resolve) => {
@@ -2767,7 +2768,7 @@ const portalCommand = {
2767
2768
  //#endregion
2768
2769
  //#region src/commands/sandbox.ts
2769
2770
  /** POSIX single-quote one word so the remote shell treats it as one token. */
2770
- function shellQuote$1(word) {
2771
+ function shellQuote(word) {
2771
2772
  if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(word)) return word;
2772
2773
  return `'${word.replace(/'/g, `'\\''`)}'`;
2773
2774
  }
@@ -2782,7 +2783,7 @@ function shellQuote$1(word) {
2782
2783
  * for too. yargs number-coerces bare numerals, so words are stringified.
2783
2784
  */
2784
2785
  function joinCommandWords(words) {
2785
- return words.map(String).map(shellQuote$1).join(" ").trim();
2786
+ return words.map(String).map(shellQuote).join(" ").trim();
2786
2787
  }
2787
2788
  /**
2788
2789
  * `skydive sandbox` — the standalone counterpart to the chat TUI's `/sandbox`
@@ -2805,8 +2806,8 @@ const sandboxCommand = {
2805
2806
  }).example("skydive sandbox --agent grace", "Live terminal (Ctrl-] detaches)").example("skydive sandbox --agent grace -- tail -n 50 /tmp/harness.log", "One-shot command (use `--` so its flags reach the sandbox)").example("skydive sandbox --agent grace -- sh -c 'ls /tmp | wc -l'", "Shell features go through an explicit `sh -c`"),
2806
2807
  handler: async (argv) => {
2807
2808
  const session = requireSession(argv);
2808
- const { createRestClient } = await import("./rest-CaWUSrnH.mjs");
2809
- const { resolveAgent } = await import("./print-B9djx8GU.mjs");
2809
+ const { createRestClient } = await import("./rest-v-7FQqLP.mjs");
2810
+ const { resolveAgent } = await import("./print-DV9L41G2.mjs");
2810
2811
  const client = createRestClient({
2811
2812
  appUrl: session.appUrl,
2812
2813
  sessionToken: session.sessionToken
@@ -2875,7 +2876,7 @@ async function runPty({ session, agentId, agentName }) {
2875
2876
  return 1;
2876
2877
  }
2877
2878
  console.error(`Connecting to ${agentName}'s sandbox… (Ctrl-] detaches)`);
2878
- const { runRawPtyPassthrough } = await import("./raw-pty-g3kATVQe.mjs");
2879
+ const { runRawPtyPassthrough } = await import("./raw-pty-Ci2qFR9F.mjs");
2879
2880
  const result = await runRawPtyPassthrough({
2880
2881
  stdin: process.stdin,
2881
2882
  stdout: process.stdout,
@@ -2887,40 +2888,151 @@ async function runPty({ session, agentId, agentName }) {
2887
2888
  return result.code;
2888
2889
  }
2889
2890
 
2891
+ //#endregion
2892
+ //#region src/chat/sandbox/fs-client.ts
2893
+ function wsBase(appUrl) {
2894
+ const base = appUrl.replace(/\/+$/, "");
2895
+ if (base.startsWith("https://")) return `wss://${base.slice(8)}`;
2896
+ if (base.startsWith("http://")) return `ws://${base.slice(7)}`;
2897
+ return `wss://${base}`;
2898
+ }
2899
+ function toU8(data) {
2900
+ if (Buffer.isBuffer(data)) return new Uint8Array(data);
2901
+ if (Array.isArray(data)) return new Uint8Array(Buffer.concat(data));
2902
+ return new Uint8Array(Buffer.from(data));
2903
+ }
2904
+ var SandboxFsClient = class SandboxFsClient {
2905
+ ws;
2906
+ ready;
2907
+ nextReqId = 1;
2908
+ pending = /* @__PURE__ */ new Map();
2909
+ closedReason = null;
2910
+ constructor(opts) {
2911
+ const spec = {
2912
+ mode: "fs",
2913
+ agentId: opts.agentId
2914
+ };
2915
+ const url = new URL(`${wsBase(opts.appUrl)}${SANDBOX_STREAM_PATH}`);
2916
+ for (const [key, value] of Object.entries(streamSpecToQuery(spec))) url.searchParams.set(key, value);
2917
+ this.ws = new WebSocket(url.toString(), { headers: { authorization: `Bearer ${opts.sessionToken}` } });
2918
+ this.ws.binaryType = "nodebuffer";
2919
+ this.ready = new Promise((resolve, reject) => {
2920
+ this.ws.once("open", () => resolve());
2921
+ this.ws.once("error", (err) => reject(err));
2922
+ });
2923
+ this.ws.on("message", (data, isBinary) => {
2924
+ if (!isBinary) return;
2925
+ const res = decodeFsResponse(toU8(data));
2926
+ if (!res) return;
2927
+ const p = this.pending.get(res.reqId);
2928
+ if (!p) return;
2929
+ this.pending.delete(res.reqId);
2930
+ if (res.status === "error") p.reject(new Error(res.message));
2931
+ else p.resolve({
2932
+ result: res.result,
2933
+ blob: res.blob
2934
+ });
2935
+ });
2936
+ const failAll = (reason) => {
2937
+ this.closedReason = reason;
2938
+ for (const [, p] of this.pending) p.reject(new Error(reason));
2939
+ this.pending.clear();
2940
+ };
2941
+ this.ws.on("error", (err) => failAll(err.message));
2942
+ this.ws.on("close", () => failAll(this.closedReason ?? "the sandbox filesystem connection closed"));
2943
+ }
2944
+ /** Open and wait for the channel to be ready to accept requests. */
2945
+ static async connect(opts) {
2946
+ const client = new SandboxFsClient(opts);
2947
+ await client.ready;
2948
+ return client;
2949
+ }
2950
+ request(req, blob) {
2951
+ if (this.closedReason) return Promise.reject(new Error(this.closedReason));
2952
+ const reqId = this.nextReqId++;
2953
+ return new Promise((resolve, reject) => {
2954
+ this.pending.set(reqId, {
2955
+ resolve,
2956
+ reject
2957
+ });
2958
+ try {
2959
+ this.ws.send(encodeFsRequest(reqId, req, blob));
2960
+ } catch (error) {
2961
+ this.pending.delete(reqId);
2962
+ reject(error instanceof Error ? error : new Error(String(error)));
2963
+ }
2964
+ });
2965
+ }
2966
+ async list(path) {
2967
+ const { result } = await this.request({
2968
+ op: "list",
2969
+ path
2970
+ }, null);
2971
+ const entries = result["entries"];
2972
+ if (!Array.isArray(entries)) return [];
2973
+ return entries;
2974
+ }
2975
+ async stat(path) {
2976
+ const { result } = await this.request({
2977
+ op: "stat",
2978
+ path
2979
+ }, null);
2980
+ return result["stat"];
2981
+ }
2982
+ async read(path, range) {
2983
+ const req = range ? {
2984
+ op: "read",
2985
+ path,
2986
+ offset: range.offset,
2987
+ length: range.length
2988
+ } : {
2989
+ op: "read",
2990
+ path
2991
+ };
2992
+ const { blob } = await this.request(req, null);
2993
+ return blob;
2994
+ }
2995
+ async write(path, data) {
2996
+ await this.request({
2997
+ op: "write",
2998
+ path
2999
+ }, data);
3000
+ }
3001
+ async mkdir(path) {
3002
+ await this.request({
3003
+ op: "mkdir",
3004
+ path
3005
+ }, null);
3006
+ }
3007
+ async rename(oldPath, newPath) {
3008
+ await this.request({
3009
+ op: "rename",
3010
+ oldPath,
3011
+ newPath
3012
+ }, null);
3013
+ }
3014
+ async remove(path) {
3015
+ await this.request({
3016
+ op: "remove",
3017
+ path
3018
+ }, null);
3019
+ }
3020
+ async exists(path) {
3021
+ const { result } = await this.request({
3022
+ op: "exists",
3023
+ path
3024
+ }, null);
3025
+ return result["exists"] === true;
3026
+ }
3027
+ close() {
3028
+ this.closedReason ??= "closed by caller";
3029
+ this.ws.close();
3030
+ }
3031
+ };
3032
+
2890
3033
  //#endregion
2891
3034
  //#region src/commands/fs.ts
2892
3035
  /**
2893
- * POSIX-quote one word so the remote shell treats it as a single token. Wraps
2894
- * `shell-quote`'s `quote` (already a repo dependency, used elsewhere in the
2895
- * CLI) rather than hand-rolling the escaping — it is the well-tested source of
2896
- * truth for making a path/arg with spaces, quotes, `$`, `;`, globs, etc. inert
2897
- * when interpolated into an `sh -c` line.
2898
- */
2899
- function shellQuote(word) {
2900
- return quote([word]);
2901
- }
2902
- const MISSING_FILE_EXIT = 44;
2903
- /**
2904
- * Build the remote shell command that base64-encodes a file to stdout. Exits
2905
- * {@link MISSING_FILE_EXIT} when the path doesn't exist, 1 when it's a
2906
- * directory, so the caller can tell "create new" from a genuine error.
2907
- */
2908
- function buildReadCommand(path) {
2909
- const q = shellQuote(path);
2910
- return `sh -c ${shellQuote(`if [ ! -e ${q} ]; then exit ${MISSING_FILE_EXIT}; fi; if [ -d ${q} ]; then echo 'path is a directory' >&2; exit 1; fi; base64 < ${q}`)}`;
2911
- }
2912
- /**
2913
- * Build the remote shell command that decodes `b64` and writes it to `path`
2914
- * atomically (temp file + `mv`) so a dropped connection can't truncate the
2915
- * original in place. `token` is a caller-supplied unique suffix for the temp
2916
- * file — generated in JS (not the shell's `$$`, which shell-quote would escape
2917
- * to a literal, so every write would collide on the same temp name).
2918
- */
2919
- function buildWriteCommand(path, b64, token) {
2920
- const tmp = `${path}.skydive-edit.${token}`;
2921
- return `sh -c ${shellQuote(`printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(tmp)} && mv -f ${shellQuote(tmp)} ${shellQuote(path)}`)}`;
2922
- }
2923
- /**
2924
3036
  * Resolve the editor command from an explicit override, then $VISUAL, $EDITOR,
2925
3037
  * then `vi`. Split so `EDITOR="code --wait"` (command + flags) is honored.
2926
3038
  */
@@ -2934,17 +3046,17 @@ function resolveEditor(override, env) {
2934
3046
  /**
2935
3047
  * `skydive fs edit <path>` — edit a file that lives on the agent's computer
2936
3048
  * (its sandbox) with your LOCAL editor. It reads the remote file down over the
2937
- * same relay `skydive sandbox` uses, opens it in `$EDITOR`, and writes your
2938
- * changes back when you save and close — so you edit a remote file as if it
2939
- * were local, without opening the chat TUI.
3049
+ * multiplexed `fs` sandbox-stream channel, opens it in `$EDITOR`, and writes
3050
+ * your changes back when you save and close — so you edit a remote file as if
3051
+ * it were local, without opening the chat TUI.
2940
3052
  *
2941
- * There is no server-side "file" endpoint yet: this rides entirely on the
2942
- * existing one-shot `exec` mode of the sandbox stream. Contents move
2943
- * base64-encoded in BOTH directions (exec has no stdin, so the write payload is
2944
- * embedded in the command string) which keeps binary bytes, trailing newlines,
2945
- * and CRLF intact. Access gating (EDIT on the agent + the sandbox kill switch)
2946
- * is enforced by the relay, exactly as for `skydive sandbox`. A future PR adds
2947
- * a first-class `fs` channel that `edit` (and `fs mount`) will ride instead.
3053
+ * It rides the first-class `fs` relay channel ({@link SandboxFsClient}): file
3054
+ * bytes move as the frame's trailing binary blob in BOTH directions, so binary
3055
+ * content, trailing newlines, and CRLF are preserved and unlike the old
3056
+ * exec-mode path that embedded a base64 payload in the upgrade URL a large
3057
+ * file no longer blows past the WebSocket URL / request-header length limit.
3058
+ * Access gating (EDIT on the agent + the `sandbox-fs-enabled` kill switch) is
3059
+ * enforced by the relay, exactly as for `skydive sandbox`.
2948
3060
  */
2949
3061
  const fsEditCommand = {
2950
3062
  command: "edit <path>",
@@ -2963,8 +3075,8 @@ const fsEditCommand = {
2963
3075
  handler: async (argv) => {
2964
3076
  const session = requireSession(argv);
2965
3077
  const remotePath = argv.path;
2966
- const { createRestClient } = await import("./rest-CaWUSrnH.mjs");
2967
- const { resolveAgent } = await import("./print-B9djx8GU.mjs");
3078
+ const { createRestClient } = await import("./rest-v-7FQqLP.mjs");
3079
+ const { resolveAgent } = await import("./print-DV9L41G2.mjs");
2968
3080
  const client = createRestClient({
2969
3081
  appUrl: session.appUrl,
2970
3082
  sessionToken: session.sessionToken
@@ -2979,148 +3091,63 @@ const fsEditCommand = {
2979
3091
  printError(error instanceof Error ? error.message : String(error));
2980
3092
  process.exit(1);
2981
3093
  }
2982
- const opts = {
2983
- session,
2984
- agentId: agent.id
2985
- };
2986
- console.error(`Reading ${remotePath} from ${agent.name}'s sandbox…`);
2987
- const read = await readRemote({
2988
- ...opts,
2989
- path: remotePath
2990
- });
2991
- if (read.kind === "error") {
2992
- printError(read.message);
3094
+ let fs;
3095
+ try {
3096
+ fs = await SandboxFsClient.connect({
3097
+ appUrl: session.appUrl,
3098
+ sessionToken: session.sessionToken,
3099
+ agentId: agent.id
3100
+ });
3101
+ } catch (error) {
3102
+ printError(`Could not open the sandbox filesystem channel: ${error instanceof Error ? error.message : String(error)}`);
2993
3103
  process.exit(1);
2994
3104
  }
2995
- const original = read.content;
2996
- if (read.kind === "missing") console.error(`${remotePath} does not exist yet — it will be created when you save.`);
2997
- const dir = await mkdtemp(join(tmpdir(), "skydive-edit-"));
2998
- const local = join(dir, remotePath.split("/").pop() || "file");
3105
+ const cleanup = async (dir) => {
3106
+ await rm(dir, {
3107
+ recursive: true,
3108
+ force: true
3109
+ }).catch((error) => {
3110
+ console.error(`Note: could not remove temp dir ${dir}: ${error instanceof Error ? error.message : String(error)}`);
3111
+ });
3112
+ };
3113
+ let local = null;
3114
+ let dir = null;
2999
3115
  try {
3116
+ console.error(`Reading ${remotePath} from ${agent.name}'s sandbox…`);
3117
+ const isNew = !await fs.exists(remotePath);
3118
+ const original = isNew ? Buffer.alloc(0) : Buffer.from(await fs.read(remotePath, null));
3119
+ if (isNew) console.error(`${remotePath} does not exist yet — it will be created when you save.`);
3120
+ dir = await mkdtemp(join(tmpdir(), "skydive-edit-"));
3121
+ const base = remotePath.split("/").pop() || "file";
3122
+ local = join(dir, base);
3000
3123
  await writeFile(local, original);
3001
3124
  if (!await openEditor(argv.editor, local)) {
3002
3125
  printError("Editor exited non-zero; not saving any changes.");
3126
+ fs.close();
3127
+ await cleanup(dir);
3003
3128
  process.exit(1);
3004
3129
  }
3005
3130
  const edited = await readFile(local);
3006
3131
  if (edited.equals(original)) {
3007
3132
  console.error("No changes — nothing written.");
3133
+ fs.close();
3134
+ await cleanup(dir);
3008
3135
  process.exit(0);
3009
3136
  }
3010
3137
  console.error(`Writing changes back to ${remotePath}…`);
3011
- const wrote = await writeRemote({
3012
- ...opts,
3013
- path: remotePath,
3014
- content: edited
3015
- });
3016
- if (wrote.kind === "error") {
3017
- printError(`${wrote.message}\nYour edited copy is kept at ${local} so you don't lose it.`);
3018
- process.exit(1);
3019
- }
3138
+ await fs.write(remotePath, new Uint8Array(edited));
3020
3139
  console.error("Saved.");
3140
+ fs.close();
3141
+ await cleanup(dir);
3021
3142
  process.exit(0);
3022
- } finally {
3023
- await rm(dir, {
3024
- recursive: true,
3025
- force: true
3026
- }).catch((error) => {
3027
- console.error(`Note: could not remove temp dir ${dir}: ${error instanceof Error ? error.message : String(error)}`);
3028
- });
3143
+ } catch (error) {
3144
+ fs.close();
3145
+ printError(`${error instanceof Error ? error.message : String(error)}${local ? `\nYour edited copy is kept at ${local} so you don't lose it.` : ""}`);
3146
+ process.exit(1);
3029
3147
  }
3030
3148
  }
3031
3149
  };
3032
3150
  /**
3033
- * Read a remote file as bytes. Runs `base64` on the file in the sandbox and
3034
- * decodes the streamed stdout locally. Distinguishes "file is missing" (exit
3035
- * code 44, so `edit` can create it) from a real read failure.
3036
- */
3037
- function readRemote({ session, agentId, path }) {
3038
- const command = buildReadCommand(path);
3039
- const chunks = [];
3040
- const stderr = [];
3041
- return new Promise((resolve) => {
3042
- SandboxStream.open({
3043
- mode: "exec",
3044
- appUrl: session.appUrl,
3045
- sessionToken: session.sessionToken,
3046
- agentId,
3047
- command,
3048
- onEvent: (e) => {
3049
- switch (e.type) {
3050
- case "data":
3051
- chunks.push(Buffer.from(e.bytes));
3052
- break;
3053
- case "exit":
3054
- if (e.code === MISSING_FILE_EXIT) resolve({
3055
- kind: "missing",
3056
- content: Buffer.alloc(0)
3057
- });
3058
- else if (e.code === 0) resolve({
3059
- kind: "ok",
3060
- content: Buffer.from(Buffer.concat(chunks).toString("utf8").replace(/\s+/g, ""), "base64")
3061
- });
3062
- else resolve({
3063
- kind: "error",
3064
- message: stderr.join("").trim() || `Could not read the file (exit ${e.code}).`
3065
- });
3066
- break;
3067
- case "error":
3068
- stderr.push(e.message);
3069
- break;
3070
- case "close":
3071
- resolve({
3072
- kind: "error",
3073
- message: e.failure || "The connection to the sandbox closed before the file could be read."
3074
- });
3075
- break;
3076
- }
3077
- }
3078
- });
3079
- });
3080
- }
3081
- /**
3082
- * Write bytes to a remote file. Exec has no stdin, so the base64 payload is
3083
- * embedded in the command and decoded on the far side. Writes atomically via a
3084
- * temp file + `mv` so a dropped connection mid-write can't leave a truncated
3085
- * file in place of the original.
3086
- */
3087
- function writeRemote({ session, agentId, path, content }) {
3088
- const token = randomBytes(6).toString("hex");
3089
- const command = buildWriteCommand(path, content.toString("base64"), token);
3090
- const stderr = [];
3091
- return new Promise((resolve) => {
3092
- SandboxStream.open({
3093
- mode: "exec",
3094
- appUrl: session.appUrl,
3095
- sessionToken: session.sessionToken,
3096
- agentId,
3097
- command,
3098
- onEvent: (e) => {
3099
- switch (e.type) {
3100
- case "data":
3101
- stderr.push(Buffer.from(e.bytes).toString("utf8"));
3102
- break;
3103
- case "exit":
3104
- resolve(e.code === 0 ? { kind: "ok" } : {
3105
- kind: "error",
3106
- message: stderr.join("").trim() || `Could not write the file (exit ${e.code}).`
3107
- });
3108
- break;
3109
- case "error":
3110
- stderr.push(e.message);
3111
- break;
3112
- case "close":
3113
- resolve({
3114
- kind: "error",
3115
- message: e.failure || "The connection to the sandbox closed before the file was written."
3116
- });
3117
- break;
3118
- }
3119
- }
3120
- });
3121
- });
3122
- }
3123
- /**
3124
3151
  * Open `file` in the caller's editor and resolve to whether it exited cleanly.
3125
3152
  * Precedence: explicit `--editor`, then $VISUAL, $EDITOR, then `vi`. The editor
3126
3153
  * inherits the real TTY so full-screen editors (vim/nano) work.
@@ -3143,7 +3170,7 @@ function openEditor(override, file) {
3143
3170
  *
3144
3171
  * - `fs edit <path>` edit one remote file with your local editor (shipped).
3145
3172
  * - `fs mount <dir>` mount the whole sandbox filesystem locally (coming in a
3146
- * later PR, on a first-class `fs` relay channel).
3173
+ * later PR, on the same first-class `fs` relay channel).
3147
3174
  *
3148
3175
  * Grouping these under one command keeps the file surface discoverable and
3149
3176
  * leaves room to grow (`fs ls`, `fs cat`, `fs pull`) without adding more
@@ -3431,7 +3458,27 @@ function resolveSelfPath(execPath = process.execPath) {
3431
3458
 
3432
3459
  //#endregion
3433
3460
  //#region src/update-check/sources.ts
3461
+ /**
3462
+ * How this CLI was installed, which decides whether `skydive update` (and the
3463
+ * background update check) self-updates the binary from the release CDN or
3464
+ * hands off to the package manager.
3465
+ *
3466
+ * Two signals, runtime env first:
3467
+ * - `SKYDIVE_CLI_INSTALL_SOURCE` env var — set by the npm launcher
3468
+ * (src/launcher.ts) to `package-manager` before it execs the compiled
3469
+ * binary. The binary itself is `--define`'d to `binary`, but when it was
3470
+ * launched via the npm-installed launcher, npm owns its bytes and must not
3471
+ * be self-mutated — so the env override wins.
3472
+ * - The `SKYDIVE_CLI_INSTALL_SOURCE` compile-time constant — stamped
3473
+ * `binary` into the standalone binary, undefined in the npm JS bundle.
3474
+ *
3475
+ * Any value other than exactly `binary` (including unset) means
3476
+ * package-manager, the safe default: we never self-update something we can't
3477
+ * prove is a standalone binary.
3478
+ */
3434
3479
  function resolveInstallSource() {
3480
+ const runtime = typeof process !== "undefined" ? process.env?.["SKYDIVE_CLI_INSTALL_SOURCE"] : void 0;
3481
+ if (runtime !== void 0) return runtime === "binary" ? "binary" : "package-manager";
3435
3482
  return typeof SKYDIVE_CLI_INSTALL_SOURCE === "string" && SKYDIVE_CLI_INSTALL_SOURCE === "binary" ? "binary" : "package-manager";
3436
3483
  }
3437
3484
  const NPM_REGISTRY_URL = "https://registry.npmjs.org";
@@ -3859,7 +3906,7 @@ function snapshot(pref) {
3859
3906
  describe: pref.describe
3860
3907
  };
3861
3908
  }
3862
- const listCommand = {
3909
+ const listCommand$1 = {
3863
3910
  command: "list",
3864
3911
  aliases: ["ls"],
3865
3912
  describe: "Show every editable preference, its value, and its source",
@@ -3950,7 +3997,7 @@ const unsetCommand = {
3950
3997
  }
3951
3998
  }
3952
3999
  };
3953
- const pathCommand = {
4000
+ const pathCommand$1 = {
3954
4001
  command: "path",
3955
4002
  describe: "Print the on-disk config file path",
3956
4003
  handler: (argv) => {
@@ -3964,14 +4011,172 @@ const pathCommand = {
3964
4011
  const configCommand = {
3965
4012
  command: "config",
3966
4013
  describe: "View and set CLI preferences (safe, hand-editable keys only)",
3967
- builder: (y) => y.command(listCommand).command(getCommand).command(setCommand).command(unsetCommand).command(pathCommand),
4014
+ builder: (y) => y.command(listCommand$1).command(getCommand).command(setCommand).command(unsetCommand).command(pathCommand$1),
4015
+ handler: (argv) => listCommand$1.handler(argv)
4016
+ };
4017
+
4018
+ //#endregion
4019
+ //#region src/commands/logs.ts
4020
+ const ISSUE_REPOSITORY_URL = "https://github.com/Create-Inc/skydive-cli";
4021
+ function issueUrl(archivePath) {
4022
+ const url = new URL(`${ISSUE_REPOSITORY_URL}/issues/new`);
4023
+ url.searchParams.set("title", "CLI issue: ");
4024
+ url.searchParams.set("body", [
4025
+ "## What happened?",
4026
+ "",
4027
+ "<!-- Tell us what you were doing and what went wrong. -->",
4028
+ "",
4029
+ "## Diagnostics",
4030
+ "",
4031
+ `Please attach \`${path.basename(archivePath)}\` to this issue.`
4032
+ ].join("\n"));
4033
+ return url.toString();
4034
+ }
4035
+ async function listLogSessions(activeSessionPath = profileDir()) {
4036
+ const root = getAutomaticLogsDir();
4037
+ try {
4038
+ const entries = await fs.promises.readdir(root, { withFileTypes: true });
4039
+ return (await Promise.all(entries.filter((entry) => entry.isDirectory() && path.join(root, entry.name) !== activeSessionPath).map(async (entry) => {
4040
+ const sessionPath = path.join(root, entry.name);
4041
+ return {
4042
+ name: entry.name,
4043
+ path: sessionPath,
4044
+ modifiedAt: (await fs.promises.stat(sessionPath)).mtime.toISOString()
4045
+ };
4046
+ }))).sort((a, b) => b.name.localeCompare(a.name));
4047
+ } catch (_error) {
4048
+ return [];
4049
+ }
4050
+ }
4051
+ async function resolveSession(name) {
4052
+ const sessions = await listLogSessions();
4053
+ const session = name ? sessions.find((candidate) => candidate.name === name) : sessions[0];
4054
+ if (session) return session;
4055
+ printError(name ? `Log session "${name}" was not found. Run \`skydive logs list\`.` : "No diagnostic logs found yet.");
4056
+ process.exit(1);
4057
+ }
4058
+ async function offerIssueReport(archivePath) {
4059
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
4060
+ console.log(`Report an issue: ${ISSUE_REPOSITORY_URL}`);
4061
+ return;
4062
+ }
4063
+ const prompt = createInterface$1({
4064
+ input: process.stdin,
4065
+ output: process.stdout
4066
+ });
4067
+ try {
4068
+ if ((await prompt.question("Open a prefilled GitHub issue in your browser? [Y/n] ")).trim().toLowerCase() === "n") {
4069
+ console.log(`File an issue: ${ISSUE_REPOSITORY_URL}`);
4070
+ return;
4071
+ }
4072
+ await open(issueUrl(archivePath));
4073
+ console.log(`Attach the diagnostics archive: ${archivePath}`);
4074
+ } finally {
4075
+ prompt.close();
4076
+ }
4077
+ }
4078
+ async function createArchive(source, destination) {
4079
+ await new Promise((resolve, reject) => {
4080
+ const child = spawn("tar", [
4081
+ "-czf",
4082
+ destination,
4083
+ "-C",
4084
+ path.dirname(source),
4085
+ path.basename(source)
4086
+ ], { stdio: [
4087
+ "ignore",
4088
+ "ignore",
4089
+ "pipe"
4090
+ ] });
4091
+ const stderr = [];
4092
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
4093
+ child.once("error", reject);
4094
+ child.once("close", (code) => {
4095
+ if (code === 0) {
4096
+ resolve();
4097
+ return;
4098
+ }
4099
+ reject(new Error(Buffer.concat(stderr).toString("utf8").trim() || "Could not archive logs."));
4100
+ });
4101
+ });
4102
+ }
4103
+ const listCommand = {
4104
+ command: "list",
4105
+ aliases: ["ls"],
4106
+ describe: "List recent diagnostic sessions",
4107
+ handler: async (argv) => {
4108
+ const sessions = await listLogSessions();
4109
+ if (argv.json) {
4110
+ output(argv, sessions);
4111
+ return;
4112
+ }
4113
+ if (sessions.length === 0) {
4114
+ console.log("No diagnostic logs found yet.");
4115
+ return;
4116
+ }
4117
+ printTable(["Session", "Modified"], sessions.map((session) => [session.name, session.modifiedAt]));
4118
+ }
4119
+ };
4120
+ const pathCommand = {
4121
+ command: "path [session]",
4122
+ describe: "Print a diagnostic session directory (latest by default)",
4123
+ builder: (y) => y.positional("session", {
4124
+ type: "string",
4125
+ describe: "Session name from `skydive logs list`"
4126
+ }),
4127
+ handler: async (argv) => {
4128
+ const session = await resolveSession(argv.session);
4129
+ if (argv.json) {
4130
+ output(argv, session);
4131
+ return;
4132
+ }
4133
+ console.log(session.path);
4134
+ }
4135
+ };
4136
+ const exportCommand = {
4137
+ command: "export [session]",
4138
+ describe: "Archive a diagnostic session for sharing (latest by default)",
4139
+ builder: (y) => y.positional("session", {
4140
+ type: "string",
4141
+ describe: "Session name from `skydive logs list`"
4142
+ }).option("output", {
4143
+ alias: "o",
4144
+ type: "string",
4145
+ describe: "Archive path (defaults to the current directory)"
4146
+ }),
4147
+ handler: async (argv) => {
4148
+ const session = await resolveSession(argv.session);
4149
+ const destination = path.resolve(argv.output ?? `skydive-logs-${session.name}.tar.gz`);
4150
+ try {
4151
+ await createArchive(session.path, destination);
4152
+ } catch (error) {
4153
+ printError(error instanceof Error ? error.message : String(error));
4154
+ process.exit(1);
4155
+ }
4156
+ if (argv.json) {
4157
+ output(argv, {
4158
+ path: destination,
4159
+ session: session.name,
4160
+ issueUrl: issueUrl(destination),
4161
+ repositoryUrl: ISSUE_REPOSITORY_URL
4162
+ });
4163
+ return;
4164
+ }
4165
+ console.log(destination);
4166
+ await offerIssueReport(destination);
4167
+ }
4168
+ };
4169
+ const logsCommand = {
4170
+ command: "logs",
4171
+ describe: "Find and export recent local diagnostic logs",
4172
+ builder: (y) => y.command(listCommand).command(pathCommand).command(exportCommand),
3968
4173
  handler: (argv) => listCommand.handler(argv)
3969
4174
  };
3970
4175
 
3971
4176
  //#endregion
3972
4177
  //#region src/cli.ts
3973
4178
  function createCli(argv) {
3974
- return yargs(argv).scriptName("skydive").usage("$0 <command> [options]").parserConfiguration({ "populate--": true }).example("skydive auth login", "Store your API key").example("skydive chat", "Open the interactive chat TUI (prod)").example("skydive chat --api-url http://localhost:4500", "Chat against a local dev API").example("skydive agents list", "List your agents").example("skydive completion install", "Set up TAB completion for your shell").example("skydive keys create \"my-key\"", "Create an API key").example("skydive secrets set OPENAI_API_KEY --agent-id <id>", "Set a secret (value from stdin)").example("skydive workspace list", "List workspaces on your account").example("skydive config set updateCheck false", "Disable the daily update check").example("skydive workspace switch acme-team", "Switch the workspace all `skydive` commands act on").example("skydive portal open --agent grace", "Open the portal to this machine for an agent, headless (no TUI)").example("skydive fs edit --agent grace /tmp/notes.md", "Edit a file on the agent's computer with your local editor").option("json", {
4179
+ return yargs(argv).scriptName("skydive").usage("$0 <command> [options]").parserConfiguration({ "populate--": true }).example("skydive auth login", "Store your API key").example("skydive chat", "Open the interactive chat TUI (prod)").example("skydive chat --api-url http://localhost:4500", "Chat against a local dev API").example("skydive agents list", "List your agents").example("skydive completion install", "Set up TAB completion for your shell").example("skydive keys create \"my-key\"", "Create an API key").example("skydive secrets set OPENAI_API_KEY --agent-id <id>", "Set a secret (value from stdin)").example("skydive workspace list", "List workspaces on your account").example("skydive config set updateCheck false", "Disable the daily update check").example("skydive logs export", "Archive the latest local diagnostics for sharing").example("skydive workspace switch acme-team", "Switch the workspace all `skydive` commands act on").example("skydive portal open --agent grace", "Open the portal to this machine for an agent, headless (no TUI)").example("skydive fs edit --agent grace /tmp/notes.md", "Edit a file on the agent's computer with your local editor").option("json", {
3975
4180
  type: "boolean",
3976
4181
  default: false,
3977
4182
  global: true,
@@ -3985,7 +4190,7 @@ function createCli(argv) {
3985
4190
  type: "string",
3986
4191
  global: true,
3987
4192
  describe: "Override API base URL"
3988
- }).command(authCommand).command(chatCommand).command(messagesCommand).command(conversationsCommand).command(agentsCommand).command(importCommand).command(keysCommand).command(secretsCommand).command(workspaceCommand).command(portalCommand).command(sandboxCommand).command(fsCommand).command(updateCommand).command(configCommand).command(completionCommand).demandCommand(1, "Specify a command. Run --help for usage.").strict().wrap(null).version(version).alias("v", "version").alias("h", "help").help().fail((msg, err) => {
4193
+ }).command(authCommand).command(chatCommand).command(messagesCommand).command(conversationsCommand).command(agentsCommand).command(importCommand).command(keysCommand).command(secretsCommand).command(workspaceCommand).command(portalCommand).command(sandboxCommand).command(fsCommand).command(updateCommand).command(configCommand).command(logsCommand).command(completionCommand).demandCommand(1, "Specify a command. Run --help for usage.").strict().wrap(null).version(version).alias("v", "version").alias("h", "help").help().fail((msg, err) => {
3989
4194
  printError(err ? err instanceof Error ? err.message : String(err) : msg ?? "Unknown error");
3990
4195
  process.exit(1);
3991
4196
  });
@@ -4198,7 +4403,7 @@ function setupUpdateCheck(argv) {
4198
4403
 
4199
4404
  //#endregion
4200
4405
  //#region src/changelog.generated.ts
4201
- const CHANGELOG_MD = "# Changelog\n\nAll notable changes to the Skydive CLI are documented here.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## [Unreleased]\n\n### Added\n\n- `/search` (alias `/find`) in the chat TUI — opens the conversation picker with its search field focused, so \"find a conversation\" has a discoverable command instead of being a feature you had to know the bare picker already had. Pass a query inline (`/search billing deep dive`) and the picker opens already narrowed to the matches; bare `/search` opens it ready for you to type. The search runs server-side across conversation titles, message bodies, and participant names, the same search the picker exposes.\n- First run in a workspace with no agents now sets you up automatically: instead of dropping you on an empty agent picker, `skydive` creates your first agent for you (with a suggested name and avatar, mirroring the web onboarding flow) and then offers to have it learn how you already work — reading the other coding agents set up on your machine (Claude Code, Cursor, Codex, and more), the same import that `skydive import` runs, with a plan shown first and credentials never copied. Decline and you go straight into the new agent's chat. You can replay this flow anytime with `skydive --onboarding` (or `SKYDIVE_FORCE_ONBOARDING=1`), even in a workspace that already has agents.\n- `/computer` (alias `/stats`) in the chat TUI — a snapshot of the agent's sandbox drawn as colored bar graphs: CPU, memory, and disk usage. Bars turn amber past 75%% and red past 90%% so a glance tells you whether the box is under pressure. The numbers come from the Skydive API (the same live resource sample the web computer view reads), not by connecting to the sandbox — so the card shows instantly, never waking or hanging on a box that isn't running: when the agent has no live sandbox it simply reads \"no sandbox running\". The card keeps itself current quietly (a slow background refresh, no flicker or \"updating\" chrome); only the most recent card refreshes, and it silently stops while you're scrolled up (no wasted polls on a card you're not looking at) and resumes at the bottom.\n- `skydive fs` — a namespace for working with the files on an agent's computer (its sandbox) from your own machine. Its first subcommand, `skydive fs edit <path>`, reads a remote file down over the same relay `skydive sandbox` uses, opens it in your local editor (`$VISUAL`/`$EDITOR`, override with `--editor`, defaults to `vi`), and writes your changes back atomically when you save and close — so you can edit a remote file as if it were local without opening the chat TUI. A path that doesn't exist yet is created on save; no changes means nothing is written. Access is gated on EDIT permission for the agent, exactly like `skydive sandbox`. (A first-class `fs` relay channel and `skydive fs mount` land in follow-ups.)\n\n## [0.4.0] - 2026-08-07\n\n### Added\n\n- `skydive chat` works with API key auth: an API key alone now opens the chat TUI (and headless `chat -p`) without a browser login, using the key's pinned workspace.\n- `skydive config` command to view and set the safe, hand-editable CLI preferences (`shareMachineDefault`, `updateCheck`) without opening `config.json`. `config`/`config list` shows each key, its effective value, and whether it comes from the file or the built-in default; `config get`/`set`/`unset` read and change one key; `config path` prints the config file location. It only ever touches those preference keys, never credentials or flow-managed state.\n- Billing-blocked sends and runs now surface the server-authored recovery\n guidance from the typed billing outcome. The chat TUI renders it as a\n warning-toned system-notice row — live when a send is refused or a run is\n stopped at the billing boundary, and again when reopening a conversation\n that holds a persisted billing notice — instead of a generic error.\n Headless `chat -p` and `messages get` print the guidance (state, recovery\n step, and manage-billing URL) on stderr, keep any partial output already\n streamed on stdout, and exit with code `5` (distinct from the generic `1`)\n so scripted callers can tell a billing pause from a failure.\n- Syntax highlighting for 14 more languages in the chat transcript and file/review panes (python, bash, go, rust, c, cpp, java, ruby, css, html, json, yaml, and more) — previously only JavaScript/TypeScript rendered colored.\n\n### Changed\n\n- `skydive agent list` lists the full agent roster by default instead of a truncated page.\n\n### Fixed\n\n- Long multi-line bash tool-call commands (e.g. heredocs) are clamped with a `+N more · click to expand` tail instead of dumping their whole body into the scrollback.\n- Tool error output is clipped the same way as ok output, so a failing command no longer floods the transcript.\n- The TUI toast overlay has an opaque background instead of letting the transcript bleed through.\n\n## [0.3.0] - 2026-08-04\n\n### Added\n\n**Chat TUI**\n\n- `/fork` slash command to fork a conversation at any point and continue in a new thread.\n- `/conversation` switches threads from inside a live session.\n- `/compact` triggers manual conversation compaction.\n- `/portal` and `/copy` slash commands.\n- Archive the current conversation from the chat TUI.\n- `--new` flag on `skydive chat` to start a fresh conversation.\n- Debounced server-side conversation search in the picker, with title matches ranked first.\n- File review pane orientation toggle, and review comments in the file pane.\n- Pinned plan card controls and a jump-to-latest hint.\n- Terminal title (OSC) follows the live conversation title on every screen; inside cmux the workspace is renamed too, and linked PRs are pushed to the cmux sidebar.\n- Every participating agent shows in the conversation list; connect cards each have their own identity, and ctrl+r asks which connect card to act on.\n- Colored Skydive splash art in `skydive --help` and the TUI pickers.\n- New-agent name prefilled from the server's suggestion.\n\n**CLI & platform**\n\n- `skydive update` self-updater, with an update notice when a new version is available.\n- Shell completions for bash, zsh, and fish via `completion install`.\n- Portal daemon: one connection per host with per-conversation working directories.\n- Agent-led coding-agent import (`skydive import`).\n- Per-workspace scoping on the REST client, and cross-org `--agent <uuid>` auto-switches workspace.\n- `skydive-beta` wrapper for the canary channel.\n\n### Fixed\n\n- `skydive update` no longer claims an update is available on every npm install.\n- Chat memory is bounded (payload clamps + windowed rows) with a memory watchdog and OOM diagnostic report; transcript rows are memoized so streaming stops re-rendering the whole chat.\n- Chat-send failures map to real error messages.\n- Notification and sidebar previews use the last text block of the reply and strip inline markdown.\n- Picker rows no longer overlap when a conversation title contains a newline, tab, or control character.\n- Sending to non-web channel conversations is blocked in the TUI.\n- GitHub bot connect opens on the web front door, not api.skydive.com.\n- TUI activity counter times from the run, not the screen.\n\n## [0.2.0] - 2026-07-29\n\n### Added\n\n**Sandbox & machine access**\n\n- Standalone `skydive sandbox` command for direct access to an agent's sandbox.\n- `/sandbox` in the chat TUI — live PTY session and one-shot command execution.\n- Headless machine sharing via `skydive portal`, with self-registering portal grants.\n- `shareMachineDefault` config key for always-on portal sharing.\n\n**Chat TUI**\n\n- File pane (`ctrl+g`) with Changes and Files tabs: a shared file tree plus source viewer and a workspace browser, mouse-resizable and responsive to terminal size.\n- Agent todo list rendered in the chat TUI, above the composer, mirroring the web chat's todo card.\n- Fuzzy finder in the conversation and agent pickers.\n- Slash-command autocomplete menu.\n- Paste or drag-and-drop any file into the composer; paste clipboard images with Cmd+V.\n- Run local shell commands with `!` in the composer.\n- Conversation recaps, streamed live title updates, and per-agent attribution on assistant turns.\n- Working timer rolls up into minutes and hours.\n- Conversation picker paginates past 50 conversations and shows only your own conversations.\n- Esc leaves a live run; typing `exit` quits the chat.\n- Cursor Dark theme.\n- Picker rows no longer overlap when a conversation title contains a newline, tab, or control character.\n\n**Headless & scripting**\n\n- Resume a conversation by id.\n- `conversations list` and `conversations show` for transcript reads.\n- `messages get`, with run recovery keyed on message id.\n- Connect cards surface in headless `-p` mode so a driving agent never gets stuck.\n\n**Authentication**\n\n- `skydive auth login` via the browser now auto-mints an API key, so one login yields both a chat session and a usable management credential. Management commands announce the key's pinned workspace when it drives them, so a workspace mismatch is visible at use time.\n- Workspace picker on the device authorization page.\n- Account and workspace identity shown in `auth status`.\n\n**Platform**\n\n- Standalone binary builds compiling the CLI into a per-target executable.\n- Interactive workspace switcher; management commands follow the active workspace.\n- Terminal host integrations and agent notifications.\n\n### Fixed\n\n- Transcript errors collapse to one line, click to expand (REST and portal errors keep their full body).\n- Dragged/pasted image file paths attach the file instead of inserting path text, including macOS paths with literal parentheses.\n- Bare URLs in chat markdown are hyperlinked so they survive text wrap.\n- Composer draft is preserved across TUI overlays.\n- Relative connect links resolve before opening the browser.\n- Numbered markdown headings render colored in the TUI.\n- Chat transcript pages by 75% of a screen; picker rows stay on one line.\n- Run starts push to the TUI over the conversation stream.\n- Security: remediated high-severity dependency findings and cleared tar/shell-quote CVEs.\n\n## [0.1.0] - 2026-07-21\n\nInitial public release: `skydive chat` TUI, agent and conversation management,\ndevice authorization, and headless `-p` mode.\n";
4406
+ const CHANGELOG_MD = "# Changelog\n\nAll notable changes to the Skydive CLI are documented here.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## [Unreleased]\n\n### Changed\n\n- `npm i -g skydive-cli` (and yarn/pnpm/bun) now installs a tiny launcher plus one prebuilt, os/cpu-matched binary that carries its own runtime — so on the common platforms `skydive chat` and `skydive import` start instantly and **do not download a Bun runtime on first use**. On any platform without a prebuilt binary (or if the optional dependency is skipped), the CLI automatically falls back to the existing behavior: it runs under your Node and provisions Bun on first `chat`, exactly as before. Nothing about the commands, flags, config, or `SKYDIVE_*` environment variables changes, and `skydive update` still upgrades npm installs via your package manager and standalone-binary installs in place.\n\n### Added\n\n- `/search` (alias `/find`) in the chat TUI — opens the conversation picker with its search field focused, so \"find a conversation\" has a discoverable command instead of being a feature you had to know the bare picker already had. Pass a query inline (`/search billing deep dive`) and the picker opens already narrowed to the matches; bare `/search` opens it ready for you to type. The search runs server-side across conversation titles, message bodies, and participant names, the same search the picker exposes.\n- First run in a workspace with no agents now sets you up automatically: instead of dropping you on an empty agent picker, `skydive` creates your first agent for you (with a suggested name and avatar, mirroring the web onboarding flow) and then offers to have it learn how you already work — reading the other coding agents set up on your machine (Claude Code, Cursor, Codex, and more), the same import that `skydive import` runs, with a plan shown first and credentials never copied. Decline and you go straight into the new agent's chat. You can replay this flow anytime with `skydive --onboarding` (or `SKYDIVE_FORCE_ONBOARDING=1`), even in a workspace that already has agents.\n- `/computer` (alias `/stats`) in the chat TUI — a snapshot of the agent's sandbox drawn as colored bar graphs: CPU, memory, and disk usage. Bars turn amber past 75%% and red past 90%% so a glance tells you whether the box is under pressure. The numbers come from the Skydive API (the same live resource sample the web computer view reads), not by connecting to the sandbox — so the card shows instantly, never waking or hanging on a box that isn't running: when the agent has no live sandbox it simply reads \"no sandbox running\". The card keeps itself current quietly (a slow background refresh, no flicker or \"updating\" chrome); only the most recent card refreshes, and it silently stops while you're scrolled up (no wasted polls on a card you're not looking at) and resumes at the bottom.\n- `skydive fs` — a namespace for working with the files on an agent's computer (its sandbox) from your own machine. Its first subcommand, `skydive fs edit <path>`, reads a remote file down over the same relay `skydive sandbox` uses, opens it in your local editor (`$VISUAL`/`$EDITOR`, override with `--editor`, defaults to `vi`), and writes your changes back atomically when you save and close — so you can edit a remote file as if it were local without opening the chat TUI. A path that doesn't exist yet is created on save; no changes means nothing is written. Access is gated on EDIT permission for the agent, exactly like `skydive sandbox`. (A first-class `fs` relay channel and `skydive fs mount` land in follow-ups.)\n\n## [0.4.0] - 2026-08-07\n\n### Added\n\n- `skydive chat` works with API key auth: an API key alone now opens the chat TUI (and headless `chat -p`) without a browser login, using the key's pinned workspace.\n- `skydive config` command to view and set the safe, hand-editable CLI preferences (`shareMachineDefault`, `updateCheck`) without opening `config.json`. `config`/`config list` shows each key, its effective value, and whether it comes from the file or the built-in default; `config get`/`set`/`unset` read and change one key; `config path` prints the config file location. It only ever touches those preference keys, never credentials or flow-managed state.\n- Billing-blocked sends and runs now surface the server-authored recovery\n guidance from the typed billing outcome. The chat TUI renders it as a\n warning-toned system-notice row — live when a send is refused or a run is\n stopped at the billing boundary, and again when reopening a conversation\n that holds a persisted billing notice — instead of a generic error.\n Headless `chat -p` and `messages get` print the guidance (state, recovery\n step, and manage-billing URL) on stderr, keep any partial output already\n streamed on stdout, and exit with code `5` (distinct from the generic `1`)\n so scripted callers can tell a billing pause from a failure.\n- Syntax highlighting for 14 more languages in the chat transcript and file/review panes (python, bash, go, rust, c, cpp, java, ruby, css, html, json, yaml, and more) — previously only JavaScript/TypeScript rendered colored.\n\n### Changed\n\n- `skydive agent list` lists the full agent roster by default instead of a truncated page.\n\n### Fixed\n\n- Long multi-line bash tool-call commands (e.g. heredocs) are clamped with a `+N more · click to expand` tail instead of dumping their whole body into the scrollback.\n- Tool error output is clipped the same way as ok output, so a failing command no longer floods the transcript.\n- The TUI toast overlay has an opaque background instead of letting the transcript bleed through.\n\n## [0.3.0] - 2026-08-04\n\n### Added\n\n**Chat TUI**\n\n- `/fork` slash command to fork a conversation at any point and continue in a new thread.\n- `/conversation` switches threads from inside a live session.\n- `/compact` triggers manual conversation compaction.\n- `/portal` and `/copy` slash commands.\n- Archive the current conversation from the chat TUI.\n- `--new` flag on `skydive chat` to start a fresh conversation.\n- Debounced server-side conversation search in the picker, with title matches ranked first.\n- File review pane orientation toggle, and review comments in the file pane.\n- Pinned plan card controls and a jump-to-latest hint.\n- Terminal title (OSC) follows the live conversation title on every screen; inside cmux the workspace is renamed too, and linked PRs are pushed to the cmux sidebar.\n- Every participating agent shows in the conversation list; connect cards each have their own identity, and ctrl+r asks which connect card to act on.\n- Colored Skydive splash art in `skydive --help` and the TUI pickers.\n- New-agent name prefilled from the server's suggestion.\n\n**CLI & platform**\n\n- `skydive update` self-updater, with an update notice when a new version is available.\n- Shell completions for bash, zsh, and fish via `completion install`.\n- Portal daemon: one connection per host with per-conversation working directories.\n- Agent-led coding-agent import (`skydive import`).\n- Per-workspace scoping on the REST client, and cross-org `--agent <uuid>` auto-switches workspace.\n- `skydive-beta` wrapper for the canary channel.\n\n### Fixed\n\n- `skydive update` no longer claims an update is available on every npm install.\n- Chat memory is bounded (payload clamps + windowed rows) with a memory watchdog and OOM diagnostic report; transcript rows are memoized so streaming stops re-rendering the whole chat.\n- Chat-send failures map to real error messages.\n- Notification and sidebar previews use the last text block of the reply and strip inline markdown.\n- Picker rows no longer overlap when a conversation title contains a newline, tab, or control character.\n- Sending to non-web channel conversations is blocked in the TUI.\n- GitHub bot connect opens on the web front door, not api.skydive.com.\n- TUI activity counter times from the run, not the screen.\n\n## [0.2.0] - 2026-07-29\n\n### Added\n\n**Sandbox & machine access**\n\n- Standalone `skydive sandbox` command for direct access to an agent's sandbox.\n- `/sandbox` in the chat TUI — live PTY session and one-shot command execution.\n- Headless machine sharing via `skydive portal`, with self-registering portal grants.\n- `shareMachineDefault` config key for always-on portal sharing.\n\n**Chat TUI**\n\n- File pane (`ctrl+g`) with Changes and Files tabs: a shared file tree plus source viewer and a workspace browser, mouse-resizable and responsive to terminal size.\n- Agent todo list rendered in the chat TUI, above the composer, mirroring the web chat's todo card.\n- Fuzzy finder in the conversation and agent pickers.\n- Slash-command autocomplete menu.\n- Paste or drag-and-drop any file into the composer; paste clipboard images with Cmd+V.\n- Run local shell commands with `!` in the composer.\n- Conversation recaps, streamed live title updates, and per-agent attribution on assistant turns.\n- Working timer rolls up into minutes and hours.\n- Conversation picker paginates past 50 conversations and shows only your own conversations.\n- Esc leaves a live run; typing `exit` quits the chat.\n- Cursor Dark theme.\n- Picker rows no longer overlap when a conversation title contains a newline, tab, or control character.\n\n**Headless & scripting**\n\n- Resume a conversation by id.\n- `conversations list` and `conversations show` for transcript reads.\n- `messages get`, with run recovery keyed on message id.\n- Connect cards surface in headless `-p` mode so a driving agent never gets stuck.\n\n**Authentication**\n\n- `skydive auth login` via the browser now auto-mints an API key, so one login yields both a chat session and a usable management credential. Management commands announce the key's pinned workspace when it drives them, so a workspace mismatch is visible at use time.\n- Workspace picker on the device authorization page.\n- Account and workspace identity shown in `auth status`.\n\n**Platform**\n\n- Standalone binary builds compiling the CLI into a per-target executable.\n- Interactive workspace switcher; management commands follow the active workspace.\n- Terminal host integrations and agent notifications.\n\n### Fixed\n\n- Transcript errors collapse to one line, click to expand (REST and portal errors keep their full body).\n- Dragged/pasted image file paths attach the file instead of inserting path text, including macOS paths with literal parentheses.\n- Bare URLs in chat markdown are hyperlinked so they survive text wrap.\n- Composer draft is preserved across TUI overlays.\n- Relative connect links resolve before opening the browser.\n- Numbered markdown headings render colored in the TUI.\n- Chat transcript pages by 75% of a screen; picker rows stay on one line.\n- Run starts push to the TUI over the conversation stream.\n- Security: remediated high-severity dependency findings and cleared tar/shell-quote CVEs.\n\n## [0.1.0] - 2026-07-21\n\nInitial public release: `skydive chat` TUI, agent and conversation management,\ndevice authorization, and headless `-p` mode.\n";
4202
4407
 
4203
4408
  //#endregion
4204
4409
  //#region src/whats-new.ts
@@ -4341,7 +4546,7 @@ if (process.argv.includes(UPDATE_WORKER_FLAG)) {
4341
4546
  process.exit(0);
4342
4547
  }
4343
4548
  if (process.argv.includes(PORTAL_DAEMON_FLAG)) {
4344
- const { runPortalDaemon } = await import("./daemon-Btd2436i.mjs");
4549
+ const { runPortalDaemon } = await import("./daemon-Dg89tpOE.mjs");
4345
4550
  runPortalDaemon(process.argv);
4346
4551
  } else runCli();
4347
4552
  function runCli() {