@agentsky/sky 3.34.0 → 3.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19101,14 +19101,14 @@ var CATALOG_MODELS = [
19101
19101
  "tiers": [
19102
19102
  {
19103
19103
  "maxPromptTokens": 1048576,
19104
- "input": 0.054637,
19105
- "output": 0.16391,
19106
- "cachedInput": 174e-5
19104
+ "input": 0.051574,
19105
+ "output": 0.154719,
19106
+ "cachedInput": 1642e-6
19107
19107
  }
19108
19108
  ],
19109
19109
  "maxPrice": {
19110
- "prompt": 0.051788,
19111
- "completion": 0.155364
19110
+ "prompt": 0.048884,
19111
+ "completion": 0.146652
19112
19112
  },
19113
19113
  "reasoningEfforts": [
19114
19114
  "none",
@@ -19774,14 +19774,14 @@ var CATALOG_MODELS = [
19774
19774
  "tiers": [
19775
19775
  {
19776
19776
  "maxPromptTokens": 202752,
19777
- "input": 1.04445,
19778
- "output": 3.36545,
19779
- "cachedInput": 0.189268
19777
+ "input": 1.043058,
19778
+ "output": 3.278181,
19779
+ "cachedInput": 0.193712
19780
19780
  }
19781
19781
  ],
19782
19782
  "maxPrice": {
19783
- "prompt": 0.99,
19784
- "completion": 3.19
19783
+ "prompt": 0.98868,
19784
+ "completion": 3.10728
19785
19785
  },
19786
19786
  "reasoningEfforts": [],
19787
19787
  "quantizations": [
@@ -19808,8 +19808,8 @@ var CATALOG_MODELS = [
19808
19808
  }
19809
19809
  ],
19810
19810
  "maxPrice": {
19811
- "prompt": 0.611072,
19812
- "completion": 1.920512
19811
+ "prompt": 0.2079,
19812
+ "completion": 0.6534
19813
19813
  },
19814
19814
  "reasoningEfforts": [
19815
19815
  "none",
@@ -1,10 +1,12 @@
1
1
  import {
2
- USER_AGENT,
2
+ USER_AGENT
3
+ } from "./chunk-WWWRFIK5.js";
4
+ import {
3
5
  apiBase,
4
6
  apiToken,
5
7
  configPath,
6
8
  currentUniverse
7
- } from "./chunk-EG7PA52K.js";
9
+ } from "./chunk-XHZJG3QT.js";
8
10
 
9
11
  // src/api.ts
10
12
  import { createWriteStream, writeFileSync } from "fs";
@@ -151,7 +153,7 @@ async function resolveSessionRef(ref) {
151
153
  return agent.defaultSessionId;
152
154
  }
153
155
  async function* streamEvents(sessionId, signal) {
154
- const { parseSseStream } = await import("./src-JTHBN3IV.js");
156
+ const { parseSseStream } = await import("./src-HN6NQQYS.js");
155
157
  const res = await fetch(
156
158
  `${apiBase()}/sessions/${encodeURIComponent(sessionId)}/stream`,
157
159
  {
@@ -0,0 +1,8 @@
1
+ // src/version.ts
2
+ var CLI_VERSION = "3.36.0";
3
+ var USER_AGENT = `sky-cli/${CLI_VERSION} (${process.platform}; node/${process.versions.node})`;
4
+
5
+ export {
6
+ CLI_VERSION,
7
+ USER_AGENT
8
+ };
@@ -37,10 +37,6 @@ function currentUniverse() {
37
37
  return process.env.SKY_WORKSPACE ?? process.env.SKY_UNIVERSE ?? loadConfig().currentUniverse;
38
38
  }
39
39
 
40
- // src/version.ts
41
- var CLI_VERSION = "3.34.0";
42
- var USER_AGENT = `sky-cli/${CLI_VERSION} (${process.platform}; node/${process.versions.node})`;
43
-
44
40
  export {
45
41
  configPath,
46
42
  loadConfig,
@@ -48,7 +44,5 @@ export {
48
44
  apiBase,
49
45
  consoleBase,
50
46
  apiToken,
51
- currentUniverse,
52
- CLI_VERSION,
53
- USER_AGENT
47
+ currentUniverse
54
48
  };
package/dist/index.js CHANGED
@@ -15,18 +15,11 @@ import {
15
15
  uploadFile,
16
16
  uploadLargeFile,
17
17
  writeResponseFile
18
- } from "./chunk-6IVMEGJO.js";
18
+ } from "./chunk-TLR374RK.js";
19
19
  import {
20
20
  CLI_VERSION,
21
- USER_AGENT,
22
- apiBase,
23
- apiToken,
24
- configPath,
25
- consoleBase,
26
- currentUniverse,
27
- loadConfig,
28
- saveConfig
29
- } from "./chunk-EG7PA52K.js";
21
+ USER_AGENT
22
+ } from "./chunk-WWWRFIK5.js";
30
23
  import {
31
24
  AGENT_TYPES,
32
25
  MODEL_SUBSCRIPTION_PLAN_PHRASE,
@@ -48,7 +41,16 @@ import {
48
41
  skillRefSchema,
49
42
  splitMcpServers,
50
43
  supersededBy
51
- } from "./chunk-VFN3NGC6.js";
44
+ } from "./chunk-5CWYSS5Q.js";
45
+ import {
46
+ apiBase,
47
+ apiToken,
48
+ configPath,
49
+ consoleBase,
50
+ currentUniverse,
51
+ loadConfig,
52
+ saveConfig
53
+ } from "./chunk-XHZJG3QT.js";
52
54
  import "./chunk-MLKGABMK.js";
53
55
 
54
56
  // src/artifact-lifecycle.ts
@@ -86,6 +88,11 @@ function listAdoptedArtifacts(options) {
86
88
  for (const [key, value] of Object.entries(selected)) if (value !== void 0) query.set(key, String(value));
87
89
  return api("GET", `/artifacts?${query}`);
88
90
  }
91
+ function pageBackendOperation(operation, artifact2, cents) {
92
+ const path2 = `/artifacts/${seg(artifact2)}/page-backend`;
93
+ if (operation === "get") return api("GET", path2);
94
+ return api("PATCH", path2, operation === "confirm" ? { confirm_spends_owner_credits: true } : { spend_limit_cents: external_exports.coerce.number().int().min(0).max(1e6).parse(cents) });
95
+ }
89
96
  function registerArtifactLifecycleCommands(artifact2) {
90
97
  artifact2.command("list-adopted").description("list canonical owner files; execution origin selects private generated meeting notes with read-only bodies").option("--origin <origin>", "consumer_adopted (default) or execution; execution notes are private and generated-body read-only").option("--limit <number>", "page size, 1 to 50").option("--cursor <cursor>", "exact prior opaque cursor").option("--q <text>", "name search, at most 120 characters").option("--visibility <visibility>", "all, only_me or public").option("--scope <scope>", "all, mine or workspace:<64-hex workspace key>").option("--folder <folder>", "artifacts or meetings").option("--kind <kind>", "design_system").action(async (options) => output(await listAdoptedArtifacts(options)));
91
98
  artifact2.command("inspect <id>").description("read task, adopted owner or private execution identity/history; execution task_id=null, run_id, can_edit=false, separate can_discuss").action(async (target2) => output(await api("GET", `/artifacts/${seg(target2)}`)));
@@ -7113,8 +7120,8 @@ async function exportArtifact(id2, options = {}) {
7113
7120
  async function convertArtifactToPage(id2, input) {
7114
7121
  return api("POST", `/artifacts/${encodeURIComponent(id2)}/conversions`, { to: "page", base_version: input.baseVersion, ...input.requestId ? { request_id: input.requestId } : {} });
7115
7122
  }
7116
- async function shareArtifact(id2, enabled) {
7117
- return (await api("POST", `/artifacts/${encodeURIComponent(id2)}/share`, { enabled })).share_url;
7123
+ async function shareArtifact(id2, enabled, confirmSpendsOwnerCredits) {
7124
+ return (await api("POST", `/artifacts/${encodeURIComponent(id2)}/share`, { enabled, ...confirmSpendsOwnerCredits ? { confirm_spends_owner_credits: true } : {} })).share_url;
7118
7125
  }
7119
7126
  async function renameArtifact(id2, name) {
7120
7127
  return (await api("PATCH", `/artifacts/${encodeURIComponent(id2)}`, { name })).artifact;
@@ -10829,12 +10836,22 @@ artifact.command("convert <id>").description("make a Markdown, Word or PDF artif
10829
10836
  if (loss) console.log(loss);
10830
10837
  })
10831
10838
  );
10832
- artifact.command("share <id>").description("turn on a public link anyone can open; --off turns it off (the old link stops working)").option("--off", "stop sharing").action(
10839
+ artifact.command("share <id>").description("turn on a public link anyone can open; --off turns it off (the old link stops working)").option("--off", "stop sharing").option("--confirm-spends-owner-credits", "for a page whose agentsky.json names agents or APIs: agree that anyone who opens the link uses your credits").action(
10833
10840
  run(async (id2, opts) => {
10834
- const url = await shareArtifact(id2, !opts.off);
10841
+ const url = await shareArtifact(id2, !opts.off, opts.confirmSpendsOwnerCredits);
10835
10842
  console.log(url ?? `Stopped sharing ${id2}`);
10836
10843
  })
10837
10844
  );
10845
+ var artifactPage = artifact.command("page").description("what a published page with an agentsky.json can spend");
10846
+ artifactPage.command("get <id>").description("whether its link spends your credits, what a message can cost, its limit and what it has spent").action(run(async (id2) => {
10847
+ console.log(JSON.stringify(await pageBackendOperation("get", id2), null, 2));
10848
+ }));
10849
+ artifactPage.command("limit <id> <cents>").description("set the most the page may spend, in US cents").action(run(async (id2, cents) => {
10850
+ console.log(JSON.stringify(await pageBackendOperation("limit", id2, cents), null, 2));
10851
+ }));
10852
+ artifactPage.command("confirm <id>").description("agree that anyone who opens this page's link uses your credits").action(run(async (id2) => {
10853
+ console.log(JSON.stringify(await pageBackendOperation("confirm", id2), null, 2));
10854
+ }));
10838
10855
  artifact.command("comments <id>").description("read private discussion, add feedback, or resolve/reopen a root thread").option("--text <text>", "comment text").option("--base <version>", "the artifact version you read").option("--reply <id>", "reply to this comment in the same artifact and version").option("--resolve <id>", "resolve this root thread; requires --base and --state-version").option("--reopen <id>", "reopen this root thread; requires --base and --state-version").option("--state-version <version>", "the root's resolution.version, or 0 when absent").action(run(async (id2, opts) => {
10839
10856
  console.log(JSON.stringify(await artifactCommentsOperation(id2, opts), null, 2));
10840
10857
  }));
@@ -12226,7 +12243,7 @@ harness.command("connect").description("run an ACP agent (the command after --)
12226
12243
  }));
12227
12244
  var traceCmd = program.command("trace").description("correlate this machine's agent work with the cloud sessions it starts (metadata only unless you choose content)");
12228
12245
  traceCmd.command("start").description("start a trace: a grant for this machine, a root span, and the spool the hooks write to").option("--name <name>", "a name for the task").option("--source <source>", "how this machine reports itself", "claude-code").option("--hooks [settings]", "also install the Claude Code hooks (default: ./.claude/settings.local.json)").option("--capture <scopes>", "also send content, redacted on this machine first: any of prompts,tool_output,files").option("--file <path>", "a file the files scope may send (repeatable)", collect).option("--dir <path>", "a folder whose files the files scope may send when a file tool touches them (repeatable)", collect).action(run(async (opts) => {
12229
- const { readState, writeState, record, installClaudeHooks, parseContentScopes, chosenPaths, fileEvent } = await import("./trace-LAMM6QJG.js");
12246
+ const { readState, writeState, record, installClaudeHooks, parseContentScopes, chosenPaths, fileEvent } = await import("./trace-DZZ7QYJT.js");
12230
12247
  if (readState()) throw new Error("a trace is already running here \u2014 `sky trace stop` it first");
12231
12248
  const scopes = parseContentScopes(opts.capture);
12232
12249
  const chosen = chosenPaths(opts.file ?? [], opts.dir ?? []);
@@ -12261,7 +12278,7 @@ traceCmd.command("start").description("start a trace: a grant for this machine,
12261
12278
  }));
12262
12279
  traceCmd.command("hook").description("record one Claude Code hook event read from stdin (run by the installed hooks; never fails, prints nothing)").action(async () => {
12263
12280
  try {
12264
- const { readState, record, flush, grantSender, eventsForClaudeHook, contentForClaudeHook, clearState } = await import("./trace-LAMM6QJG.js");
12281
+ const { readState, record, flush, grantSender, eventsForClaudeHook, contentForClaudeHook, clearState } = await import("./trace-DZZ7QYJT.js");
12265
12282
  const chunks = [];
12266
12283
  for await (const chunk of process.stdin) chunks.push(chunk);
12267
12284
  const input = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
@@ -12274,14 +12291,14 @@ traceCmd.command("hook").description("record one Claude Code hook event read fro
12274
12291
  }
12275
12292
  });
12276
12293
  traceCmd.command("flush").description("send what the spool holds, retrying with backoff").action(run(async () => {
12277
- const { readState, flush, grantSender } = await import("./trace-LAMM6QJG.js");
12294
+ const { readState, flush, grantSender } = await import("./trace-DZZ7QYJT.js");
12278
12295
  const state = readState();
12279
12296
  if (!state) throw new Error("no trace is running here");
12280
12297
  const outcome = await flush(grantSender(state), { attempts: 4 });
12281
12298
  console.log(`sent ${outcome.sent}, refused ${outcome.refused}, given up ${outcome.expired}, still pending ${outcome.pending}${outcome.stopped ? ` (stopped: ${outcome.stopped})` : ""}`);
12282
12299
  }));
12283
12300
  traceCmd.command("status").description("the running trace and its spool").action(run(async () => {
12284
- const { readState, spoolStatus } = await import("./trace-LAMM6QJG.js");
12301
+ const { readState, spoolStatus } = await import("./trace-DZZ7QYJT.js");
12285
12302
  const state = readState();
12286
12303
  if (!state) {
12287
12304
  console.log("No trace is running here.");
@@ -12291,7 +12308,7 @@ traceCmd.command("status").description("the running trace and its spool").action
12291
12308
  console.log(`${state.trace_id} as ${state.source}: ${spool.pending} pending, ${spool.dropped_full} dropped (spool full), ${spool.dropped_expired} given up, ${spool.refused} refused`);
12292
12309
  }));
12293
12310
  traceCmd.command("show [id]").description("the trace bundle: spans, the sessions they reach, cost counted once per session").option("--json", "print the bundle as JSON").action(run(async (id2, opts) => {
12294
- const { readState } = await import("./trace-LAMM6QJG.js");
12311
+ const { readState } = await import("./trace-DZZ7QYJT.js");
12295
12312
  const ref = id2 ?? readState()?.trace_id;
12296
12313
  if (!ref) throw new Error("name a trace, or start one here");
12297
12314
  const bundle = await api("GET", `/traces/${ref}`);
@@ -12318,7 +12335,7 @@ traceCmd.command("show [id]").description("the trace bundle: spans, the sessions
12318
12335
  for (const gap of bundle.gaps) console.log(` gap: ${gap.span_id} ${gap.reason}`);
12319
12336
  }));
12320
12337
  traceCmd.command("stop").description("end the root span, send what is left, and revoke this machine's grant").action(run(async () => {
12321
- const { readState, record, flush, grantSender, clearState } = await import("./trace-LAMM6QJG.js");
12338
+ const { readState, record, flush, grantSender, clearState } = await import("./trace-DZZ7QYJT.js");
12322
12339
  const state = readState();
12323
12340
  if (!state) throw new Error("no trace is running here");
12324
12341
  if (state.root_span) record(() => [{ span_id: state.root_span, kind: "end", outcome: "completed" }]);
@@ -12327,8 +12344,74 @@ traceCmd.command("stop").description("end the root span, send what is left, and
12327
12344
  clearState();
12328
12345
  console.log(`Stopped ${state.trace_id}${outcome.pending ? ` (${outcome.pending} events could not be sent)` : ""}`);
12329
12346
  }));
12347
+ var recordCmd = traceCmd.command("record").description("record every Claude Code session on this machine with its environment into your own vault (~/.trace-vault); nothing is uploaded").option("--enable", "install the recording hooks and start recording new sessions").option("--disable", "remove the recording hooks; what was recorded stays in the vault").option("--vault <dir>", "with --enable: where to keep the vault (default ~/.trace-vault)").option("--max-size <size>", "keep the vault under this size (e.g. 20G); past it the oldest stored file contents are deleted first, never transcripts; 0 removes the cap").option("--settings <path>", "with --enable or --disable: the Claude Code settings file for the hooks (default ~/.claude/settings.json)").action(run(async (opts) => {
12348
+ const { homedir: homedir13 } = await import("os");
12349
+ const { join: join23 } = await import("path");
12350
+ const vault2 = await import("./trace-vault-IUNYRVGZ.js");
12351
+ const { installClaudeHooks, uninstallClaudeHooks } = await import("./trace-DZZ7QYJT.js");
12352
+ const command = "sky trace record hook";
12353
+ const config = vault2.loadVaultConfig();
12354
+ const settings = resolve11(opts.settings ?? config.settings ?? join23(process.env.CLAUDE_CONFIG_DIR ?? join23(homedir13(), ".claude"), "settings.json"));
12355
+ if (opts.enable && opts.disable) throw new Error("choose --enable or --disable");
12356
+ const maxBytes = opts.maxSize === void 0 ? config.max_bytes : opts.maxSize.trim() === "0" ? void 0 : vault2.parseSize(opts.maxSize);
12357
+ if (opts.maxSize !== void 0 && !opts.enable && !opts.disable) {
12358
+ vault2.saveVaultConfig({ ...config, max_bytes: maxBytes });
12359
+ const freed = maxBytes ? vault2.enforceCap(vault2.vaultDir(config), maxBytes) : 0;
12360
+ console.log(maxBytes ? `The vault is kept under ${vault2.formatBytes(maxBytes)}${freed ? `; freed ${vault2.formatBytes(freed)} of the oldest stored files` : ""}.` : "The vault has no size cap.");
12361
+ return;
12362
+ }
12363
+ if (opts.enable) {
12364
+ const next = { enabled: true, vault: resolve11(opts.vault ?? config.vault ?? join23(homedir13(), ".trace-vault")), settings, enabled_at: (/* @__PURE__ */ new Date()).toISOString(), max_bytes: maxBytes };
12365
+ vault2.saveVaultConfig(next);
12366
+ installClaudeHooks(settings, command, vault2.recordHooksConfig(command));
12367
+ console.log(`Recording Claude Code sessions into ${next.vault}`);
12368
+ console.log(` hooks: ${settings} (session start, each prompt, each turn end, session end)`);
12369
+ console.log(" each turn keeps its prompt, the agent's messages and tool calls, the workspace before and after, and the machine's environment");
12370
+ console.log(" credential-shaped files are listed without their contents; known secret values are replaced before anything is written");
12371
+ if (maxBytes) console.log(` kept under ${vault2.formatBytes(maxBytes)}: past it the oldest stored file contents go first, never transcripts`);
12372
+ console.log(" nothing leaves this machine; `sky trace record --disable` stops recording");
12373
+ return;
12374
+ }
12375
+ if (opts.disable) {
12376
+ vault2.saveVaultConfig({ ...config, enabled: false });
12377
+ const removed = uninstallClaudeHooks(settings, command);
12378
+ console.log(`Recording is off${removed ? ` (hooks removed from ${removed})` : ""}. The vault stays at ${vault2.vaultDir(config)}.`);
12379
+ return;
12380
+ }
12381
+ const status = vault2.vaultStatus(vault2.vaultDir(config));
12382
+ console.log(`Recording is ${config.enabled ? "on" : "off"}${config.enabled_at ? ` (since ${config.enabled_at})` : ""}. Vault: ${vault2.vaultDir(config)}`);
12383
+ console.log(` ${status.sessions} sessions, ${status.turns} turns, ${status.segments} segments, ${vault2.formatBytes(status.bytes)}${config.max_bytes ? ` of a ${vault2.formatBytes(config.max_bytes)} cap` : ""}; last sealed ${status.last_sealed_at ?? "never"}`);
12384
+ if (config.max_bytes && status.bytes > config.max_bytes) console.log(" over the cap: no stored file contents are left to delete, only transcripts and records, which are always kept");
12385
+ if (status.partial || status.failures) console.log(` ${status.partial} sessions with a partial environment; ${status.failures} hook failures (${join23(vault2.vaultDir(config), "failures.jsonl")})`);
12386
+ if (config.enabled && !status.segments) console.log(" nothing recorded yet: start a new Claude Code session");
12387
+ }));
12388
+ recordCmd.command("hook").description("seal one segment at a Claude Code hook boundary read from stdin (run by the installed hooks; never fails, prints nothing)").action(async () => {
12389
+ let input = {};
12390
+ const vault2 = await import("./trace-vault-IUNYRVGZ.js");
12391
+ const config = vault2.loadVaultConfig();
12392
+ if (!config.enabled) return;
12393
+ const dir = vault2.vaultDir(config);
12394
+ try {
12395
+ const chunks = [];
12396
+ for await (const chunk of process.stdin) chunks.push(chunk);
12397
+ input = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
12398
+ const job = vault2.cutSegment(input, dir);
12399
+ if (!job) return;
12400
+ vault2.startSealer(vault2.sessionDir(dir, job.session_id), job, [process.execPath, process.argv[1], "trace", "record", "seal"]);
12401
+ } catch (error) {
12402
+ vault2.markPartial(dir, input.session_id, error);
12403
+ }
12404
+ });
12405
+ recordCmd.command("seal <session-dir>").description("seal the cut segments of one recorded session (started by the hook in the background)").action(async (session2) => {
12406
+ const vault2 = await import("./trace-vault-IUNYRVGZ.js");
12407
+ try {
12408
+ await vault2.sealPending(resolve11(session2), { maxBytes: vault2.loadVaultConfig().max_bytes });
12409
+ } catch (error) {
12410
+ vault2.markPartial(resolve11(session2, "..", "..", ".."), session2.split(/[\\/]/).filter(Boolean).pop(), error);
12411
+ }
12412
+ });
12330
12413
  traceCmd.command("sync [payload]").description("upload this machine's agent sessions (Claude Code, Codex, Cursor, Gemini CLI and every other agent `--agents` lists) to the matching workspace's trace library, redacted here first").option("--enable", "turn sync on for this machine").option("--disable", "turn sync off; nothing more is uploaded").option("--route <match=workspace>", "send sessions whose folder path contains <match> to <workspace> (repeatable; replaces the saved rules)", collect).option("--default <workspace>", "where a session no rule matches goes").option("--keep-local", "keep sessions no rule matches on this machine (the default)").option("--session <ref>", "only this session: its id or transcript path (repeatable)", collect).option("--import <export>", "add a downloaded cloud export (claude.ai, ChatGPT, Gemini, Grok, DeepSeek \u2026: its .zip, folder or file) so sync uploads it (repeatable)", collect).option("--agents", "list the agents sync reads and which are on this machine").option("--full", "re-read every session, not only files that changed").option("--limit <n>", "at most this many changed sessions this run", (v) => Number.parseInt(v, 10)).option("--dry-run", "show what would be uploaded without uploading").option("--hook", "run from a Claude Code SessionEnd hook or Codex notify: upload that session in the background and return at once").option("--install-schedule", "also sweep every 15 minutes (macOS launchd)").option("--status", "what sync has done on this machine").option("--quiet", "print only failures").action(async (payload, opts) => {
12331
- const lib = await import("./trace-library-AFHVFATX.js");
12414
+ const lib = await import("./trace-library-VZX576JO.js");
12332
12415
  if (opts.hook) {
12333
12416
  try {
12334
12417
  let raw = payload ?? "";
@@ -12444,7 +12527,7 @@ traceCmd.command("search <query...>").description("search every session in a wor
12444
12527
  console.log(opts.json ? JSON.stringify(page, null, 2) : renderContextPage(page));
12445
12528
  }));
12446
12529
  traceCmd.command("library").description("list the sessions in a workspace's trace library, most recently updated first").option("--workspace <slug>", "the workspace (default: the current one)").option("--limit <n>", "how many", (v) => Number.parseInt(v, 10), 20).option("--json", "print the page as JSON").action(run(async (opts) => {
12447
- const { libraryRequest } = await import("./trace-library-AFHVFATX.js");
12530
+ const { libraryRequest } = await import("./trace-library-VZX576JO.js");
12448
12531
  const workspace2 = opts.workspace ?? currentUniverse();
12449
12532
  if (!workspace2) throw new Error("name a workspace with --workspace");
12450
12533
  const page = await libraryRequest("GET", `/trace-library?limit=${opts.limit}`, workspace2);
@@ -2,7 +2,7 @@ import {
2
2
  admittedInputScopeSchema,
3
3
  external_exports,
4
4
  messagePartSchema
5
- } from "./chunk-VFN3NGC6.js";
5
+ } from "./chunk-5CWYSS5Q.js";
6
6
  import "./chunk-MLKGABMK.js";
7
7
 
8
8
  // ../../packages/chat/src/stream.ts
@@ -1,11 +1,13 @@
1
1
  import {
2
- USER_AGENT,
3
- configPath
4
- } from "./chunk-EG7PA52K.js";
2
+ USER_AGENT
3
+ } from "./chunk-WWWRFIK5.js";
5
4
  import {
6
5
  TRACE_CONTENT_SCOPES,
7
6
  redactTraceText
8
- } from "./chunk-VFN3NGC6.js";
7
+ } from "./chunk-5CWYSS5Q.js";
8
+ import {
9
+ configPath
10
+ } from "./chunk-XHZJG3QT.js";
9
11
  import "./chunk-MLKGABMK.js";
10
12
 
11
13
  // src/trace.ts
@@ -228,18 +230,25 @@ function claudeHooksConfig(command = "sky trace hook") {
228
230
  SessionEnd: entry
229
231
  };
230
232
  }
231
- function installClaudeHooks(settingsPath, command = "sky trace hook") {
233
+ function rewriteClaudeHooks(settingsPath, command, add) {
232
234
  const settings = existsSync(settingsPath) ? JSON.parse(readFileSync(settingsPath, "utf8")) : {};
233
235
  const hooks = settings.hooks ?? {};
234
- for (const [event, entries] of Object.entries(claudeHooksConfig(command))) {
235
- const existing = (hooks[event] ?? []).filter((group) => !group.hooks?.some((hook) => hook.command === command));
236
- hooks[event] = [...existing, ...entries];
236
+ for (const event of Object.keys(hooks)) {
237
+ hooks[event] = hooks[event].filter((group) => !group.hooks?.some((hook) => hook.command === command));
238
+ if (!hooks[event].length) delete hooks[event];
237
239
  }
240
+ for (const [event, entries] of Object.entries(add)) hooks[event] = [...hooks[event] ?? [], ...entries];
238
241
  mkdirSync(dirname(settingsPath), { recursive: true });
239
242
  writeFileSync(settingsPath, `${JSON.stringify({ ...settings, hooks }, null, 2)}
240
243
  `);
241
244
  return settingsPath;
242
245
  }
246
+ function installClaudeHooks(settingsPath, command = "sky trace hook", config = claudeHooksConfig(command)) {
247
+ return rewriteClaudeHooks(settingsPath, command, config);
248
+ }
249
+ function uninstallClaudeHooks(settingsPath, command) {
250
+ return existsSync(settingsPath) ? rewriteClaudeHooks(settingsPath, command, {}) : null;
251
+ }
243
252
  var FILE_READ_MAX_BYTES = 1024 * 1024;
244
253
  var FILE_TOOLS = /* @__PURE__ */ new Set(["Read", "Write", "Edit", "MultiEdit", "NotebookEdit"]);
245
254
  var CONTENT_ESCAPED_MAX_BYTES = 56 * 1024;
@@ -363,5 +372,6 @@ export {
363
372
  spoolStatus,
364
373
  stamp,
365
374
  traceDir,
375
+ uninstallClaudeHooks,
366
376
  writeState
367
377
  };
@@ -1,19 +1,21 @@
1
1
  import {
2
2
  ApiError,
3
3
  uploadLargeFile
4
- } from "./chunk-6IVMEGJO.js";
4
+ } from "./chunk-TLR374RK.js";
5
5
  import {
6
- USER_AGENT,
7
- apiBase,
8
- apiToken
9
- } from "./chunk-EG7PA52K.js";
6
+ USER_AGENT
7
+ } from "./chunk-WWWRFIK5.js";
10
8
  import {
11
9
  SessionSourceCollector,
12
10
  UnsafeImportError,
13
11
  publicRemote,
14
12
  redactLine,
15
13
  redactTraceText
16
- } from "./chunk-VFN3NGC6.js";
14
+ } from "./chunk-5CWYSS5Q.js";
15
+ import {
16
+ apiBase,
17
+ apiToken
18
+ } from "./chunk-XHZJG3QT.js";
17
19
  import "./chunk-MLKGABMK.js";
18
20
 
19
21
  // src/trace-library.ts
@@ -0,0 +1,743 @@
1
+ import {
2
+ configPath
3
+ } from "./chunk-XHZJG3QT.js";
4
+ import "./chunk-MLKGABMK.js";
5
+
6
+ // src/trace-vault.ts
7
+ import { execFile, spawn, spawnSync } from "child_process";
8
+ import { createHash, randomBytes } from "crypto";
9
+ import {
10
+ closeSync,
11
+ copyFileSync,
12
+ existsSync,
13
+ mkdirSync,
14
+ openSync,
15
+ readdirSync,
16
+ readFileSync,
17
+ readSync,
18
+ renameSync,
19
+ rmSync,
20
+ statfsSync,
21
+ statSync,
22
+ writeFileSync,
23
+ appendFileSync,
24
+ lstatSync,
25
+ readlinkSync
26
+ } from "fs";
27
+ import { homedir, platform, release } from "os";
28
+ import { basename, dirname, join, relative, resolve, sep } from "path";
29
+ var TURN_START_HOLD_MS = 2e3;
30
+ var DISK_FLOOR_BYTES = 1024 ** 3;
31
+ var SCRUB_MAX_BYTES = 64 * 1024 * 1024;
32
+ var TRANSCRIPT_SETTLE_MS = 300;
33
+ var TRANSCRIPT_SETTLE_MAX_MS = 1500;
34
+ var LOCK_STALE_MS = 10 * 60 * 1e3;
35
+ var COMMAND_TIMEOUT_MS = 1e4;
36
+ var HARNESS = "claude-code";
37
+ var AGENT_TYPE = "claude_code";
38
+ var now = () => (/* @__PURE__ */ new Date()).toISOString();
39
+ function vaultConfigPath() {
40
+ return join(dirname(configPath()), "trace-vault.json");
41
+ }
42
+ function loadVaultConfig() {
43
+ try {
44
+ return JSON.parse(readFileSync(vaultConfigPath(), "utf8"));
45
+ } catch {
46
+ return { enabled: false };
47
+ }
48
+ }
49
+ function saveVaultConfig(config) {
50
+ mkdirSync(dirname(vaultConfigPath()), { recursive: true, mode: 448 });
51
+ writeFileSync(vaultConfigPath(), `${JSON.stringify(config, null, 2)}
52
+ `, { mode: 384 });
53
+ }
54
+ function vaultDir(config = loadVaultConfig()) {
55
+ return resolve(process.env.TRACE_VAULT_DIR ?? config.vault ?? join(homedir(), ".trace-vault"));
56
+ }
57
+ function sessionDir(vault, sessionId) {
58
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(sessionId)) throw new Error(`unusable session id ${JSON.stringify(sessionId)}`);
59
+ return join(vault, "sessions", HARNESS, sessionId);
60
+ }
61
+ function recordHooksConfig(command = "sky trace record hook") {
62
+ const entry = (timeout) => [{ hooks: [{ type: "command", command, timeout }] }];
63
+ return { SessionStart: entry(10), UserPromptSubmit: entry(10), Stop: entry(10), SessionEnd: entry(10) };
64
+ }
65
+ var reasonFor = { SessionStart: "boot", UserPromptSubmit: "turn_start", Stop: "turn_end", SessionEnd: "shutdown" };
66
+ function stateDir(session) {
67
+ return join(session, ".state");
68
+ }
69
+ function readJson(path, fallback) {
70
+ try {
71
+ return JSON.parse(readFileSync(path, "utf8"));
72
+ } catch {
73
+ return fallback;
74
+ }
75
+ }
76
+ function writeJson(path, value) {
77
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
78
+ const tmp = `${path}.${process.pid}.tmp`;
79
+ writeFileSync(tmp, JSON.stringify(value), { mode: 384 });
80
+ renameSync(tmp, path);
81
+ }
82
+ function readState(session) {
83
+ return readJson(join(stateDir(session), "state.json"), { epochs: [], next_sequence: 0, native_offsets: {}, call_names: {} });
84
+ }
85
+ function writeState(session, state) {
86
+ writeJson(join(stateDir(session), "state.json"), state);
87
+ }
88
+ function sleepSync(ms) {
89
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
90
+ }
91
+ function tryLock(path) {
92
+ try {
93
+ mkdirSync(path);
94
+ return true;
95
+ } catch {
96
+ try {
97
+ if (Date.now() - statSync(path).mtimeMs > LOCK_STALE_MS) rmSync(path, { recursive: true, force: true });
98
+ } catch {
99
+ }
100
+ return false;
101
+ }
102
+ }
103
+ function withLock(path, waitMs, fn) {
104
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
105
+ const deadline = Date.now() + waitMs;
106
+ while (!tryLock(path)) {
107
+ if (Date.now() > deadline) throw new Error(`${path} is busy`);
108
+ sleepSync(20);
109
+ }
110
+ try {
111
+ return fn();
112
+ } finally {
113
+ rmSync(path, { recursive: true, force: true });
114
+ }
115
+ }
116
+ function newEpoch() {
117
+ return `${Date.now().toString(36)}-${randomBytes(3).toString("hex")}`;
118
+ }
119
+ function inboundRecord(prompt, at) {
120
+ const id = randomBytes(16).toString("hex");
121
+ return {
122
+ t: at,
123
+ id,
124
+ message: { id, role: "user", created_at: at, parts: [{ type: "text", index: 0, text: prompt }], content: [], system: [], metadata: {} }
125
+ };
126
+ }
127
+ function cutSegment(input, vault, at = now()) {
128
+ const reason = reasonFor[input.hook_event_name ?? ""];
129
+ if (!reason || !input.session_id) return null;
130
+ const session = sessionDir(vault, input.session_id);
131
+ return withLock(join(stateDir(session), "cut.lock"), 3e3, () => {
132
+ const state = readState(session);
133
+ let startedMid = false;
134
+ if (reason === "boot" || !state.epoch) {
135
+ startedMid = reason !== "boot";
136
+ state.epoch = newEpoch();
137
+ state.epochs.push(state.epoch);
138
+ state.next_sequence = 0;
139
+ state.opened_at = at;
140
+ }
141
+ const sequence = String(state.next_sequence++).padStart(6, "0");
142
+ const pending = join(session, state.epoch, `.pending-${sequence}`);
143
+ mkdirSync(pending, { recursive: true, mode: 448 });
144
+ const open = join(stateDir(session), "open");
145
+ for (const name of existsSync(open) ? readdirSync(open) : []) renameSync(join(open, name), join(pending, name));
146
+ const job = {
147
+ reason,
148
+ epoch: state.epoch,
149
+ sequence,
150
+ opened_at: state.opened_at ?? at,
151
+ cut_at: at,
152
+ session_id: input.session_id,
153
+ ...input.transcript_path ? { transcript_path: input.transcript_path } : {},
154
+ ...input.cwd ? { cwd: input.cwd } : {},
155
+ ...startedMid ? { started_mid_session: true } : {},
156
+ ...input.source ? { hook_source: input.source } : {},
157
+ ...input.reason ? { end_reason: input.reason } : {}
158
+ };
159
+ writeJson(join(pending, "job.json"), job);
160
+ state.opened_at = at;
161
+ if (reason === "turn_start" && input.prompt !== void 0) {
162
+ mkdirSync(open, { recursive: true, mode: 448 });
163
+ appendFileSync(join(open, "inbound.jsonl"), `${JSON.stringify(inboundRecord(input.prompt, at))}
164
+ `, { mode: 384 });
165
+ }
166
+ writeState(session, state);
167
+ return job;
168
+ });
169
+ }
170
+ function markPartial(vault, sessionId, error) {
171
+ try {
172
+ if (!sessionId) return;
173
+ const session = sessionDir(vault, sessionId);
174
+ appendFileSync(join(vault, "failures.jsonl"), `${JSON.stringify({ t: now(), session_id: sessionId, error: String(error instanceof Error ? error.message : error) })}
175
+ `);
176
+ withLock(join(stateDir(session), "cut.lock"), 3e3, () => {
177
+ const state = readState(session);
178
+ state.partial = true;
179
+ writeState(session, state);
180
+ });
181
+ } catch {
182
+ }
183
+ }
184
+ function sealedPath(session, job) {
185
+ return join(session, job.epoch, job.sequence);
186
+ }
187
+ function startSealer(session, job, argv, holdMs = TURN_START_HOLD_MS) {
188
+ const child = spawn(argv[0], [...argv.slice(1), session], { detached: true, stdio: "ignore" });
189
+ child.unref();
190
+ if (job.reason !== "turn_start") return true;
191
+ const deadline = Date.now() + holdMs;
192
+ while (Date.now() < deadline) {
193
+ if (existsSync(join(sealedPath(session, job), "manifest.json"))) return true;
194
+ sleepSync(25);
195
+ }
196
+ return false;
197
+ }
198
+ function pendingJobs(session, state) {
199
+ return state.epochs.flatMap((epoch) => {
200
+ const folder = join(session, epoch);
201
+ if (!existsSync(folder)) return [];
202
+ return readdirSync(folder).filter((name) => name.startsWith(".pending-")).sort().flatMap((name) => {
203
+ const job = readJson(join(folder, name, "job.json"), null);
204
+ return job ? [{ dir: join(folder, name), job }] : [];
205
+ });
206
+ });
207
+ }
208
+ async function sealPending(session, options = {}) {
209
+ const lock = join(stateDir(session), "seal.lock");
210
+ mkdirSync(dirname(lock), { recursive: true, mode: 448 });
211
+ const deadline = Date.now() + LOCK_STALE_MS;
212
+ while (!tryLock(lock)) {
213
+ if (Date.now() > deadline) throw new Error(`${lock} is busy`);
214
+ await new Promise((wake) => setTimeout(wake, 20));
215
+ }
216
+ let sealed = 0;
217
+ try {
218
+ for (; ; ) {
219
+ const next = pendingJobs(session, readState(session))[0];
220
+ if (!next) {
221
+ if (options.maxBytes) enforceCap(resolve(session, "..", "..", ".."), options.maxBytes);
222
+ return sealed;
223
+ }
224
+ await sealOne(session, next.dir, next.job, options.claudeHome ?? process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"));
225
+ sealed++;
226
+ }
227
+ } finally {
228
+ rmSync(lock, { recursive: true, force: true });
229
+ }
230
+ }
231
+ function secretValues(environ = process.env) {
232
+ return Object.entries(environ).filter((entry) => /(TOKEN|SECRET|KEY|PASSWORD|CREDENTIAL)/i.test(entry[0]) && typeof entry[1] === "string" && entry[1].length >= 8).sort((a, b) => b[1].length - a[1].length);
233
+ }
234
+ function scrubSecrets(text, secrets) {
235
+ let out = text;
236
+ for (const [name, value] of secrets) out = out.split(value).join(`[secret:${name}]`);
237
+ return { text: out, scrubbed: out !== text };
238
+ }
239
+ var CACHE_DIRS = /* @__PURE__ */ new Set([".git", ".cache", ".npm", ".bun", ".yarn", ".pnpm-store", "node_modules", ".venv", "__pycache__"]);
240
+ var CREDENTIAL_FILE = /(^\.?credentials(\.json)?$|^auth\.json$|^\.netrc$|^\.git-credentials$|^\.pgpass$|^\.npmrc$|^\.pypirc$|^\.env(\..+)?$|^id_[a-z0-9]+$|\.(pem|key|p12|pfx|keystore|jks|kdbx)$|oauth|token)/i;
241
+ function sha256File(path) {
242
+ const hash = createHash("sha256");
243
+ const fd = openSync(path, "r");
244
+ try {
245
+ const buffer = Buffer.allocUnsafe(1024 * 1024);
246
+ for (let read = readSync(fd, buffer); read > 0; read = readSync(fd, buffer)) hash.update(buffer.subarray(0, read));
247
+ } finally {
248
+ closeSync(fd);
249
+ }
250
+ return hash.digest("hex");
251
+ }
252
+ function freeBytes(path) {
253
+ try {
254
+ const fs = statfsSync(path);
255
+ return Number(fs.bavail) * Number(fs.bsize);
256
+ } catch {
257
+ return Number.POSITIVE_INFINITY;
258
+ }
259
+ }
260
+ function workspaceRoot(cwd, home = homedir()) {
261
+ if (!cwd || !existsSync(cwd)) return null;
262
+ const top = spawnSync("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8", timeout: COMMAND_TIMEOUT_MS });
263
+ const root = resolve(top.status === 0 && top.stdout.trim() ? top.stdout.trim() : cwd);
264
+ return root === resolve(home) || root === resolve("/") ? null : root;
265
+ }
266
+ function readTree(root, segment, shipped, cache, secrets, exclude = []) {
267
+ const entries = [];
268
+ const walk = (dir) => {
269
+ let names;
270
+ try {
271
+ names = readdirSync(dir).sort();
272
+ } catch {
273
+ return;
274
+ }
275
+ for (const name of names) {
276
+ const path = join(dir, name);
277
+ if (exclude.some((skip) => path === skip || path.startsWith(`${skip}${sep}`))) continue;
278
+ const rel = relative(root, path).split(sep).join("/");
279
+ let info;
280
+ try {
281
+ info = lstatSync(path);
282
+ } catch {
283
+ continue;
284
+ }
285
+ if (info.isSymbolicLink()) {
286
+ try {
287
+ entries.push({ path: rel, link: readlinkSync(path) });
288
+ } catch {
289
+ }
290
+ continue;
291
+ }
292
+ if (info.isDirectory()) {
293
+ if (!CACHE_DIRS.has(name)) walk(path);
294
+ continue;
295
+ }
296
+ if (!info.isFile()) continue;
297
+ const mode = info.mode & 4095;
298
+ if (CREDENTIAL_FILE.test(name)) {
299
+ entries.push({ path: rel, size: info.size, mode, withheld: true });
300
+ continue;
301
+ }
302
+ const stamp = [info.size, Math.trunc(info.mtimeMs * 1e3)];
303
+ let digest;
304
+ try {
305
+ const cached = cache[path];
306
+ digest = cached && cached[0] === stamp[0] && cached[1] === stamp[1] ? cached[2] : sha256File(path);
307
+ } catch {
308
+ entries.push({ path: rel, size: info.size, mode, not_stored: "unreadable" });
309
+ continue;
310
+ }
311
+ cache[path] = [...stamp, digest];
312
+ const entry = { path: rel, size: info.size, mode, sha256: digest };
313
+ if (!shipped[digest]) {
314
+ const stored = storeBlob(path, segment, digest, info.size, secrets);
315
+ if (stored === "disk_floor" || stored === "unreadable") entry.not_stored = stored;
316
+ else {
317
+ if (stored.scrubbed) entry.scrubbed = true;
318
+ if (stored.digest !== digest) {
319
+ entry.sha256 = digest = stored.digest;
320
+ entry.changed_while_read = true;
321
+ delete cache[path];
322
+ }
323
+ shipped[digest] = true;
324
+ }
325
+ }
326
+ entries.push(entry);
327
+ }
328
+ };
329
+ walk(root);
330
+ return entries;
331
+ }
332
+ function storeBlob(path, segment, digest, size, secrets) {
333
+ const blobs = join(segment, "blobs");
334
+ if (freeBytes(segment) - size < DISK_FLOOR_BYTES) return "disk_floor";
335
+ mkdirSync(blobs, { recursive: true });
336
+ try {
337
+ if (size > SCRUB_MAX_BYTES) {
338
+ copyFileSync(path, join(blobs, digest));
339
+ const read2 = sha256File(join(blobs, digest));
340
+ if (read2 !== digest) renameSync(join(blobs, digest), join(blobs, read2));
341
+ return { digest: read2, scrubbed: false };
342
+ }
343
+ const bytes = readFileSync(path);
344
+ const read = createHash("sha256").update(bytes).digest("hex");
345
+ const clean = secrets.length && !bytes.includes(0) ? scrubSecrets(bytes.toString("utf8"), secrets) : null;
346
+ writeFileSync(join(blobs, read), clean?.scrubbed ? clean.text : bytes);
347
+ return { digest: read, scrubbed: Boolean(clean?.scrubbed) };
348
+ } catch {
349
+ return "unreadable";
350
+ }
351
+ }
352
+ function run(argv) {
353
+ return new Promise((done) => {
354
+ execFile(argv[0], argv.slice(1), { encoding: "utf8", timeout: COMMAND_TIMEOUT_MS, maxBuffer: 32 * 1024 * 1024 }, (error, stdout, stderr) => {
355
+ if (error && typeof error.code !== "number") done({ error: `${error.name}: ${error.message}` });
356
+ else done({ exit: error ? error.code : 0, stdout, stderr: stderr.slice(-2e3) });
357
+ });
358
+ });
359
+ }
360
+ var LOCKFILES = [
361
+ "package-lock.json",
362
+ "pnpm-lock.yaml",
363
+ "yarn.lock",
364
+ "bun.lockb",
365
+ "bun.lock",
366
+ "uv.lock",
367
+ "poetry.lock",
368
+ "Pipfile.lock",
369
+ "requirements.txt",
370
+ "Cargo.lock",
371
+ "go.sum",
372
+ "Gemfile.lock",
373
+ "composer.lock",
374
+ "mix.lock",
375
+ "pubspec.lock",
376
+ "Package.resolved"
377
+ ];
378
+ async function readEnvironment(root) {
379
+ const commands = {
380
+ uname: ["uname", "-a"],
381
+ node: ["node", "--version"],
382
+ npm: ["npm", "--version"],
383
+ npm_global: ["npm", "ls", "-g", "--depth=0", "--json"],
384
+ python: ["python3", "--version"],
385
+ pip: ["python3", "-m", "pip", "list", "--format=json"],
386
+ git: ["git", "--version"],
387
+ ...platform() === "darwin" ? { sw_vers: ["sw_vers"], brew: ["brew", "list", "--versions"] } : { os_release: ["cat", "/etc/os-release"], apt: ["dpkg-query", "-W", "-f=${Package} ${Version}\n"] }
388
+ };
389
+ const captured = { env_names: Object.keys(process.env).sort(), platform: platform(), release: release(), arch: process.arch };
390
+ const [results, repositories] = await Promise.all([
391
+ Promise.all(Object.entries(commands).map(async ([name, argv]) => [name, await run(argv)])),
392
+ root ? gitRepositories(root) : Promise.resolve([])
393
+ ]);
394
+ for (const [name, result] of results) captured[name] = result;
395
+ captured.lockfiles = root ? LOCKFILES.filter((name) => existsSync(join(root, name))) : [];
396
+ captured.git_repositories = repositories;
397
+ return captured;
398
+ }
399
+ async function gitRepositories(root) {
400
+ const found = [];
401
+ const walk = (dir, depth) => {
402
+ let names;
403
+ try {
404
+ names = readdirSync(dir);
405
+ } catch {
406
+ return;
407
+ }
408
+ if (names.includes(".git")) found.push(gitState(root, dir));
409
+ if (depth >= 3) return;
410
+ for (const name of names) {
411
+ if (CACHE_DIRS.has(name)) continue;
412
+ try {
413
+ if (lstatSync(join(dir, name)).isDirectory()) walk(join(dir, name), depth + 1);
414
+ } catch {
415
+ }
416
+ }
417
+ };
418
+ walk(root, 0);
419
+ return Promise.all(found);
420
+ }
421
+ async function gitState(root, dir) {
422
+ const queries = [["head", ["rev-parse", "HEAD"]], ["branch", ["rev-parse", "--abbrev-ref", "HEAD"]], ["status", ["status", "--porcelain"]], ["remotes", ["remote", "-v"]], ["log", ["log", "--oneline", "-20"]]];
423
+ const answers = await Promise.all(queries.map(([, args]) => run(["git", "-C", dir, ...args])));
424
+ const info = { path: relative(root, dir).split(sep).join("/") || "." };
425
+ queries.forEach(([key], index) => {
426
+ const out = answers[index];
427
+ info[key] = "stdout" in out ? out.stdout.replace(/:\/\/[^/@\s]+@/g, "://[credentials]@") : null;
428
+ });
429
+ return info;
430
+ }
431
+ var INSTRUCTION_FILES = ["CLAUDE.md", "AGENTS.md", "GEMINI.md", ".claude/CLAUDE.md", "CLAUDE.local.md"];
432
+ function instructionFiles(root) {
433
+ const found = {};
434
+ for (const name of root ? INSTRUCTION_FILES : []) {
435
+ try {
436
+ const path = join(root, name);
437
+ if (lstatSync(path).isFile()) found[name] = readFileSync(path, "utf8");
438
+ } catch {
439
+ }
440
+ }
441
+ return found;
442
+ }
443
+ function waitForSettled(path) {
444
+ const deadline = Date.now() + TRANSCRIPT_SETTLE_MAX_MS;
445
+ let last = -1;
446
+ for (; ; ) {
447
+ const size = existsSync(path) ? statSync(path).size : 0;
448
+ if (size === last || Date.now() > deadline) return;
449
+ last = size;
450
+ sleepSync(TRANSCRIPT_SETTLE_MS);
451
+ }
452
+ }
453
+ function nativeFiles(transcript, sessionId) {
454
+ if (!transcript || !existsSync(transcript)) return [];
455
+ const files = [transcript];
456
+ const beside = join(dirname(transcript), sessionId);
457
+ const walk = (dir) => {
458
+ for (const name of existsSync(dir) ? readdirSync(dir).sort() : []) {
459
+ const path = join(dir, name);
460
+ try {
461
+ const info = lstatSync(path);
462
+ if (info.isDirectory()) walk(path);
463
+ else if (info.isFile()) files.push(path);
464
+ } catch {
465
+ }
466
+ }
467
+ };
468
+ walk(beside);
469
+ return files;
470
+ }
471
+ function nativeDelta(files, claudeHome, segment, offsets, secrets) {
472
+ const native = [];
473
+ const lines = [];
474
+ for (const file of files) {
475
+ const size = statSync(file).size;
476
+ const previous = offsets[file] ?? 0;
477
+ const rewritten = size < previous;
478
+ const start = rewritten ? 0 : previous;
479
+ if (size === start) continue;
480
+ const fd = openSync(file, "r");
481
+ const bytes = Buffer.alloc(size - start);
482
+ try {
483
+ readSync(fd, bytes, 0, bytes.length, start);
484
+ } finally {
485
+ closeSync(fd);
486
+ }
487
+ const end = bytes.lastIndexOf(10) + 1;
488
+ if (end === 0) continue;
489
+ const chunk = bytes.subarray(0, end).toString("utf8");
490
+ const rel = relative(claudeHome, file).startsWith("..") ? basename(file) : relative(claudeHome, file).split(sep).join("/");
491
+ const name = rewritten ? rel : `${rel}@${start}`;
492
+ const target = join(segment, "native", name);
493
+ mkdirSync(dirname(target), { recursive: true });
494
+ const clean = scrubSecrets(chunk, secrets);
495
+ writeFileSync(target, clean.text);
496
+ native.push({ path: rel, file: `native/${name}`, offset: start, bytes: end, ...rewritten ? { rewritten: true } : {}, ...clean.scrubbed ? { scrubbed: true } : {} });
497
+ lines.push({ file, text: chunk });
498
+ offsets[file] = start + end;
499
+ }
500
+ return { native, lines };
501
+ }
502
+ function eventsFromClaudeRows(rows, callNames) {
503
+ const events = [];
504
+ for (const row of rows) {
505
+ const content = row.message?.content;
506
+ if (!Array.isArray(content) || !row.uuid) continue;
507
+ const parts = [];
508
+ for (const block of content) {
509
+ const index = parts.length;
510
+ if (row.type === "assistant") {
511
+ if (block.type === "text") parts.push({ type: "text", index, text: String(block.text ?? "") });
512
+ else if (block.type === "thinking") parts.push({ type: "reasoning", index, text: String(block.thinking ?? ""), redacted: false });
513
+ else if (block.type === "redacted_thinking") parts.push({ type: "reasoning", index, text: "", redacted: true });
514
+ else if (block.type === "tool_use") {
515
+ const callId = String(block.id ?? "");
516
+ const toolName = String(block.name ?? "");
517
+ callNames[callId] = toolName;
518
+ parts.push({ type: "tool_call", index, call_id: callId, tool_name: toolName, args: block.input ?? {} });
519
+ }
520
+ } else if (row.type === "user" && block.type === "tool_result") {
521
+ const callId = String(block.tool_use_id ?? "");
522
+ parts.push({ type: "tool_result", index, call_id: callId, tool_name: callNames[callId] ?? "", status: block.is_error ? "error" : "ok", result: { content: block.content ?? null } });
523
+ }
524
+ }
525
+ if (!parts.length) continue;
526
+ const at = row.timestamp ?? now();
527
+ events.push({
528
+ id: row.uuid,
529
+ type: "message",
530
+ detail: null,
531
+ created_at: at,
532
+ data: {
533
+ message: {
534
+ id: row.uuid,
535
+ role: "agent",
536
+ created_at: at,
537
+ parts,
538
+ content: [],
539
+ system: [],
540
+ metadata: { native_role: row.message?.role ?? row.type, ...row.message?.model ? { model: row.message.model } : {}, ...row.message?.id ? { native_message_id: row.message.id } : {}, ...row.isSidechain ? { sidechain: true } : {} }
541
+ }
542
+ }
543
+ });
544
+ }
545
+ return events;
546
+ }
547
+ function parseRows(text) {
548
+ return text.split("\n").flatMap((line) => {
549
+ if (!line.trim()) return [];
550
+ try {
551
+ return [JSON.parse(line)];
552
+ } catch {
553
+ return [];
554
+ }
555
+ });
556
+ }
557
+ function scrubSegmentFiles(segment, secrets) {
558
+ if (!secrets.length) return;
559
+ for (const name of readdirSync(segment)) {
560
+ if (!name.endsWith(".json") && !name.endsWith(".jsonl")) continue;
561
+ const path = join(segment, name);
562
+ const clean = scrubSecrets(readFileSync(path, "utf8"), secrets);
563
+ if (clean.scrubbed) writeFileSync(path, clean.text);
564
+ }
565
+ }
566
+ async function sealOne(session, pending, job, claudeHome) {
567
+ const secrets = secretValues();
568
+ const state = readState(session);
569
+ if (job.transcript_path && job.reason !== "turn_start") waitForSettled(job.transcript_path);
570
+ const root = workspaceRoot(job.cwd);
571
+ const environment = job.reason === "turn_start" ? null : readEnvironment(root);
572
+ const delta = nativeDelta(nativeFiles(job.transcript_path, job.session_id), claudeHome, pending, state.native_offsets, secrets);
573
+ const rows = delta.lines.flatMap((part) => parseRows(part.text));
574
+ const events = eventsFromClaudeRows(rows, state.call_names);
575
+ if (events.length) writeFileSync(join(pending, "events.jsonl"), events.map((event) => `${JSON.stringify(event)}
576
+ `).join(""));
577
+ const model = [...rows].reverse().find((row) => row.message?.model && row.message.model !== "<synthetic>")?.message?.model;
578
+ const version = [...rows].reverse().find((row) => row.version)?.version;
579
+ const shipped = readJson(join(stateDir(session), "blobs-shipped.json"), {});
580
+ const cache = readJson(join(stateDir(session), "tree-cache.json"), {});
581
+ const manifest = {
582
+ format: "agent-trace-segment",
583
+ format_version: 1,
584
+ epoch: job.epoch,
585
+ opened_at: job.opened_at,
586
+ sealed_at: job.cut_at,
587
+ reason: job.reason,
588
+ agent_type: AGENT_TYPE,
589
+ origin: "local",
590
+ capture: "exact",
591
+ conversation_id: null,
592
+ session_id: job.session_id,
593
+ harness_version: version ?? null,
594
+ model: model ?? null,
595
+ cwd: job.cwd ?? null,
596
+ workspace_root: root,
597
+ workdir_instructions: instructionFiles(root),
598
+ native: delta.native,
599
+ ...job.hook_source ? { start: job.hook_source } : {},
600
+ ...job.end_reason ? { end_reason: job.end_reason } : {},
601
+ ...job.started_mid_session ? { started_mid_session: true } : {}
602
+ };
603
+ manifest.trees_at = now();
604
+ const vault = resolve(session, "..", "..", "..");
605
+ const workspace = root ? readTree(root, pending, shipped, cache, secrets, [vault, claudeHome]) : [];
606
+ manifest.trees_done_at = now();
607
+ if (!root) manifest.workspace_skipped = job.cwd ? "home_or_root" : "no_cwd";
608
+ if (workspace.some((entry) => entry.not_stored)) manifest.environment = "partial";
609
+ writeFileSync(join(pending, "trees.json"), JSON.stringify({ workspace }));
610
+ writeJson(join(stateDir(session), "blobs-shipped.json"), shipped);
611
+ writeJson(join(stateDir(session), "tree-cache.json"), cache);
612
+ if (environment) writeFileSync(join(pending, "environment.json"), JSON.stringify(await environment));
613
+ withLock(join(stateDir(session), "cut.lock"), 3e3, () => {
614
+ const latest = readState(session);
615
+ latest.native_offsets = state.native_offsets;
616
+ latest.call_names = state.call_names;
617
+ writeState(session, latest);
618
+ if (latest.partial) manifest.environment = "partial";
619
+ });
620
+ rmSync(join(pending, "job.json"), { force: true });
621
+ writeFileSync(join(pending, "manifest.json"), JSON.stringify(manifest));
622
+ scrubSegmentFiles(pending, secrets);
623
+ renameSync(pending, sealedPath(session, job));
624
+ }
625
+ function formatBytes(bytes) {
626
+ const units = ["B", "KiB", "MiB", "GiB", "TiB"];
627
+ let value = bytes;
628
+ let unit = 0;
629
+ while (value >= 1024 && unit < units.length - 1) {
630
+ value /= 1024;
631
+ unit++;
632
+ }
633
+ return unit ? `${value.toFixed(1)} ${units[unit]}` : `${value} B`;
634
+ }
635
+ function parseSize(value) {
636
+ const match = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i.exec(value.trim());
637
+ if (!match) throw new Error(`unreadable size ${JSON.stringify(value)} (use e.g. 500M or 20G)`);
638
+ const power = " kmgt".indexOf((match[2] || " ").toLowerCase());
639
+ const bytes = Math.floor(Number(match[1]) * 1024 ** power);
640
+ if (bytes < 1) throw new Error("a vault cap must be at least one byte");
641
+ return bytes;
642
+ }
643
+ function treeBytes(path) {
644
+ try {
645
+ const info = lstatSync(path);
646
+ return info.isDirectory() ? readdirSync(path).reduce((sum, name) => sum + treeBytes(join(path, name)), 0) : info.size;
647
+ } catch {
648
+ return 0;
649
+ }
650
+ }
651
+ function enforceCap(vault, maxBytes) {
652
+ let excess = treeBytes(vault) - maxBytes;
653
+ if (excess <= 0) return 0;
654
+ const root = join(vault, "sessions", HARNESS);
655
+ const segments = [];
656
+ for (const id of existsSync(root) ? readdirSync(root) : []) {
657
+ for (const epoch of readdirSync(join(root, id)).filter((name) => !name.startsWith("."))) {
658
+ for (const seq of readdirSync(join(root, id, epoch)).filter((name) => /^\d{6}$/.test(name))) {
659
+ const dir = join(root, id, epoch, seq);
660
+ const manifest = readJson(join(dir, "manifest.json"), null);
661
+ if (manifest && existsSync(join(dir, "blobs"))) segments.push({ dir, sealed: manifest.sealed_at ?? "" });
662
+ }
663
+ }
664
+ }
665
+ segments.sort((a, b) => a.sealed.localeCompare(b.sealed));
666
+ let freed = 0;
667
+ for (const { dir } of segments) {
668
+ if (excess <= 0) break;
669
+ const evicted = [];
670
+ for (const blob of readdirSync(join(dir, "blobs")).sort()) {
671
+ if (excess <= 0) break;
672
+ const size = treeBytes(join(dir, "blobs", blob));
673
+ rmSync(join(dir, "blobs", blob), { force: true });
674
+ evicted.push(blob);
675
+ excess -= size;
676
+ freed += size;
677
+ }
678
+ if (!evicted.length) continue;
679
+ const manifest = readJson(join(dir, "manifest.json"), {});
680
+ manifest.evicted_blobs = [...manifest.evicted_blobs ?? [], ...evicted];
681
+ writeFileSync(join(dir, "manifest.json"), JSON.stringify(manifest));
682
+ appendFileSync(join(vault, "evictions.jsonl"), `${JSON.stringify({ t: now(), segment: relative(vault, dir), blobs: evicted })}
683
+ `);
684
+ }
685
+ return freed;
686
+ }
687
+ function vaultStatus(vault) {
688
+ const root = join(vault, "sessions", HARNESS);
689
+ let segments = 0;
690
+ let turns = 0;
691
+ let partial = 0;
692
+ let last = null;
693
+ let bytes = 0;
694
+ const sessions = existsSync(root) ? readdirSync(root) : [];
695
+ const size = (path) => {
696
+ const info = lstatSync(path);
697
+ return info.isDirectory() ? readdirSync(path).reduce((sum, name) => sum + size(join(path, name)), 0) : info.size;
698
+ };
699
+ for (const id of sessions) {
700
+ const session = join(root, id);
701
+ let sessionPartial = false;
702
+ for (const epoch of readdirSync(session).filter((name) => !name.startsWith("."))) {
703
+ for (const seq of readdirSync(join(session, epoch)).filter((name) => /^\d{6}$/.test(name))) {
704
+ const manifest = readJson(join(session, epoch, seq, "manifest.json"), null);
705
+ if (!manifest) continue;
706
+ segments++;
707
+ if (existsSync(join(session, epoch, seq, "inbound.jsonl"))) turns++;
708
+ if (manifest.environment === "partial") sessionPartial = true;
709
+ if (typeof manifest.sealed_at === "string" && (!last || manifest.sealed_at > last)) last = manifest.sealed_at;
710
+ }
711
+ }
712
+ if (sessionPartial) partial++;
713
+ bytes += size(session);
714
+ }
715
+ const failuresFile = join(vault, "failures.jsonl");
716
+ const failures = existsSync(failuresFile) ? readFileSync(failuresFile, "utf8").split("\n").filter(Boolean).length : 0;
717
+ return { sessions: sessions.length, segments, turns, partial, failures, last_sealed_at: last, bytes };
718
+ }
719
+ export {
720
+ DISK_FLOOR_BYTES,
721
+ TURN_START_HOLD_MS,
722
+ cutSegment,
723
+ enforceCap,
724
+ eventsFromClaudeRows,
725
+ formatBytes,
726
+ loadVaultConfig,
727
+ markPartial,
728
+ nativeDelta,
729
+ nativeFiles,
730
+ parseSize,
731
+ readEnvironment,
732
+ readTree,
733
+ recordHooksConfig,
734
+ saveVaultConfig,
735
+ scrubSecrets,
736
+ sealPending,
737
+ sessionDir,
738
+ startSealer,
739
+ vaultConfigPath,
740
+ vaultDir,
741
+ vaultStatus,
742
+ workspaceRoot
743
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsky/sky",
3
- "version": "3.34.0",
3
+ "version": "3.36.0",
4
4
  "description": "sky \u2014 the AgentSky developer CLI: launch and talk to long-lived agents from your terminal.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -19,7 +19,6 @@
19
19
  "dev": "tsx src/index.ts",
20
20
  "build": "tsup src/index.ts --format esm --target node20 --clean",
21
21
  "test": "vitest run",
22
- "sync:served-skill": "tsx scripts/sync-served-skill.ts",
23
22
  "typecheck": "tsc --noEmit"
24
23
  },
25
24
  "dependencies": {