@agentsky/sky 3.48.1 → 3.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/chunk-2H4W5ZKZ.js +34 -0
  2. package/dist/{chunk-W24YSGH4.js → chunk-2YUZZ5VG.js} +7 -856
  3. package/dist/{chunk-E7HNEQ7F.js → chunk-6LRSRXQI.js} +1 -1
  4. package/dist/{chunk-TIP2XS2L.js → chunk-7JFTEJ7B.js} +1 -1
  5. package/dist/chunk-BKNZQZZD.js +857 -0
  6. package/dist/chunk-CK7N635F.js +317 -0
  7. package/dist/{chunk-KHJRD4DR.js → chunk-HFWHVU72.js} +4 -3
  8. package/dist/{chunk-RVDXKUWH.js → chunk-HGL7TLNA.js} +20 -353
  9. package/dist/{chunk-X4DBI7R7.js → chunk-HNUY5PBQ.js} +62 -8
  10. package/dist/{chunk-OJ5ERABF.js → chunk-IO2N34S2.js} +1 -1
  11. package/dist/{chunk-LVHQILKX.js → chunk-JMGVHVOS.js} +27 -23
  12. package/dist/{chunk-H7KHMRUZ.js → chunk-QTE5OMZY.js} +7 -5
  13. package/dist/{chunk-NDVCYVW5.js → chunk-RVI7ZWR2.js} +5 -5
  14. package/dist/chunk-TGU7T4O7.js +1363 -0
  15. package/dist/{chunk-46I7RCQQ.js → chunk-UYBKORXA.js} +43 -24
  16. package/dist/chunk-YO2XUCCF.js +30 -0
  17. package/dist/{chunk-GDZSCISF.js → chunk-ZOXE2XNH.js} +4 -2
  18. package/dist/{compute-TCUMLDEK.js → compute-4MMGFJGE.js} +2 -2
  19. package/dist/compute-report-LIMMRQY3.js +43 -0
  20. package/dist/grok-bot-export-7LSTXWJW.js +57 -0
  21. package/dist/index.js +634 -1791
  22. package/dist/local-agents-O7PYSQGR.js +11 -0
  23. package/dist/{local-skills-EIUQL24E.js → local-skills-5LJST7EP.js} +9 -3
  24. package/dist/{local-skills-run-FSVTDDOW.js → local-skills-run-6SZJQSVF.js} +16 -10
  25. package/dist/mcp-register-XY4MR3ZZ.js +40 -0
  26. package/dist/mcp-serve-QROKKUJV.js +18 -0
  27. package/dist/{trace-GFC46TQC.js → trace-SJZ25T35.js} +4 -3
  28. package/dist/{trace-exclusions-JEGMUPWQ.js → trace-exclusions-IC6OA2ND.js} +3 -2
  29. package/dist/trace-handoff-CD5LOS7B.js +116 -0
  30. package/dist/{trace-library-4F57EGL7.js → trace-library-V23TEXG4.js} +14 -8
  31. package/dist/trace-privacy-DU3TL5EO.js +11 -0
  32. package/package.json +1 -1
  33. package/vendor/trace-collect/SOURCE.json +2 -1
  34. package/vendor/trace-collect/sources/_pii.mjs +56 -0
  35. package/vendor/trace-collect/sources/grok-bot.mjs +180 -0
  36. package/vendor/trace-collect/sources/index.mjs +4 -2
  37. package/vendor/trace-collect/sources/muse-agent.mjs +95 -0
  38. package/dist/compute-report-LC2OH2QJ.js +0 -39
  39. package/dist/mcp-serve-NQJZL7YP.js +0 -16
package/dist/index.js CHANGED
@@ -17,14 +17,32 @@ import {
17
17
  skyCommand,
18
18
  takeBack,
19
19
  waitForAnswer
20
- } from "./chunk-LVHQILKX.js";
20
+ } from "./chunk-JMGVHVOS.js";
21
+ import {
22
+ SINGLE_REQUEST_MAX_BYTES,
23
+ codexThreadName,
24
+ importPathAllowed,
25
+ importReadAllowed,
26
+ loadedSkills,
27
+ repositoryRoot,
28
+ sharedInstructionPaths,
29
+ skillFiles,
30
+ transfer,
31
+ uploadLargeFile,
32
+ workspaceState
33
+ } from "./chunk-UYBKORXA.js";
34
+ import "./chunk-IO2N34S2.js";
21
35
  import {
22
36
  SetupJournal,
23
37
  TOKEN_ENV,
24
38
  shellEnvFiles,
25
39
  shellStartupFiles,
26
40
  writeShellEnv
27
- } from "./chunk-GDZSCISF.js";
41
+ } from "./chunk-ZOXE2XNH.js";
42
+ import {
43
+ convertSession,
44
+ isEngine
45
+ } from "./chunk-TGU7T4O7.js";
28
46
  import {
29
47
  SHELL_AGENT,
30
48
  agentKeysPath,
@@ -33,56 +51,31 @@ import {
33
51
  runsUnattended,
34
52
  shortToolCount,
35
53
  wantsInteractiveClientKey
36
- } from "./chunk-H7KHMRUZ.js";
54
+ } from "./chunk-QTE5OMZY.js";
37
55
  import {
38
- NO_TOOLS,
39
56
  addPolicy,
40
57
  deleteWorkspace,
41
58
  deletionPreview,
42
- detectClaudeApp,
43
- detectHermes,
44
- detectLocalAgents,
45
- detectMcpClients,
46
- hasMcpServer,
47
59
  invite,
48
60
  joinWorkspace,
49
61
  leaveWorkspace,
50
62
  listMembers,
51
63
  listPolicies,
52
- mcpConfigPath,
53
- mcpUrlFor,
54
64
  readWorkspaceSettings,
55
- refreshMcpRegistrations,
56
- registerMcpServer,
57
65
  removeMember,
58
66
  removePolicy,
59
67
  renderDeletionPreview,
60
68
  renderMembers,
61
69
  renderPolicy,
62
70
  renderSettingsBlock,
63
- selectLocalAgents,
64
71
  setPolicyEnabled,
65
72
  setRole,
66
- systemCommandRunner,
67
73
  typedConfirmation,
68
74
  withdrawInvite,
69
75
  withoutSettingsBlock,
70
76
  workspaceSlug,
71
77
  writeSettingsBlocks
72
- } from "./chunk-RVDXKUWH.js";
73
- import {
74
- SINGLE_REQUEST_MAX_BYTES,
75
- codexThreadName,
76
- importPathAllowed,
77
- importReadAllowed,
78
- loadedSkills,
79
- repositoryRoot,
80
- sharedInstructionPaths,
81
- skillFiles,
82
- transfer,
83
- uploadLargeFile,
84
- workspaceState
85
- } from "./chunk-46I7RCQQ.js";
78
+ } from "./chunk-HGL7TLNA.js";
86
79
  import {
87
80
  ApiError,
88
81
  api,
@@ -96,32 +89,25 @@ import {
96
89
  streamEvents,
97
90
  uploadFile,
98
91
  writeResponseFile
99
- } from "./chunk-KHJRD4DR.js";
100
- import "./chunk-NDVCYVW5.js";
101
- import {
102
- skillTargets,
103
- syncLocalSkills
104
- } from "./chunk-X4DBI7R7.js";
105
- import {
106
- SKILL_NAME,
107
- installSkill,
108
- isInstalledSkill,
109
- skillPaths
110
- } from "./chunk-TIP2XS2L.js";
92
+ } from "./chunk-HFWHVU72.js";
111
93
  import {
112
- CLI_VERSION,
113
- USER_AGENT
114
- } from "./chunk-E7HNEQ7F.js";
94
+ NO_TOOLS,
95
+ detectClaudeApp,
96
+ detectHermes,
97
+ detectMcpClients,
98
+ hasMcpServer,
99
+ mcpConfigPath,
100
+ mcpUrlFor,
101
+ refreshMcpRegistrations,
102
+ registerMcpServer,
103
+ systemCommandRunner
104
+ } from "./chunk-CK7N635F.js";
115
105
  import {
116
- apiBase,
117
- apiToken,
118
- configPath,
119
- consoleBase,
120
- currentUniverse,
121
- loadConfig,
122
- saveConfig
123
- } from "./chunk-XHZJG3QT.js";
124
- import "./chunk-OJ5ERABF.js";
106
+ detectLocalAgents,
107
+ selectLocalAgents
108
+ } from "./chunk-2H4W5ZKZ.js";
109
+ import "./chunk-YO2XUCCF.js";
110
+ import "./chunk-RVI7ZWR2.js";
125
111
  import {
126
112
  AGENT_TYPES,
127
113
  MODEL_SUBSCRIPTION_PLAN_PHRASE,
@@ -140,14 +126,38 @@ import {
140
126
  modelSubscriptionProviderFor,
141
127
  preinstalledManifest,
142
128
  reasoningEffortDocLine,
143
- redactLine,
144
- redactPlainText,
145
- redactSecretValues,
146
129
  splitMcpServers,
147
130
  storeSkillRefSchema,
148
- supersededBy,
149
- unsafeNumberSpans
150
- } from "./chunk-W24YSGH4.js";
131
+ supersededBy
132
+ } from "./chunk-2YUZZ5VG.js";
133
+ import {
134
+ redactLine,
135
+ redactPlainText,
136
+ redactSecretValues
137
+ } from "./chunk-BKNZQZZD.js";
138
+ import {
139
+ skillTargets,
140
+ syncLocalSkills
141
+ } from "./chunk-HNUY5PBQ.js";
142
+ import {
143
+ SKILL_NAME,
144
+ installSkill,
145
+ isInstalledSkill,
146
+ skillPaths
147
+ } from "./chunk-7JFTEJ7B.js";
148
+ import {
149
+ apiBase,
150
+ apiToken,
151
+ configPath,
152
+ consoleBase,
153
+ currentUniverse,
154
+ loadConfig,
155
+ saveConfig
156
+ } from "./chunk-XHZJG3QT.js";
157
+ import {
158
+ CLI_VERSION,
159
+ USER_AGENT
160
+ } from "./chunk-6LRSRXQI.js";
151
161
  import "./chunk-MLKGABMK.js";
152
162
 
153
163
  // src/session-show.ts
@@ -412,7 +422,10 @@ var administrationArgumentSchemas = {
412
422
  device_save_arena_chart: chartSource,
413
423
  device_configure_local_sync: syncArguments,
414
424
  device_relaunch: empty,
415
- device_restart_to_update: empty
425
+ device_restart_to_update: empty,
426
+ device_permission_state: empty,
427
+ device_request_permission: external_exports.object({ permission: external_exports.enum(["screen_recording", "accessibility", "keychain"]), waitSeconds: external_exports.number().int().min(0).max(50).optional() }).strict(),
428
+ device_set_chat_permission_mode: external_exports.object({ chatId: external_exports.string().min(1).max(200), mode: external_exports.enum(["bypass", "auto", "manual"]) }).strict()
416
429
  };
417
430
  var administrationOperations = [
418
431
  "legacy_drafts_list",
@@ -434,7 +447,10 @@ var administrationOperations = [
434
447
  "device_save_arena_chart",
435
448
  "device_configure_local_sync",
436
449
  "device_relaunch",
437
- "device_restart_to_update"
450
+ "device_restart_to_update",
451
+ "device_permission_state",
452
+ "device_request_permission",
453
+ "device_set_chat_permission_mode"
438
454
  ];
439
455
  var administrationOperationSchema = external_exports.enum(administrationOperations);
440
456
  var administrationRequestIdSchema = external_exports.string().regex(/^[A-Za-z0-9_-]{16,200}$/);
@@ -444,6 +460,7 @@ function parseAdministrationCall(operation, input) {
444
460
  }
445
461
 
446
462
  // src/mac-administration.ts
463
+ import { randomUUID as randomUUID2 } from "crypto";
447
464
  function registerMacAdministrationCommands(mac2) {
448
465
  mac2.command("administration <machine> <operation>").description("invoke an exact native owner operation; requires your unrestricted account-wide admin key").option("--arguments <json>", "operation arguments matching its published schema", "{}").requiredOption("--request-id <id>", "stable operation identity; reuse on retry").option("--workspace <slug>", "checked operation context; does not grant account-owner authority").option("--personal-workspace", "explicitly select your default workspace").addHelpText("after", `
449
466
  Exact operations:
@@ -463,6 +480,16 @@ Sign-out, relaunch and restart-to-update return pending admission, not completed
463
480
  const result = await api("POST", `/desktop/machines/${encodeURIComponent(machine)}/administration/${encodeURIComponent(operation)}${query}`, input);
464
481
  console.log(JSON.stringify(result, null, 2));
465
482
  });
483
+ const administer = async (machine, operation, args) => {
484
+ const input = parseAdministrationCall(operation, { arguments: args, request_id: `sky_${randomUUID2().replace(/-/g, "")}` });
485
+ return api("POST", `/desktop/machines/${encodeURIComponent(machine)}/administration/${operation}`, input);
486
+ };
487
+ mac2.command("permissions <machine>").description("read whether the Mac app has Screen Recording and Accessibility, and whether it waits on Keychain access").action(async (machine) => console.log(JSON.stringify(await administer(machine, "device_permission_state", {}), null, 2)));
488
+ mac2.command("request-permission <machine> <permission>").description("make the Mac app ask macOS for screen_recording, accessibility or keychain; the person answers the dialog on the Mac").option("--wait <seconds>", "how long to wait for their answer (0-50)", "30").action(async (machine, permission, options) => {
489
+ const result = await administer(machine, "device_request_permission", { permission, waitSeconds: Number.parseInt(options.wait, 10) });
490
+ console.log(JSON.stringify(result, null, 2));
491
+ });
492
+ mac2.command("chat-mode <machine> <chat> <mode>").description("set one of your local chats on the Mac to bypass, auto or manual; a looser mode waits for the person to allow it on the Mac").action(async (machine, chatId, mode) => console.log(JSON.stringify(await administer(machine, "device_set_chat_permission_mode", { chatId, mode }), null, 2)));
466
493
  }
467
494
 
468
495
  // src/mac-sign-in.ts
@@ -493,10 +520,10 @@ async function localMacAuthRequest(socketPath, path2, body) {
493
520
  return new Promise((done, reject) => {
494
521
  const req = request2({ socketPath, path: path2, method: body === void 0 ? "GET" : "POST", headers: body === void 0 ? {} : { "content-type": "application/json", "content-length": Buffer.byteLength(body) } }, (res) => {
495
522
  const chunks = [];
496
- let size2 = 0;
523
+ let size = 0;
497
524
  res.on("data", (chunk) => {
498
- size2 += chunk.length;
499
- if (size2 > LIMIT) {
525
+ size += chunk.length;
526
+ if (size > LIMIT) {
500
527
  req.destroy();
501
528
  reject(new Error("Local authentication response too large"));
502
529
  } else chunks.push(chunk);
@@ -519,11 +546,11 @@ async function localMacAuthRequest(socketPath, path2, body) {
519
546
  async function readMacSignInKey(input, isTTY = false) {
520
547
  if (isTTY) throw new Error("Pipe a key from your credential loader; interactive key input is not accepted");
521
548
  const chunks = [];
522
- let size2 = 0;
549
+ let size = 0;
523
550
  for await (const chunk of input) {
524
551
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
525
- size2 += buffer.length;
526
- if (size2 > 4098) throw new Error("Key input too large");
552
+ size += buffer.length;
553
+ if (size > 4098) throw new Error("Key input too large");
527
554
  chunks.push(buffer);
528
555
  }
529
556
  const key = Buffer.concat(chunks).toString("utf8").trim();
@@ -617,7 +644,7 @@ function registerMacAutomationCommands(mac2) {
617
644
  }
618
645
 
619
646
  // src/mac-control.ts
620
- import { randomUUID as randomUUID2 } from "crypto";
647
+ import { randomUUID as randomUUID3 } from "crypto";
621
648
  var controllers = (machine) => `/desktop/machines/${encodeURIComponent(machine)}/controllers`;
622
649
  function registerMacControlCommands(mac2) {
623
650
  const print = (value) => console.log(JSON.stringify(value, null, 2));
@@ -635,15 +662,15 @@ function registerMacControlCommands(mac2) {
635
662
  print({ removed: controller });
636
663
  });
637
664
  mac2.command("stop <session>").description("stop a chat running on your Mac (this key must be paired with it)").option("--request-id <id>", "stable retry identity; a retry stops once").action(async (session2, options) => {
638
- print(await api("POST", `/desktop/sessions/${encodeURIComponent(session2)}/stop`, { request_id: options.requestId ?? randomUUID2(), surface: "api" }));
665
+ print(await api("POST", `/desktop/sessions/${encodeURIComponent(session2)}/stop`, { request_id: options.requestId ?? randomUUID3(), surface: "api" }));
639
666
  });
640
667
  mac2.command("start <text>").description("start a new chat on your newest online Mac with your own Claude Code or Codex (this key must be paired with it); the Mac picks the folder from the request").option("--agent <agent>", "claude_code or codex", "claude_code").option("--repository <owner/name>", "the GitHub repository the task is about, to find its folder").option("--request-id <id>", "stable retry identity; a retry starts it once").action(async (text2, options) => {
641
668
  if (options.agent !== "claude_code" && options.agent !== "codex") throw new Error("agent must be claude_code or codex");
642
- print(await api("POST", "/desktop/chats", { text: text2, request_id: options.requestId ?? randomUUID2(), agent: options.agent, ...options.repository ? { repository: options.repository } : {}, surface: "api" }));
669
+ print(await api("POST", "/desktop/chats", { text: text2, request_id: options.requestId ?? randomUUID3(), agent: options.agent, ...options.repository ? { repository: options.repository } : {}, surface: "api" }));
643
670
  });
644
671
  mac2.command("answer <session> <prompt> <decision>").description("allow or deny a command a chat on your Mac waits on; keychain commands are answered on the Mac only").option("--request-id <id>", "stable retry identity; a retry answers once").action(async (session2, prompt, decision, options) => {
645
672
  if (decision !== "allow" && decision !== "deny") throw new Error("decision must be allow or deny");
646
- print(await api("POST", `/desktop/sessions/${encodeURIComponent(session2)}/prompts/${encodeURIComponent(prompt)}/answer`, { request_id: options.requestId ?? randomUUID2(), decision, surface: "api" }));
673
+ print(await api("POST", `/desktop/sessions/${encodeURIComponent(session2)}/prompts/${encodeURIComponent(prompt)}/answer`, { request_id: options.requestId ?? randomUUID3(), decision, surface: "api" }));
647
674
  });
648
675
  }
649
676
 
@@ -764,13 +791,13 @@ var cost = (money) => money ? `, $${money.amount}` : "";
764
791
  function renderSearch(search) {
765
792
  if (search.status === "running") return `${search.id} running
766
793
  still running: run the same search again with --request-id ${search.request_id}`;
767
- const lines2 = [`${search.endpoint}${cost(search.cost)}${search.filtered ? `, ${search.filtered} non-public results dropped` : ""}`];
768
- if (search.answer) lines2.push(search.answer, "");
769
- for (const result of search.results) lines2.push(`${result.rank}. ${result.title ?? result.url}
794
+ const lines = [`${search.endpoint}${cost(search.cost)}${search.filtered ? `, ${search.filtered} non-public results dropped` : ""}`];
795
+ if (search.answer) lines.push(search.answer, "");
796
+ for (const result of search.results) lines.push(`${result.rank}. ${result.title ?? result.url}
770
797
  ${result.url}${result.snippet ? `
771
798
  ${result.snippet}` : ""}`);
772
- if (search.truncated) lines2.push("(more results: raise --limit)");
773
- return lines2.join("\n");
799
+ if (search.truncated) lines.push("(more results: raise --limit)");
800
+ return lines.join("\n");
774
801
  }
775
802
  function renderJob(job) {
776
803
  const head = `${job.id} ${job.status}${cost(job.cost)}`;
@@ -834,7 +861,7 @@ async function deploy(name, dir, opts = {}) {
834
861
 
835
862
  // src/site-domains.ts
836
863
  function domainLines(domain) {
837
- return [`${domain.hostname} ${domain.status}`, ...domain.records.map((record3) => ` ${record3.type.padEnd(5)} ${record3.name} ${record3.value}`)];
864
+ return [`${domain.hostname} ${domain.status}`, ...domain.records.map((record) => ` ${record.type.padEnd(5)} ${record.name} ${record.value}`)];
838
865
  }
839
866
  async function addDomain(name, hostname3) {
840
867
  return api("POST", `/sites/${encodeURIComponent(name)}/domains`, { hostname: hostname3 });
@@ -874,7 +901,7 @@ function registerEmailCommands(emailCommand2) {
874
901
  // src/plugins.ts
875
902
  import { chmodSync, lstatSync as lstatSync3, mkdirSync, writeFileSync as writeFileSync2 } from "fs";
876
903
  import { basename as basename2, dirname as dirname2, isAbsolute, resolve as resolve3, sep as sep2 } from "path";
877
- import { randomUUID as randomUUID3 } from "crypto";
904
+ import { randomUUID as randomUUID4 } from "crypto";
878
905
 
879
906
  // src/skills-store.ts
880
907
  import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync } from "fs";
@@ -1253,10 +1280,10 @@ async function answerPlugin(id2, where) {
1253
1280
  return api("PUT", `/plugins/${encodeURIComponent(id2)}/answer`, { ...target(where), ...where.connection ? { connection_id: where.connection } : {} });
1254
1281
  }
1255
1282
  function renderAdd(answer) {
1256
- const lines2 = [answer.status === "added" ? `Added ${answer.plugin_id}.` : `${answer.plugin_id} needs you to finish:`];
1257
- if (answer.next?.url) lines2.push(` open ${answer.next.url}`);
1258
- for (const step of answer.next?.steps ?? []) lines2.push(` ${step}`);
1259
- return lines2.join("\n");
1283
+ const lines = [answer.status === "added" ? `Added ${answer.plugin_id}.` : `${answer.plugin_id} needs you to finish:`];
1284
+ if (answer.next?.url) lines.push(` open ${answer.next.url}`);
1285
+ for (const step of answer.next?.steps ?? []) lines.push(` ${step}`);
1286
+ return lines.join("\n");
1260
1287
  }
1261
1288
  async function requestPlugin(id2, session2) {
1262
1289
  return api("POST", `/plugins/${encodeURIComponent(id2)}/request`, { session_id: session2 });
@@ -1287,16 +1314,16 @@ function renderPropose(answer) {
1287
1314
  return `Proposed ${answer.draft_id} ${answer.revision}. The person answers on its card; end your turn, then propose again to finish.`;
1288
1315
  }
1289
1316
  function renderTest(answer) {
1290
- const lines2 = [`${answer.id} ${answer.revision}: ${answer.status}`];
1291
- for (const result of answer.results) lines2.push(` ${result.passed ? "pass" : result.skipped ? "skip" : "fail"} ${result.sample}${result.reason ? `: ${result.reason}` : ""}${result.skipped ? `: ${result.skipped}` : ""}`);
1292
- return lines2.join("\n");
1317
+ const lines = [`${answer.id} ${answer.revision}: ${answer.status}`];
1318
+ for (const result of answer.results) lines.push(` ${result.passed ? "pass" : result.skipped ? "skip" : "fail"} ${result.sample}${result.reason ? `: ${result.reason}` : ""}${result.skipped ? `: ${result.skipped}` : ""}`);
1319
+ return lines.join("\n");
1293
1320
  }
1294
1321
  function renderDraft(answer) {
1295
- const lines2 = [`${answer.id} ${answer.name ?? answer.path} ${answer.revision}${answer.created ? " (new revision)" : ""}`];
1296
- for (const [tool2, effect] of Object.entries(answer.effects)) lines2.push(` tool ${tool2}: ${effect}`);
1297
- if (answer.problems.length === 0) lines2.push("No problems.");
1298
- for (const problem of answer.problems) lines2.push(` ${problem.path}: ${problem.message}`);
1299
- return lines2.join("\n");
1322
+ const lines = [`${answer.id} ${answer.name ?? answer.path} ${answer.revision}${answer.created ? " (new revision)" : ""}`];
1323
+ for (const [tool2, effect] of Object.entries(answer.effects)) lines.push(` tool ${tool2}: ${effect}`);
1324
+ if (answer.problems.length === 0) lines.push("No problems.");
1325
+ for (const problem of answer.problems) lines.push(` ${problem.path}: ${problem.message}`);
1326
+ return lines.join("\n");
1300
1327
  }
1301
1328
  function renderOff(answer) {
1302
1329
  const where = answer.agent_id ? `agent ${answer.agent_id}` : `chat ${answer.session_id}`;
@@ -1307,26 +1334,26 @@ function statusWord(plugin) {
1307
1334
  return plugin.status === "added" ? "" : ` ${PLUGIN_STATUS_LABEL[plugin.status].toLowerCase()}`;
1308
1335
  }
1309
1336
  function renderPluginList(list) {
1310
- const lines2 = list.data.map((plugin) => `${plugin.id} ${plugin.name} ${priceLine(plugin)}${statusWord(plugin)}`);
1311
- for (const gap of list.unavailable) lines2.push(`(${gap.message})`);
1312
- if (list.next_cursor) lines2.push(`more: --cursor ${list.next_cursor}`);
1313
- return lines2.length ? lines2.join("\n") : "nothing here yet: sky plugins list --view discover";
1337
+ const lines = list.data.map((plugin) => `${plugin.id} ${plugin.name} ${priceLine(plugin)}${statusWord(plugin)}`);
1338
+ for (const gap of list.unavailable) lines.push(`(${gap.message})`);
1339
+ if (list.next_cursor) lines.push(`more: --cursor ${list.next_cursor}`);
1340
+ return lines.length ? lines.join("\n") : "nothing here yet: sky plugins list --view discover";
1314
1341
  }
1315
1342
  function renderPlugin(plugin) {
1316
- const lines2 = [
1343
+ const lines = [
1317
1344
  `${plugin.name} (${plugin.id})`,
1318
1345
  ` ${[priceLine(plugin), PLUGIN_STATUS_LABEL[plugin.status], plugin.scope === "me" ? "yours" : "workspace"].filter(Boolean).join(" \xB7 ")}`
1319
1346
  ];
1320
- if (plugin.description) lines2.push(` ${plugin.description}`);
1321
- if (plugin.mcp && plugin.mcp.url !== plugin.description) lines2.push(` ${plugin.mcp.url}`);
1322
- if (plugin.mcp) lines2.push(` ${plugin.mcp.has_token ? "token saved" : "no token"}`);
1323
- for (const gift of plugin.gives) lines2.push(` gives ${gift.type}: ${gift.name}`);
1324
- for (const part of plugin.parts ?? []) lines2.push(` part ${PLUGIN_PART_LABEL[part.type].toLowerCase()}: ${part.name}${part.category ? ` (any ${part.category} app)` : ""}${part.status === "added" ? "" : ` ${part.status.replace("_", " ")}`}`);
1325
- for (const need of plugin.requires) lines2.push(` needs ${need.plugin_id}: ${need.reason}`);
1326
- if (plugin.next?.url) lines2.push(` finish at ${plugin.next.url}`);
1327
- for (const step of plugin.next?.steps ?? []) lines2.push(` next: ${step}`);
1328
- for (const gap of plugin.unavailable) lines2.push(` (${gap.message})`);
1329
- return lines2.join("\n");
1347
+ if (plugin.description) lines.push(` ${plugin.description}`);
1348
+ if (plugin.mcp && plugin.mcp.url !== plugin.description) lines.push(` ${plugin.mcp.url}`);
1349
+ if (plugin.mcp) lines.push(` ${plugin.mcp.has_token ? "token saved" : "no token"}`);
1350
+ for (const gift of plugin.gives) lines.push(` gives ${gift.type}: ${gift.name}`);
1351
+ for (const part of plugin.parts ?? []) lines.push(` part ${PLUGIN_PART_LABEL[part.type].toLowerCase()}: ${part.name}${part.category ? ` (any ${part.category} app)` : ""}${part.status === "added" ? "" : ` ${part.status.replace("_", " ")}`}`);
1352
+ for (const need of plugin.requires) lines.push(` needs ${need.plugin_id}: ${need.reason}`);
1353
+ if (plugin.next?.url) lines.push(` finish at ${plugin.next.url}`);
1354
+ for (const step of plugin.next?.steps ?? []) lines.push(` next: ${step}`);
1355
+ for (const gap of plugin.unavailable) lines.push(` (${gap.message})`);
1356
+ return lines.join("\n");
1330
1357
  }
1331
1358
  async function pluginShares(id2, connection) {
1332
1359
  const query = connection ? `?${new URLSearchParams({ connection_id: connection })}` : "";
@@ -1365,7 +1392,7 @@ async function callDeclaredPluginAction(id2, options) {
1365
1392
  action_id: action.id,
1366
1393
  session_id: options.session,
1367
1394
  input: { ...action.input, ...options.input }
1368
- }, { idempotencyKey: options.requestId ?? randomUUID3() });
1395
+ }, { idempotencyKey: options.requestId ?? randomUUID4() });
1369
1396
  }
1370
1397
  async function connectionsThroughPlugins() {
1371
1398
  const page = await listPluginResources({ view: "yours", source: "app", include: ["connections"] });
@@ -1404,10 +1431,10 @@ function writeExportFiles(dir, files2) {
1404
1431
  }
1405
1432
  return targets.map(({ file }) => file.path);
1406
1433
  }
1407
- async function runImport(plan2, env = process.env) {
1408
- if (plan2.core) return [{ part: plan2.core, result: "already_in_workspace", plugin_id: plan2.core, detail: "AgentSky core plugins are in every workspace; switch it on in Plugins." }];
1434
+ async function runImport(plan, env = process.env) {
1435
+ if (plan.core) return [{ part: plan.core, result: "already_in_workspace", plugin_id: plan.core, detail: "AgentSky core plugins are in every workspace; switch it on in Plugins." }];
1409
1436
  const results = [];
1410
- for (const skill of plan2.skills) {
1437
+ for (const skill of plan.skills) {
1411
1438
  try {
1412
1439
  const uploaded = await uploadSkillPlugin(skill.dir, skill.name);
1413
1440
  results.push({ part: `skills/${skill.name}`, result: "added", plugin_id: `skill:${uploaded.skill.id}` });
@@ -1415,7 +1442,7 @@ async function runImport(plan2, env = process.env) {
1415
1442
  results.push({ part: `skills/${skill.name}`, result: "failed", detail: error instanceof Error ? error.message : String(error) });
1416
1443
  }
1417
1444
  }
1418
- for (const server of plan2.servers) {
1445
+ for (const server of plan.servers) {
1419
1446
  const token = server.tokenEnv ? env[server.tokenEnv] : void 0;
1420
1447
  try {
1421
1448
  const added = await addPlugin(void 0, { mcpUrl: server.url, name: server.name, ...token ? { token } : {} });
@@ -1517,18 +1544,18 @@ function recordedTools(records, cwd) {
1517
1544
  const out = [];
1518
1545
  let context2 = cwd;
1519
1546
  records.forEach((raw, index) => {
1520
- const record3 = obj(raw);
1521
- if (!record3) return;
1522
- const payload = obj(record3.payload);
1523
- if (record3.type === "turn_context" || record3.type === "session_meta") context2 = str(payload?.cwd) || context2;
1524
- const base = str(record3.cwd) || context2;
1547
+ const record = obj(raw);
1548
+ if (!record) return;
1549
+ const payload = obj(record.payload);
1550
+ if (record.type === "turn_context" || record.type === "session_meta") context2 = str(payload?.cwd) || context2;
1551
+ const base = str(record.cwd) || context2;
1525
1552
  const add = (name, input) => out.push({ name, input, cwd: str(obj(input)?.workdir) || str(obj(input)?.cwd) || base, record: index });
1526
- const content = obj(record3.message)?.content;
1527
- if (record3.type === "assistant" && Array.isArray(content)) for (const rawBlock of content) {
1553
+ const content = obj(record.message)?.content;
1554
+ if (record.type === "assistant" && Array.isArray(content)) for (const rawBlock of content) {
1528
1555
  const block = obj(rawBlock);
1529
1556
  if (block?.type === "tool_use") add(str(block.name), block.input);
1530
1557
  }
1531
- if (record3.type === "response_item" && (payload?.type === "function_call" || payload?.type === "custom_tool_call")) {
1558
+ if (record.type === "response_item" && (payload?.type === "function_call" || payload?.type === "custom_tool_call")) {
1532
1559
  let input = payload.arguments ?? payload.input ?? "";
1533
1560
  if (typeof input === "string") {
1534
1561
  try {
@@ -1741,11 +1768,11 @@ function collectSessionFiles(records, opts) {
1741
1768
  leftOut.push({ path: path2, reason: "credential or build file" });
1742
1769
  return;
1743
1770
  }
1744
- let size2;
1771
+ let size;
1745
1772
  try {
1746
1773
  const stat = statSync2(path2);
1747
1774
  if (!stat.isFile()) return;
1748
- size2 = stat.size;
1775
+ size = stat.size;
1749
1776
  } catch {
1750
1777
  leftOut.push({ path: path2, reason: "missing" });
1751
1778
  return;
@@ -1755,16 +1782,16 @@ function collectSessionFiles(records, opts) {
1755
1782
  leftOut.push({ path: path2, reason: "unsupported type" });
1756
1783
  return;
1757
1784
  }
1758
- if (size2 > MAX_ATTACHED_FILE_BYTES) {
1785
+ if (size > MAX_ATTACHED_FILE_BYTES) {
1759
1786
  leftOut.push({ path: path2, reason: "too large" });
1760
1787
  return;
1761
1788
  }
1762
- candidates.push({ path: path2, name, ...type, size: size2 });
1789
+ candidates.push({ path: path2, name, ...type, size });
1763
1790
  };
1764
1791
  for (const path2 of [...instructionPaths(opts.cwd, opts.harness, home, opts.pathAllowed), ...workspaces.flatMap((workspace2) => instructionPaths(workspace2.cwd, opts.harness, home, opts.pathAllowed)), ...touched]) consider(path2, resourceName(path2, opts.cwd, home));
1765
1792
  for (const skill of skills2.found) for (const file of skillFiles(skill, opts.pathAllowed)) consider(file.path, file.name);
1766
1793
  candidates.sort((a, b) => ORDER[a.kind] - ORDER[b.kind] || a.size - b.size);
1767
- const lines2 = [];
1794
+ const lines = [];
1768
1795
  const attached = [];
1769
1796
  let bytes = 0;
1770
1797
  const state = workspaceState(opts.cwd, opts.harness, skills2, home, opts.title ?? null, opts.pathAllowed);
@@ -1789,13 +1816,13 @@ function collectSessionFiles(records, opts) {
1789
1816
  leftOut.push({ path: file.name, reason: "could not be redacted safely" });
1790
1817
  continue;
1791
1818
  }
1792
- const size2 = Buffer.byteLength(line2);
1793
- if (bytes + size2 > opts.budget) {
1819
+ const size = Buffer.byteLength(line2);
1820
+ if (bytes + size > opts.budget) {
1794
1821
  leftOut.push({ path: file.name, reason: "over the upload budget" });
1795
1822
  continue;
1796
1823
  }
1797
- bytes += size2;
1798
- lines2.push(line2);
1824
+ bytes += size;
1825
+ lines.push(line2);
1799
1826
  attached.push({ name: file.name, kind: "text", bytes: file.data.length });
1800
1827
  }
1801
1828
  for (const file of candidates) {
@@ -1818,13 +1845,13 @@ function collectSessionFiles(records, opts) {
1818
1845
  leftOut.push({ path: file.path, reason: file.kind === "text" && !isUtf8(data) ? "not valid UTF-8 text" : "could not be redacted safely" });
1819
1846
  continue;
1820
1847
  }
1821
- const size2 = Buffer.byteLength(line2);
1822
- if (bytes + size2 > opts.budget) {
1848
+ const size = Buffer.byteLength(line2);
1849
+ if (bytes + size > opts.budget) {
1823
1850
  leftOut.push({ path: file.path, reason: "over the upload budget" });
1824
1851
  continue;
1825
1852
  }
1826
- bytes += size2;
1827
- lines2.push(line2);
1853
+ bytes += size;
1854
+ lines.push(line2);
1828
1855
  attached.push({ name: file.name, kind: file.kind, bytes: data.length });
1829
1856
  }
1830
1857
  const setup = {
@@ -1833,7 +1860,7 @@ function collectSessionFiles(records, opts) {
1833
1860
  mcpServers: state.manifest.mcp_servers.map((server) => server.name),
1834
1861
  git: state.manifest.git !== null
1835
1862
  };
1836
- return { lines: lines2, bytes, attached, leftOut, setup };
1863
+ return { lines, bytes, attached, leftOut, setup };
1837
1864
  }
1838
1865
 
1839
1866
  // src/import-environment.ts
@@ -1970,13 +1997,13 @@ function importLayout(files2, sourceCwd, platform, wholeFolder) {
1970
1997
  }
1971
1998
  var TAR_BLOCK = 512;
1972
1999
  var TAR_END = Buffer.alloc(TAR_BLOCK * 2);
1973
- function header(name, size2, type) {
2000
+ function header(name, size, type) {
1974
2001
  const block = Buffer.alloc(TAR_BLOCK);
1975
2002
  block.write(name, 0, 100, "utf8");
1976
2003
  block.write("0000644\0", 100);
1977
2004
  block.write("0000000\0", 108);
1978
2005
  block.write("0000000\0", 116);
1979
- block.write(size2.toString(8).padStart(11, "0") + "\0", 124);
2006
+ block.write(size.toString(8).padStart(11, "0") + "\0", 124);
1980
2007
  block.write("00000000000\0", 136);
1981
2008
  block.write(" ", 148);
1982
2009
  block.write(type, 156);
@@ -1996,14 +2023,14 @@ function paxRecord(key, value) {
1996
2023
  length += 1;
1997
2024
  }
1998
2025
  }
1999
- function tarPadding(size2) {
2000
- const rest = size2 % TAR_BLOCK;
2026
+ function tarPadding(size) {
2027
+ const rest = size % TAR_BLOCK;
2001
2028
  return Buffer.alloc(rest ? TAR_BLOCK - rest : 0);
2002
2029
  }
2003
- function tarHeader(path2, size2) {
2004
- if (Buffer.byteLength(path2) <= 100) return header(path2, size2, "0");
2030
+ function tarHeader(path2, size) {
2031
+ if (Buffer.byteLength(path2) <= 100) return header(path2, size, "0");
2005
2032
  const pax = paxRecord("path", path2);
2006
- return Buffer.concat([header("PaxHeader", pax.length, "x"), pax, tarPadding(pax.length), header(path2, size2, "0")]);
2033
+ return Buffer.concat([header("PaxHeader", pax.length, "x"), pax, tarPadding(pax.length), header(path2, size, "0")]);
2007
2034
  }
2008
2035
 
2009
2036
  // src/import-environment.ts
@@ -2035,8 +2062,8 @@ function listFiles(cwd) {
2035
2062
  walk(cwd, "");
2036
2063
  return out;
2037
2064
  }
2038
- function textOf(path2, size2) {
2039
- if (size2 > MAX_REDACTED_TEXT_BYTES) return null;
2065
+ function textOf(path2, size) {
2066
+ if (size > MAX_REDACTED_TEXT_BYTES) return null;
2040
2067
  const data = readFileSync7(path2);
2041
2068
  if (data.subarray(0, 8e3).includes(0) || !isUtf82(data)) return null;
2042
2069
  return data;
@@ -2143,12 +2170,12 @@ async function packEnvironment(cwd, resources, platform = IMPORT_PLATFORM) {
2143
2170
  throw error;
2144
2171
  }
2145
2172
  }
2146
- function resourcesOf(lines2) {
2147
- return lines2.flatMap((line2) => {
2173
+ function resourcesOf(lines) {
2174
+ return lines.flatMap((line2) => {
2148
2175
  try {
2149
- const record3 = JSON.parse(line2);
2150
- if (record3.type !== "import.resource" || typeof record3.name !== "string" || typeof record3.media_type !== "string" || typeof record3.data !== "string") return [];
2151
- return [{ name: record3.name, mediaType: record3.media_type, data: Buffer.from(record3.data, "base64") }];
2176
+ const record = JSON.parse(line2);
2177
+ if (record.type !== "import.resource" || typeof record.name !== "string" || typeof record.media_type !== "string" || typeof record.data !== "string") return [];
2178
+ return [{ name: record.name, mediaType: record.media_type, data: Buffer.from(record.data, "base64") }];
2152
2179
  } catch {
2153
2180
  return [];
2154
2181
  }
@@ -2409,7 +2436,7 @@ function prepareImport(session2, summaryPath, options = {}) {
2409
2436
  const maximum = 16 * 1024 * 1024;
2410
2437
  let inputBytes = 0;
2411
2438
  let outputBytes = 0;
2412
- const lines2 = [];
2439
+ const lines = [];
2413
2440
  const digest = createHash3("sha256");
2414
2441
  let nativeId;
2415
2442
  let redactionCount = 0;
@@ -2424,15 +2451,15 @@ function prepareImport(session2, summaryPath, options = {}) {
2424
2451
  const text2 = readFileSync8(path2, "utf8");
2425
2452
  for (const raw of text2.split("\n")) {
2426
2453
  if (!raw.trim()) continue;
2427
- let record3;
2454
+ let record;
2428
2455
  try {
2429
- record3 = JSON.parse(raw);
2456
+ record = JSON.parse(raw);
2430
2457
  } catch {
2431
2458
  unreadableCount++;
2432
2459
  continue;
2433
2460
  }
2434
- if (!record3 || typeof record3 !== "object" || Array.isArray(record3)) throw new Error("Transcript records must be JSON objects.");
2435
- const rec = record3;
2461
+ if (!record || typeof record !== "object" || Array.isArray(record)) throw new Error("Transcript records must be JSON objects.");
2462
+ const rec = record;
2436
2463
  if (String(rec.type).startsWith("import.")) throw new Error("Native transcripts cannot supply import protocol records.");
2437
2464
  if (path2 === session2.files[0]) source.push(rec);
2438
2465
  records.push(rec);
@@ -2453,10 +2480,10 @@ function prepareImport(session2, summaryPath, options = {}) {
2453
2480
  outputBytes += Buffer.byteLength(line2);
2454
2481
  if (outputBytes > maximum) throw new Error("Redacted transcript exceeds the 16 MiB limit.");
2455
2482
  digest.update(line2);
2456
- lines2.push(line2);
2483
+ lines.push(line2);
2457
2484
  }
2458
2485
  }
2459
- if (!lines2.length) throw new Error("The selected transcript is empty.");
2486
+ if (!lines.length) throw new Error("The selected transcript is empty.");
2460
2487
  const sourceId = nativeId ?? session2.sessionId;
2461
2488
  if (!/^[A-Za-z0-9_-]{1,200}$/.test(sourceId) || redactLine2(JSON.stringify(sourceId)) !== JSON.stringify(sourceId)) throw new Error("The source conversation has an invalid identifier.");
2462
2489
  const meta = source.result();
@@ -2494,13 +2521,13 @@ function prepareImport(session2, summaryPath, options = {}) {
2494
2521
  };
2495
2522
  summaryJson = JSON.stringify(summary);
2496
2523
  }
2497
- const body = lines2.join("") + files2.lines.join("") + JSON.stringify({ type: "import.summary", package: JSON.parse(summaryJson) }) + "\n" + JSON.stringify({ type: "import.end", records: lines2.length + files2.lines.length + 1 }) + "\n";
2524
+ const body = lines.join("") + files2.lines.join("") + JSON.stringify({ type: "import.summary", package: JSON.parse(summaryJson) }) + "\n" + JSON.stringify({ type: "import.end", records: lines.length + files2.lines.length + 1 }) + "\n";
2498
2525
  const gaps = [];
2499
2526
  if (encryptedReasoningCount > 0) gaps.push({ kind: "encrypted_reasoning", count: encryptedReasoningCount });
2500
2527
  if (compactionCount > 0) gaps.push({ kind: "compaction", count: compactionCount });
2501
2528
  if (unreadableCount > 0) gaps.push({ kind: "unreadable", count: unreadableCount });
2502
2529
  const cwd = meta.cwd ?? (session2.harness === "claude_code" ? session2.workspace : "");
2503
- return { body, transcriptLines: lines2.length, outputBytes, redactionCount, gaps, attachedFiles: files2.attached, leftOutFiles: files2.leftOut, setup: files2.setup, cwd, resourceLines: files2.lines };
2530
+ return { body, transcriptLines: lines.length, outputBytes, redactionCount, gaps, attachedFiles: files2.attached, leftOutFiles: files2.leftOut, setup: files2.setup, cwd, resourceLines: files2.lines };
2504
2531
  }
2505
2532
  async function importSession(opts) {
2506
2533
  const base = (opts.agentUseUrl ?? agentUseBase()).replace(/\/$/, "");
@@ -2591,25 +2618,25 @@ import { spawn } from "child_process";
2591
2618
  // src/local-access.ts
2592
2619
  var reason = (error) => (error instanceof Error ? error.message : String(error)).split("\n")[0];
2593
2620
  async function syncLocalAccess(signedIn, clients = detectMcpClients(), deps = {}) {
2594
- const lines2 = [];
2621
+ const lines = [];
2595
2622
  if (!signedIn) {
2596
2623
  const shell = writeShellEnv(void 0);
2597
- lines2.push(shell.outcome === "failed" ? ` ${TOKEN_ENV} not updated for new shells: ${shell.detail}` : ` new shells no longer get ${TOKEN_ENV}`);
2624
+ lines.push(shell.outcome === "failed" ? ` ${TOKEN_ENV} not updated for new shells: ${shell.detail}` : ` new shells no longer get ${TOKEN_ENV}`);
2598
2625
  const holding = clients.filter((client) => hasMcpServer(client)).map((client) => client.name);
2599
- if (holding.length) lines2.push(` the agentsky MCP server in ${holding.join(", ")} still holds a key sky made for it: revoke it in Developer \u2192 API keys, or \`sky auth login\` replaces it`);
2600
- return lines2;
2626
+ if (holding.length) lines.push(` the agentsky MCP server in ${holding.join(", ")} still holds a key sky made for it: revoke it in Developer \u2192 API keys, or \`sky auth login\` replaces it`);
2627
+ return lines;
2601
2628
  }
2602
2629
  try {
2603
2630
  const shell = writeShellEnv(await localAgentKey(SHELL_AGENT, deps));
2604
- lines2.push(shell.outcome === "failed" ? ` ${TOKEN_ENV} not updated for new shells: ${shell.detail}` : ` new shells get ${TOKEN_ENV}: a key of their own, not this login's`);
2631
+ lines.push(shell.outcome === "failed" ? ` ${TOKEN_ENV} not updated for new shells: ${shell.detail}` : ` new shells get ${TOKEN_ENV}: a key of their own, not this login's`);
2605
2632
  } catch (error) {
2606
- lines2.push(` ${TOKEN_ENV} not updated for new shells: ${reason(error)}`);
2633
+ lines.push(` ${TOKEN_ENV} not updated for new shells: ${reason(error)}`);
2607
2634
  }
2608
2635
  for (const registered of await refreshMcpRegistrations({ token: (client) => localAgentKey(client.id, deps), apiBase: apiBase() }, clients)) {
2609
2636
  const name = clients.find((client) => client.id === registered.agent)?.name ?? registered.agent;
2610
- lines2.push(registered.outcome === "registered" ? ` agentsky MCP server for ${name} now uses a key of its own` : ` agentsky MCP server for ${name} not updated: ${registered.detail ?? registered.outcome} \u2014 run \`sky setup skill\``);
2637
+ lines.push(registered.outcome === "registered" ? ` agentsky MCP server for ${name} now uses a key of its own` : ` agentsky MCP server for ${name} not updated: ${registered.detail ?? registered.outcome} \u2014 run \`sky setup skill\``);
2611
2638
  }
2612
- return lines2;
2639
+ return lines;
2613
2640
  }
2614
2641
  async function withdrawLocalAgentKeys(revoke) {
2615
2642
  const { revoked, left } = await revokeLocalAgentKeys(revoke).catch(() => ({ revoked: 0, left: -1 }));
@@ -3683,7 +3710,7 @@ function describe(event) {
3683
3710
  case "plan":
3684
3711
  return ` ${event.provider} plan: ${event.outcome === "already" ? "already connected" : event.outcome}${event.detail ? ` (${event.detail})` : ""}`;
3685
3712
  case "found": {
3686
- const lines2 = [
3713
+ const lines = [
3687
3714
  ` ${event.skills.length} skill${event.skills.length === 1 ? "" : "s"}${event.skills.length ? `: ${event.skills.map((skill) => skill.name).join(", ")}` : ""}`,
3688
3715
  ...event.instructions.map((item) => ` instructions from ${item.agent}: ${item.path} (${kb(item.bytes)}${item.imports.length ? `, with ${item.imports.length} imported file${item.imports.length === 1 ? "" : "s"}` : ""})`),
3689
3716
  ...event.instructions.length ? [] : [" no global instructions file"],
@@ -3691,7 +3718,7 @@ function describe(event) {
3691
3718
  ...event.secrets.map((secret) => ` key for ${secret.name} (${secret.url}), from ${secret.agent}`),
3692
3719
  ...event.gcloud ? [` gcloud login${event.gcloud.account ? ` for ${event.gcloud.account}` : ""}`] : []
3693
3720
  ];
3694
- return lines2.join("\n");
3721
+ return lines.join("\n");
3695
3722
  }
3696
3723
  case "imported_skill":
3697
3724
  return ` skill ${event.name}: ${event.outcome}`;
@@ -3710,8 +3737,8 @@ function describe(event) {
3710
3737
  }
3711
3738
  case "settings": {
3712
3739
  if (event.outcome === "unavailable") return ` workspace settings not written into the agents' instruction files${event.detail ? ` (${event.detail})` : ""}; the next scheduled sync tries again`;
3713
- const lines2 = event.files.filter((file) => file.outcome !== "current").map((file) => ` workspace settings ${file.outcome === "planned" ? "would be written" : file.outcome} in ${file.path}${file.detail ? ` (${file.detail})` : ""}`);
3714
- return lines2.length ? lines2.join("\n") : " workspace settings already current in every agent";
3740
+ const lines = event.files.filter((file) => file.outcome !== "current").map((file) => ` workspace settings ${file.outcome === "planned" ? "would be written" : file.outcome} in ${file.path}${file.detail ? ` (${file.detail})` : ""}`);
3741
+ return lines.length ? lines.join("\n") : " workspace settings already current in every agent";
3715
3742
  }
3716
3743
  case "computer":
3717
3744
  return event.outcome === "reported" ? " this computer is listed under Settings \u203A Compute" : ` this computer could not be listed under Settings \u203A Compute: ${event.detail ?? "unknown error"}`;
@@ -3884,8 +3911,8 @@ async function setUp(opts, journal, afterwards = []) {
3884
3911
  await syncConfig(sources2, opts.syncAs, emit);
3885
3912
  return;
3886
3913
  }
3887
- const claudeCode2 = agents.find((agent2) => agent2.id === "claude_code");
3888
- if (claudeCode2 && !opts.dryRun) afterwards.push(keepClaudeCodeSideEffects(claudeCode2, journal));
3914
+ const claudeCode = agents.find((agent2) => agent2.id === "claude_code");
3915
+ if (claudeCode && !opts.dryRun) afterwards.push(keepClaudeCodeSideEffects(claudeCode, journal));
3889
3916
  const run3 = { agents: [], plans: [] };
3890
3917
  let captureNotices = [];
3891
3918
  const earlier = loadReport();
@@ -3908,7 +3935,7 @@ async function setUp(opts, journal, afterwards = []) {
3908
3935
  const workspace2 = engines.length && (has("skill") || has("capture")) ? await workspaceSlug().catch(() => null) : null;
3909
3936
  let install = false;
3910
3937
  if (engines.length && (has("skill") || has("capture") || has("plugins"))) {
3911
- const captureNoticeLines = has("capture") && workspace2 ? captureNotice(workspace2, await (await import("./trace-library-4F57EGL7.js")).sourceFolders()) : [];
3938
+ const captureNoticeLines = has("capture") && workspace2 ? captureNotice(workspace2, await (await import("./trace-library-V23TEXG4.js")).sourceFolders()) : [];
3912
3939
  if (interactive) for (const line2 of captureNoticeLines) console.log(line2);
3913
3940
  install = await agreed(installQuestion(engines.map((engine) => engine.name), { capture: captureNoticeLines.length > 0 }));
3914
3941
  if (!interactive && captureNoticeLines.length) captureNotices = captureNoticeLines;
@@ -3960,9 +3987,9 @@ async function setUp(opts, journal, afterwards = []) {
3960
3987
  for (const client of mcpOnly) await registerMcp(client);
3961
3988
  if (token) {
3962
3989
  try {
3963
- const { localSkillWorkspace } = await import("./local-skills-run-FSVTDDOW.js");
3990
+ const { localSkillWorkspace } = await import("./local-skills-run-6SZJQSVF.js");
3964
3991
  const workspace3 = await localSkillWorkspace();
3965
- const { libraryRequest } = await import("./trace-library-4F57EGL7.js");
3992
+ const { libraryRequest } = await import("./trace-library-V23TEXG4.js");
3966
3993
  const local = await syncLocalSkills({
3967
3994
  workspace: workspace3,
3968
3995
  targets: skillTargets(agents, hermes?.root ?? null),
@@ -4090,45 +4117,45 @@ async function connectPlans(agents, opts, interactive, emit, run3) {
4090
4117
  const only = planProviders(opts.plans);
4091
4118
  const wanted = (provider) => only === null || only.has(provider);
4092
4119
  const connected = opts.dryRun && !apiToken() ? /* @__PURE__ */ new Set() : await connectedProviders();
4093
- const record3 = (provider, outcome, detail) => {
4120
+ const record = (provider, outcome, detail) => {
4094
4121
  emit({ type: "plan", provider, outcome, ...detail ? { detail } : {} });
4095
4122
  if (outcome === "available") return;
4096
4123
  run3.plans.push({ provider, outcome: outcome === "already" ? "connected" : outcome });
4097
4124
  };
4098
4125
  const copy = async (provider, name, read) => {
4099
- if (connected.has(provider)) return record3(provider, "already");
4126
+ if (connected.has(provider)) return record(provider, "already");
4100
4127
  let found;
4101
4128
  try {
4102
4129
  found = read();
4103
4130
  } catch (error) {
4104
4131
  if (error instanceof ApiError && error.status === 404) return;
4105
- return record3(provider, "failed", message(error));
4132
+ return record(provider, "failed", message(error));
4106
4133
  }
4107
- if (opts.dryRun) return record3(provider, "available", found.account ? `account ${found.account}` : void 0);
4134
+ if (opts.dryRun) return record(provider, "available", found.account ? `account ${found.account}` : void 0);
4108
4135
  if (interactive && !await confirm2(`Use the ${name} sign-in on this computer${found.account ? ` (account ${found.account})` : ""} for your cloud agents?`)) {
4109
- return record3(provider, "skipped");
4136
+ return record(provider, "skipped");
4110
4137
  }
4111
4138
  try {
4112
4139
  await put(provider, found.raw);
4113
- record3(provider, "connected");
4140
+ record(provider, "connected");
4114
4141
  } catch (error) {
4115
- record3(provider, "failed", message(error));
4142
+ record(provider, "failed", message(error));
4116
4143
  }
4117
4144
  };
4118
4145
  if (agents.some((agent2) => agent2.id === "claude_code") && wanted("anthropic")) {
4119
- if (connected.has("anthropic")) record3("anthropic", "already");
4120
- else if (opts.dryRun) record3("anthropic", "available");
4121
- else if (opts.json || opts.yes || opts.claude === false) record3("anthropic", "skipped", "needs a browser approval");
4122
- else if (!await confirm2("Connect your Claude plan? It opens the browser for one approval and does not sign Claude Code out.")) record3("anthropic", "skipped");
4146
+ if (connected.has("anthropic")) record("anthropic", "already");
4147
+ else if (opts.dryRun) record("anthropic", "available");
4148
+ else if (opts.json || opts.yes || opts.claude === false) record("anthropic", "skipped", "needs a browser approval");
4149
+ else if (!await confirm2("Connect your Claude plan? It opens the browser for one approval and does not sign Claude Code out.")) record("anthropic", "skipped");
4123
4150
  else {
4124
4151
  const token = await mintClaudeToken();
4125
- if (!token) record3("anthropic", "failed", "`claude setup-token` did not return a token");
4152
+ if (!token) record("anthropic", "failed", "`claude setup-token` did not return a token");
4126
4153
  else {
4127
4154
  try {
4128
4155
  await put("anthropic", token);
4129
- record3("anthropic", "connected");
4156
+ record("anthropic", "connected");
4130
4157
  } catch (error) {
4131
- record3("anthropic", "failed", message(error));
4158
+ record("anthropic", "failed", message(error));
4132
4159
  }
4133
4160
  }
4134
4161
  }
@@ -4393,9 +4420,9 @@ function interruptLine(res) {
4393
4420
  }
4394
4421
 
4395
4422
  // src/index.ts
4396
- import { createHash as createHash10 } from "crypto";
4423
+ import { createHash as createHash12 } from "crypto";
4397
4424
  import { existsSync as existsSync15, readFileSync as readFileSync28, writeFileSync as writeFileSync13 } from "fs";
4398
- import { basename as basename9, resolve as resolve13 } from "path";
4425
+ import { basename as basename8, resolve as resolve13 } from "path";
4399
4426
  import { createInterface as createInterface5 } from "readline";
4400
4427
  import { Command, Option } from "commander";
4401
4428
 
@@ -4407,27 +4434,27 @@ function eventsQuery(opts) {
4407
4434
  return query ? `?${query}` : "";
4408
4435
  }
4409
4436
  function renderEventPage(page) {
4410
- const lines2 = page.data.map((event) => {
4437
+ const lines = page.data.map((event) => {
4411
4438
  const who = event.actor.session_id ? `agent ${event.actor.session_id}` : event.actor.kind;
4412
4439
  const objects = event.objects.map((object) => `${object.type}:${object.id.length > 24 ? `${object.id.slice(0, 12)}\u2026` : object.id}${object.role ? `(${object.role})` : ""}`).join(" ");
4413
4440
  return `${event.occurred_at} ${event.id} ${event.kind.padEnd(26)} ${who} via ${event.surface} ${objects}`;
4414
4441
  });
4415
- if (!page.data.length) lines2.push("no events on this page");
4416
- if (page.next_cursor) lines2.push(`more: --cursor ${page.next_cursor}`);
4417
- return lines2.join("\n");
4442
+ if (!page.data.length) lines.push("no events on this page");
4443
+ if (page.next_cursor) lines.push(`more: --cursor ${page.next_cursor}`);
4444
+ return lines.join("\n");
4418
4445
  }
4419
4446
  function renderDigestPage(page) {
4420
4447
  if (!page.data.length) return "no digests in this range";
4421
4448
  return page.data.map((digest) => {
4422
- const lines2 = [`${digest.window?.key ?? digest.id} ${digest.title ?? ""} (${digest.stats?.events ?? 0} events, ${digest.id})`];
4423
- if (digest.summary) lines2.push(digest.summary);
4449
+ const lines = [`${digest.window?.key ?? digest.id} ${digest.title ?? ""} (${digest.stats?.events ?? 0} events, ${digest.id})`];
4450
+ if (digest.summary) lines.push(digest.summary);
4424
4451
  for (const activity of digest.activities ?? []) {
4425
- lines2.push(`- ${activity.title}${activity.where ? ` [${activity.where}]` : ""}: ${activity.what}`);
4426
- for (const decision of activity.decisions) lines2.push(` decision: ${decision}`);
4427
- for (const output2 of activity.outputs) lines2.push(` output: ${output2}`);
4428
- lines2.push(` events: ${activity.event_ids.join(" ")}`);
4452
+ lines.push(`- ${activity.title}${activity.where ? ` [${activity.where}]` : ""}: ${activity.what}`);
4453
+ for (const decision of activity.decisions) lines.push(` decision: ${decision}`);
4454
+ for (const output2 of activity.outputs) lines.push(` output: ${output2}`);
4455
+ lines.push(` events: ${activity.event_ids.join(" ")}`);
4429
4456
  }
4430
- return lines2.join("\n");
4457
+ return lines.join("\n");
4431
4458
  }).join("\n\n");
4432
4459
  }
4433
4460
  function renderTimelinePause(paused) {
@@ -4473,22 +4500,22 @@ function renderMyDigests(digests) {
4473
4500
  return `${what}: ${digests.enabled ? "on" : "off"}${digests.workspace_enabled ? "" : " (the workspace has digests off)"}.`;
4474
4501
  }
4475
4502
  function renderCapturePage(page) {
4476
- const lines2 = [];
4503
+ const lines = [];
4477
4504
  if (page.sources) {
4478
4505
  for (const source of page.sources) {
4479
- if (source.kind === "message") lines2.push(`${source.source}: ${source.count} messages, ${source.first_at?.slice(0, 10)} to ${source.last_at?.slice(0, 10)}`);
4480
- else if (source.days?.length) lines2.push(`${source.source}: ${source.days.length} days (${source.days[0]} to ${source.days.at(-1)})`);
4506
+ if (source.kind === "message") lines.push(`${source.source}: ${source.count} messages, ${source.first_at?.slice(0, 10)} to ${source.last_at?.slice(0, 10)}`);
4507
+ else if (source.days?.length) lines.push(`${source.source}: ${source.days.length} days (${source.days[0]} to ${source.days.at(-1)})`);
4481
4508
  }
4482
- if (lines2.length) lines2.push("");
4509
+ if (lines.length) lines.push("");
4483
4510
  }
4484
4511
  for (const item of page.data) {
4485
- if (item.kind === "segment") lines2.push(`${item.day} ${item.source} ${item.segment} ${item.files} files, ${item.bytes} bytes${item.sealed ? "" : " (uploading)"}`);
4486
- else lines2.push(`${item.occurred_at} ${item.source} ${item.thread ?? item.conversation} ${item.sender ?? "?"}: ${(item.subject ?? item.preview ?? "").replace(/\s+/g, " ").slice(0, 100)}${item.files ? ` [${item.files} files]` : ""}`);
4512
+ if (item.kind === "segment") lines.push(`${item.day} ${item.source} ${item.segment} ${item.files} files, ${item.bytes} bytes${item.sealed ? "" : " (uploading)"}`);
4513
+ else lines.push(`${item.occurred_at} ${item.source} ${item.thread ?? item.conversation} ${item.sender ?? "?"}: ${(item.subject ?? item.preview ?? "").replace(/\s+/g, " ").slice(0, 100)}${item.files ? ` [${item.files} files]` : ""}`);
4487
4514
  }
4488
- if (!lines2.length) lines2.push("Nothing captured.");
4489
- if (page.partial) lines2.push("Some days hold more than one read lists; ask for one day at a time.");
4490
- if (page.next_cursor) lines2.push(`more: --cursor ${page.next_cursor}`);
4491
- return lines2.join("\n");
4515
+ if (!lines.length) lines.push("Nothing captured.");
4516
+ if (page.partial) lines.push("Some days hold more than one read lists; ask for one day at a time.");
4517
+ if (page.next_cursor) lines.push(`more: --cursor ${page.next_cursor}`);
4518
+ return lines.join("\n");
4492
4519
  }
4493
4520
  function renderCaptureDeletion(total) {
4494
4521
  if (total.deleted_messages !== void 0) return `Deleted ${total.deleted_messages} ${total.source} messages.`;
@@ -4498,10 +4525,10 @@ function renderCaptureDeletion(total) {
4498
4525
  // src/sky-progress.ts
4499
4526
  var STAGE = { assigned: "assigned", in_progress: "in progress", delivered: "delivered", landed: "landed" };
4500
4527
  function renderProgressPage(page) {
4501
- const lines2 = page.threads.map((thread2) => `${thread2.needs_you ? "needs you " : " "}${STAGE[thread2.stage].padEnd(12)}${thread2.title} \u2014 ${thread2.sentence}${thread2.owner?.name ? ` (${thread2.owner.name})` : ""} ${thread2.task_id}`);
4502
- if (!lines2.length) lines2.push("no threads");
4503
- if (page.next_cursor) lines2.push(`more: --cursor ${page.next_cursor}`);
4504
- return lines2.join("\n");
4528
+ const lines = page.threads.map((thread2) => `${thread2.needs_you ? "needs you " : " "}${STAGE[thread2.stage].padEnd(12)}${thread2.title} \u2014 ${thread2.sentence}${thread2.owner?.name ? ` (${thread2.owner.name})` : ""} ${thread2.task_id}`);
4529
+ if (!lines.length) lines.push("no threads");
4530
+ if (page.next_cursor) lines.push(`more: --cursor ${page.next_cursor}`);
4531
+ return lines.join("\n");
4505
4532
  }
4506
4533
 
4507
4534
  // src/files.ts
@@ -4683,30 +4710,30 @@ function driverLine(goal2) {
4683
4710
  }
4684
4711
  function renderGoal(goal2) {
4685
4712
  if (!goal2) return 'No goal. Set one: sky goal set <session> "<objective>"';
4686
- const lines2 = [];
4713
+ const lines = [];
4687
4714
  const state = goal2.status === "stopped" && goal2.stop_reason ? `stopped (${goal2.stop_reason})` : goal2.status;
4688
- lines2.push(`${goal2.id} ${state} iteration ${goal2.iteration}/${goal2.max_iterations}`);
4689
- lines2.push(`objective: ${goal2.objective}`);
4690
- if (goal2.driver !== void 0) lines2.push(driverLine(goal2));
4715
+ lines.push(`${goal2.id} ${state} iteration ${goal2.iteration}/${goal2.max_iterations}`);
4716
+ lines.push(`objective: ${goal2.objective}`);
4717
+ if (goal2.driver !== void 0) lines.push(driverLine(goal2));
4691
4718
  const spend = goal2.max_spend ? `${dollars2(goal2.consumed_spend.amount)} of ${dollars2(goal2.max_spend.amount)}` : dollars2(goal2.consumed_spend.amount);
4692
4719
  const tokens = goal2.max_tokens === null ? `${goal2.consumed_tokens}` : `${goal2.consumed_tokens} of ${goal2.max_tokens}`;
4693
- lines2.push(`spent: ${spend} tokens: ${tokens}${goal2.deadline_at ? ` deadline: ${goal2.deadline_at}` : ""}`);
4720
+ lines.push(`spent: ${spend} tokens: ${tokens}${goal2.deadline_at ? ` deadline: ${goal2.deadline_at}` : ""}`);
4694
4721
  const verdicts = new Map((goal2.last_evaluation?.criteria ?? []).map((c) => [c.id, c]));
4695
- lines2.push(`criteria${goal2.criteria_source === "derived" ? " (written from the objective)" : ""}:`);
4722
+ lines.push(`criteria${goal2.criteria_source === "derived" ? " (written from the objective)" : ""}:`);
4696
4723
  for (const criterion of goal2.criteria) {
4697
4724
  const verdict = verdicts.get(criterion.id);
4698
4725
  const mark = verdict ? verdict.met ? "[x]" : "[ ]" : "[?]";
4699
- lines2.push(` ${mark} ${criterion.id} ${criterion.text}`);
4700
- if (criterion.command) lines2.push(` $ ${criterion.command}`);
4701
- for (const file of criterion.files ?? []) lines2.push(` frozen: ${file.path} (sha256 ${file.sha256.slice(0, 12)})`);
4726
+ lines.push(` ${mark} ${criterion.id} ${criterion.text}`);
4727
+ if (criterion.command) lines.push(` $ ${criterion.command}`);
4728
+ for (const file of criterion.files ?? []) lines.push(` frozen: ${file.path} (sha256 ${file.sha256.slice(0, 12)})`);
4702
4729
  const ran = verdict && ranLine(verdict);
4703
- if (ran) lines2.push(` ${ran}`);
4704
- if (verdict && !verdict.met && verdict.reason) lines2.push(` ${verdict.reason}`);
4730
+ if (ran) lines.push(` ${ran}`);
4731
+ if (verdict && !verdict.met && verdict.reason) lines.push(` ${verdict.reason}`);
4705
4732
  }
4706
4733
  if (goal2.last_evaluation && goal2.last_evaluation.result !== "satisfied") {
4707
- lines2.push(`last check (iteration ${goal2.last_evaluation.iteration}): ${goal2.last_evaluation.explanation}`);
4734
+ lines.push(`last check (iteration ${goal2.last_evaluation.iteration}): ${goal2.last_evaluation.explanation}`);
4708
4735
  }
4709
- return lines2.join("\n");
4736
+ return lines.join("\n");
4710
4737
  }
4711
4738
 
4712
4739
  // src/account.ts
@@ -4737,10 +4764,10 @@ var usd = (value) => `$${value.toFixed(2)}`;
4737
4764
  var centsUsd = (money) => money.amount_usd !== void 0 ? `$${Number(money.amount_usd).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 6, useGrouping: false })}` : `$${(Number(money.amount) / 100).toFixed(2)}`;
4738
4765
  function renderAutoTopup(settings) {
4739
4766
  const state = settings.enabled ? `on \u2014 below ${usd(settings.threshold_usd)}, the saved card adds ${usd(settings.amount_usd)}` : `off${settings.opted_out ? " (you turned it off)" : ""} \u2014 would add ${usd(settings.amount_usd)} below ${usd(settings.threshold_usd)}`;
4740
- const lines2 = [`auto top-up: ${state}`];
4741
- if (settings.card_on_file === false) lines2.push(" no saved card \u2014 `sky billing card` adds one");
4742
- if (settings.failure) lines2.push(` last charge failed${settings.failure.paused ? " (paused)" : ""}: ${settings.failure.reason}`);
4743
- return lines2.join("\n");
4767
+ const lines = [`auto top-up: ${state}`];
4768
+ if (settings.card_on_file === false) lines.push(" no saved card \u2014 `sky billing card` adds one");
4769
+ if (settings.failure) lines.push(` last charge failed${settings.failure.paused ? " (paused)" : ""}: ${settings.failure.reason}`);
4770
+ return lines.join("\n");
4744
4771
  }
4745
4772
  function renderBalance(balance) {
4746
4773
  return `balance: ${usd(balance.balance_usd)} card on file: ${balance.card_on_file ? "yes" : "no"}`;
@@ -4758,13 +4785,13 @@ function measureLine(m) {
4758
4785
  return `${String(m.calls).padStart(6)} calls ${String(m.inputTokens).padStart(10)} in ${String(m.outputTokens).padStart(9)} out ${`$${m.billedCostUsd.toFixed(4)}`.padStart(10)}`;
4759
4786
  }
4760
4787
  function renderUsage(summary) {
4761
- const lines2 = [`usage ${summary.range.from} \u2192 ${summary.range.to} (end exclusive), by ${summary.groupBy}`];
4788
+ const lines = [`usage ${summary.range.from} \u2192 ${summary.range.to} (end exclusive), by ${summary.groupBy}`];
4762
4789
  for (const group of summary.groups) {
4763
- lines2.push(` ${group.label.padEnd(28).slice(0, 28)} ${group.source.padEnd(8)} ${measureLine(group)}`);
4790
+ lines.push(` ${group.label.padEnd(28).slice(0, 28)} ${group.source.padEnd(8)} ${measureLine(group)}`);
4764
4791
  }
4765
- if (!summary.groups.length) lines2.push(" no usage in this range");
4766
- lines2.push(` ${"total".padEnd(37)} ${measureLine(summary.totals)}`);
4767
- return lines2.join("\n");
4792
+ if (!summary.groups.length) lines.push(" no usage in this range");
4793
+ lines.push(` ${"total".padEnd(37)} ${measureLine(summary.totals)}`);
4794
+ return lines.join("\n");
4768
4795
  }
4769
4796
  function usageQuery(opts) {
4770
4797
  const params = new URLSearchParams();
@@ -4919,16 +4946,16 @@ function refArgument(ref) {
4919
4946
  return `'${JSON.stringify(ref).replace(/'/g, "'\\''")}'`;
4920
4947
  }
4921
4948
  function renderContextPage(page) {
4922
- const lines2 = [];
4949
+ const lines = [];
4923
4950
  for (const hit of page.hits) {
4924
- lines2.push(`${hit.path ?? hit.title}${hit.line ? `:${hit.line}` : ""}: ${hit.snippet.replace(/\s+/g, " ").slice(0, 160)}`);
4925
- lines2.push(` sky context read ${refArgument(hit.ref)}`);
4951
+ lines.push(`${hit.path ?? hit.title}${hit.line ? `:${hit.line}` : ""}: ${hit.snippet.replace(/\s+/g, " ").slice(0, 160)}`);
4952
+ lines.push(` sky context read ${refArgument(hit.ref)}`);
4926
4953
  }
4927
- if (!page.hits.length) lines2.push("no matches on this page");
4954
+ if (!page.hits.length) lines.push("no matches on this page");
4928
4955
  const missed = (page.sources ?? []).filter((source) => source.status === "failed" || source.status === "partial").map((source) => source.source);
4929
- if (page.partial) lines2.push(`partial: ${missed.length ? `${missed.join(", ")} not fully searched` : "not every source was searched"}`);
4930
- if (page.nextCursor) lines2.push(`more: --cursor ${page.nextCursor}`);
4931
- return lines2.join("\n");
4956
+ if (page.partial) lines.push(`partial: ${missed.length ? `${missed.join(", ")} not fully searched` : "not every source was searched"}`);
4957
+ if (page.nextCursor) lines.push(`more: --cursor ${page.nextCursor}`);
4958
+ return lines.join("\n");
4932
4959
  }
4933
4960
 
4934
4961
  // src/agent-manifest-file.ts
@@ -5115,14 +5142,14 @@ function deployReport(id2, spec, before, after, promptChanged) {
5115
5142
  if (promptChanged) changed.push("prompt");
5116
5143
  if (after.version !== before.version) changed.push("settings");
5117
5144
  if (!changed.length) return [`${id2} is up to date \u2014 nothing to deploy (version ${after.version})`];
5118
- const lines2 = [`Deployed ${id2}: ${changed.join(" and ")} updated (version ${before.version} \u2192 ${after.version})`];
5145
+ const lines = [`Deployed ${id2}: ${changed.join(" and ")} updated (version ${before.version} \u2192 ${after.version})`];
5119
5146
  if (after.agentType !== before.agentType || after.llm !== before.llm) {
5120
- lines2.push(` now ${after.agentType} \xB7 ${after.llm} for new sessions (was ${before.agentType} \xB7 ${before.llm})`);
5147
+ lines.push(` now ${after.agentType} \xB7 ${after.llm} for new sessions (was ${before.agentType} \xB7 ${before.llm})`);
5121
5148
  }
5122
5149
  if (spec.skills && after.version !== before.version) {
5123
- lines2.push(` Skills apply to new sessions; running sessions keep the skills they started with \u2014 start one with \`sky session create ${id2}\`.`);
5150
+ lines.push(` Skills apply to new sessions; running sessions keep the skills they started with \u2014 start one with \`sky session create ${id2}\`.`);
5124
5151
  }
5125
- return lines2;
5152
+ return lines;
5126
5153
  }
5127
5154
 
5128
5155
  // src/agent-manifest-file.ts
@@ -5159,30 +5186,30 @@ function stampManifestId(path2, id2) {
5159
5186
  writeFileSync7(path2, stampIdText(readFileSync17(path2, "utf8"), id2));
5160
5187
  }
5161
5188
  function lineOfField(text2, field) {
5162
- const lines2 = text2.split("\n");
5189
+ const lines = text2.split("\n");
5163
5190
  const [top, index, key] = field.split(".");
5164
- const keyLine = (name, from = 0, to = lines2.length) => {
5165
- const at = lines2.slice(from, to).findIndex((line3) => new RegExp(`^\\s*"?${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"?\\s*=`).test(line3));
5191
+ const keyLine = (name, from = 0, to = lines.length) => {
5192
+ const at = lines.slice(from, to).findIndex((line3) => new RegExp(`^\\s*"?${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"?\\s*=`).test(line3));
5166
5193
  return at < 0 ? null : from + at;
5167
5194
  };
5168
5195
  if (top === void 0) return null;
5169
5196
  if (index !== void 0 && /^\d+$/.test(index)) {
5170
- const headers = lines2.map((line3, at) => new RegExp(`^\\s*\\[\\[\\s*${top}\\s*\\]\\]`).test(line3) ? at : -1).filter((at) => at >= 0);
5197
+ const headers = lines.map((line3, at) => new RegExp(`^\\s*\\[\\[\\s*${top}\\s*\\]\\]`).test(line3) ? at : -1).filter((at) => at >= 0);
5171
5198
  const header2 = headers[Number(index)];
5172
5199
  if (header2 !== void 0) {
5173
- const end = lines2.findIndex((line3, at) => at > header2 && /^\s*\[/.test(line3));
5174
- const within = key ? keyLine(key, header2 + 1, end < 0 ? lines2.length : end) : null;
5200
+ const end = lines.findIndex((line3, at) => at > header2 && /^\s*\[/.test(line3));
5201
+ const within = key ? keyLine(key, header2 + 1, end < 0 ? lines.length : end) : null;
5175
5202
  return (within ?? header2) + 1;
5176
5203
  }
5177
5204
  }
5178
- const tableHeader = lines2.findIndex((line3) => new RegExp(`^\\s*\\[\\s*${top}\\s*\\]`).test(line3));
5205
+ const tableHeader = lines.findIndex((line3) => new RegExp(`^\\s*\\[\\s*${top}\\s*\\]`).test(line3));
5179
5206
  if (tableHeader >= 0) {
5180
- const end = lines2.findIndex((line3, at) => at > tableHeader && /^\s*\[/.test(line3));
5181
- const within = index !== void 0 ? keyLine(index, tableHeader + 1, end < 0 ? lines2.length : end) : null;
5207
+ const end = lines.findIndex((line3, at) => at > tableHeader && /^\s*\[/.test(line3));
5208
+ const within = index !== void 0 ? keyLine(index, tableHeader + 1, end < 0 ? lines.length : end) : null;
5182
5209
  return (within ?? tableHeader) + 1;
5183
5210
  }
5184
- const firstTable = lines2.findIndex((line3) => /^\s*\[/.test(line3));
5185
- const line2 = keyLine(top, 0, firstTable < 0 ? lines2.length : firstTable);
5211
+ const firstTable = lines.findIndex((line3) => /^\s*\[/.test(line3));
5212
+ const line2 = keyLine(top, 0, firstTable < 0 ? lines.length : firstTable);
5186
5213
  return line2 === null ? null : line2 + 1;
5187
5214
  }
5188
5215
  function refusalLines(label, text2, issues) {
@@ -5249,7 +5276,7 @@ async function setEngineStatus(engine, status, reason2) {
5249
5276
  var uses = (agent2) => `${agent2.stats.uses} ${agent2.stats.uses === 1 ? "use" : "uses"}`;
5250
5277
  var mine = (agent2) => agent2.visibility === "workspace" ? " (yours)" : "";
5251
5278
  function renderCatalogAgent(agent2) {
5252
- const section = (title, lines2) => lines2.length ? [`${title}:`, ...lines2.map((line2) => ` - ${line2}`)] : [];
5279
+ const section = (title, lines) => lines.length ? [`${title}:`, ...lines.map((line2) => ` - ${line2}`)] : [];
5253
5280
  return [
5254
5281
  `@${agent2.handle} ${agent2.name}${mine(agent2)}`,
5255
5282
  agent2.tagline,
@@ -5829,6 +5856,15 @@ async function slackBot(agentId, team, wait) {
5829
5856
  async function unpublishFromSlack(agentId, team) {
5830
5857
  return api("DELETE", `/channels/agent-bots/slack/${encodeURIComponent(agentId)}${teamQuery(team)}`);
5831
5858
  }
5859
+ async function connectAgentSlackDm(agentId) {
5860
+ return api("POST", `/channels/agent-bots/slack/${encodeURIComponent(agentId)}/dm`);
5861
+ }
5862
+ async function agentSlackDm(agentId) {
5863
+ return api("GET", `/channels/agent-bots/slack/${encodeURIComponent(agentId)}/dm`);
5864
+ }
5865
+ async function disconnectAgentSlackDm(agentId) {
5866
+ return api("DELETE", `/channels/agent-bots/slack/${encodeURIComponent(agentId)}/dm`);
5867
+ }
5832
5868
 
5833
5869
  // src/routine-triggers.ts
5834
5870
  var triggerPath = (id2, resource) => `/routines/${encodeURIComponent(id2)}/${resource}`;
@@ -5871,1364 +5907,8 @@ import { spawnSync as spawnSync2 } from "child_process";
5871
5907
  import { createHash as createHash8, randomUUID as randomUUID5 } from "crypto";
5872
5908
  import { existsSync as existsSync12, lstatSync as lstatSync5, mkdirSync as mkdirSync5, readdirSync as readdirSync8, readFileSync as readFileSync20, renameSync as renameSync2, statSync as statSync6, writeFileSync as writeFileSync9 } from "fs";
5873
5909
  import { homedir as homedir11, hostname as hostname2, tmpdir as tmpdir3 } from "os";
5874
- import { basename as basename7, dirname as dirname10, join as join16, relative as relative4, resolve as resolve10 } from "path";
5910
+ import { basename as basename6, dirname as dirname10, join as join16, relative as relative4, resolve as resolve10 } from "path";
5875
5911
  import { inflateRawSync } from "zlib";
5876
-
5877
- // ../../packages/spec/src/native/triage.ts
5878
- var KEPT_ATTACHMENT_KINDS = /* @__PURE__ */ new Set([
5879
- "queued_command",
5880
- "edited_text_file"
5881
- ]);
5882
- var DROPPED_ATTACHMENT_KINDS = /* @__PURE__ */ new Set([
5883
- "total_tokens_reminder",
5884
- "batching_reminder_sent",
5885
- "hook_success",
5886
- "hook_non_blocking_error",
5887
- "hook_additional_context",
5888
- "environment",
5889
- "deferred_tools_delta",
5890
- "compact_file_reference"
5891
- ]);
5892
- var DROPPED_LINE_TYPES = /* @__PURE__ */ new Set([
5893
- "bridge-session",
5894
- "queue-operation",
5895
- "last-prompt",
5896
- "custom-title",
5897
- "atis-latch",
5898
- "pr-link",
5899
- "frame-link",
5900
- "mode",
5901
- "file-history-snapshot",
5902
- "file-history-delta",
5903
- "ai-title",
5904
- "agent-setting",
5905
- "permission-mode",
5906
- "cost-state",
5907
- "relocated",
5908
- "artifact-autoreact-ledger",
5909
- "artifact-comment-monitor"
5910
- ]);
5911
- function isInjectedTurn(line2) {
5912
- return line2.isMeta === true || line2.isSynthetic === true || line2.isCompactSummary === true;
5913
- }
5914
- function isImageCompanion(blocks) {
5915
- if (blocks.length === 0) return false;
5916
- return blocks.every((block) => {
5917
- if (typeof block !== "object" || block === null) return false;
5918
- const b = block;
5919
- return b.type === "text" && typeof b.text === "string" && /^\s*\[Image:\s*source:/.test(b.text);
5920
- });
5921
- }
5922
- function triage(line2) {
5923
- const type = typeof line2.type === "string" ? line2.type : null;
5924
- if (type === null) return { keep: false, reason: "no line type" };
5925
- if (type === "attachment") {
5926
- const payload = typeof line2.attachment === "object" && line2.attachment !== null ? line2.attachment : line2;
5927
- const kind = typeof payload.type === "string" ? payload.type : "";
5928
- if (KEPT_ATTACHMENT_KINDS.has(kind)) return { keep: true, reason: `attachment:${kind}` };
5929
- if (DROPPED_ATTACHMENT_KINDS.has(kind)) return { keep: false, reason: `bookkeeping:${kind}` };
5930
- return { keep: true, reason: `attachment:unclassified:${kind || "unnamed"}` };
5931
- }
5932
- if (DROPPED_LINE_TYPES.has(type)) return { keep: false, reason: `bookkeeping:${type}` };
5933
- if (type === "user" || type === "assistant") return { keep: true, reason: type };
5934
- if (type === "system") return { keep: false, reason: "harness system line" };
5935
- return { keep: true, reason: `unclassified:${type}` };
5936
- }
5937
-
5938
- // ../../packages/spec/src/native/claude-code.ts
5939
- var INTERRUPT_MARKERS = [
5940
- "[Request interrupted by user",
5941
- "Tool use was rejected"
5942
- ];
5943
- function textOf2(value) {
5944
- return typeof value === "string" ? value : "";
5945
- }
5946
- function basename6(path2) {
5947
- const parts = path2.split(/[\\/]/);
5948
- return parts[parts.length - 1] ?? path2;
5949
- }
5950
- function guessMediaType(name) {
5951
- const ext = name.slice(name.lastIndexOf(".") + 1).toLowerCase();
5952
- const map = {
5953
- png: "image/png",
5954
- jpg: "image/jpeg",
5955
- jpeg: "image/jpeg",
5956
- gif: "image/gif",
5957
- webp: "image/webp",
5958
- pdf: "application/pdf",
5959
- json: "application/json",
5960
- csv: "text/csv",
5961
- md: "text/markdown",
5962
- html: "text/html",
5963
- css: "text/css",
5964
- js: "text/javascript",
5965
- ts: "text/typescript",
5966
- tsx: "text/typescript",
5967
- py: "text/x-python"
5968
- };
5969
- return map[ext] ?? "text/plain";
5970
- }
5971
- function looksInterrupted(blocks) {
5972
- return blocks.some((block) => {
5973
- if (typeof block !== "object" || block === null) return false;
5974
- const text2 = textOf2(block.text);
5975
- return INTERRUPT_MARKERS.some((marker) => text2.includes(marker));
5976
- });
5977
- }
5978
- function imageBlockToPart(block, index) {
5979
- const source = typeof block.source === "object" && block.source !== null ? block.source : {};
5980
- const data = textOf2(source.data);
5981
- const uri = textOf2(source.url) || textOf2(block.url);
5982
- if (!data && !uri) return null;
5983
- const embedded = uri && isEmbeddedImage(uri) ? uri : "";
5984
- if (!data && !embedded) return { type: "text", index, text: imageLinkText(uri) };
5985
- return {
5986
- type: "image",
5987
- index,
5988
- media_type: textOf2(source.media_type) || imageMediaType(embedded || uri || `data:${textOf2(source.type)};`),
5989
- ...embedded ? { uri: embedded } : {},
5990
- ...data ? { data } : {}
5991
- };
5992
- }
5993
- function documentBlockToPart(block, index) {
5994
- const source = typeof block.source === "object" && block.source !== null ? block.source : {};
5995
- const mediaType = textOf2(source.media_type) || "application/pdf";
5996
- const name = textOf2(block.title) || `document.${mediaType === "application/pdf" ? "pdf" : mediaType === "text/plain" ? "txt" : "bin"}`;
5997
- if (source.type === "base64" && textOf2(source.data)) {
5998
- const data = textOf2(source.data);
5999
- return { type: "file", index, name, media_type: mediaType, data, size_bytes: Math.floor(data.replace(/=+$/, "").length * 3 / 4) };
6000
- }
6001
- if (source.type === "text" && textOf2(source.data)) {
6002
- const bytes = new TextEncoder().encode(textOf2(source.data));
6003
- let binary = "";
6004
- for (const byte of bytes) binary += String.fromCharCode(byte);
6005
- return { type: "file", index, name, media_type: "text/plain", data: btoa(binary), size_bytes: bytes.length };
6006
- }
6007
- const url = textOf2(source.url);
6008
- return url ? { type: "text", index, text: remoteLinkText("document", url) } : null;
6009
- }
6010
- function isEmbeddedImage(url) {
6011
- return /^data:/i.test(url);
6012
- }
6013
- function imageLinkText(url) {
6014
- return remoteLinkText("image", url);
6015
- }
6016
- function remoteLinkText(kind, url) {
6017
- return `[${kind} not carried, linked at ${url}]`;
6018
- }
6019
- function imageMediaType(url) {
6020
- const data = /^data:([a-zA-Z0-9.+-]+\/[a-zA-Z0-9.+-]+)[;,]/.exec(url);
6021
- if (data) return data[1].toLowerCase();
6022
- const ext = /\.([a-zA-Z0-9]+)(?:[?#]|$)/.exec(url)?.[1]?.toLowerCase();
6023
- const byExtension = {
6024
- png: "image/png",
6025
- jpg: "image/jpeg",
6026
- jpeg: "image/jpeg",
6027
- gif: "image/gif",
6028
- webp: "image/webp",
6029
- svg: "image/svg+xml",
6030
- bmp: "image/bmp",
6031
- avif: "image/avif"
6032
- };
6033
- return ext && byExtension[ext] || "application/octet-stream";
6034
- }
6035
- function assistantParts(blocks) {
6036
- const parts = [];
6037
- const calls = [];
6038
- blocks.forEach((raw, index) => {
6039
- if (typeof raw !== "object" || raw === null) return;
6040
- const block = raw;
6041
- switch (block.type) {
6042
- case "text": {
6043
- const text2 = textOf2(block.text);
6044
- if (text2) parts.push({ type: "text", index, text: text2 });
6045
- return;
6046
- }
6047
- case "thinking": {
6048
- const text2 = textOf2(block.thinking);
6049
- if (text2) parts.push({ type: "reasoning", index, text: text2, redacted: false });
6050
- return;
6051
- }
6052
- case "image": {
6053
- const part = imageBlockToPart(block, index);
6054
- if (part) parts.push(part);
6055
- return;
6056
- }
6057
- case "tool_use": {
6058
- calls.push({
6059
- type: "agent.tool_use",
6060
- part: {
6061
- type: "tool_call",
6062
- index,
6063
- call_id: textOf2(block.id),
6064
- tool_name: textOf2(block.name),
6065
- args: block.input ?? {}
6066
- }
6067
- });
6068
- return;
6069
- }
6070
- default:
6071
- return;
6072
- }
6073
- });
6074
- return { parts, calls };
6075
- }
6076
- function toolResults(blocks) {
6077
- const out = [];
6078
- blocks.forEach((raw, index) => {
6079
- if (typeof raw !== "object" || raw === null) return;
6080
- const block = raw;
6081
- if (block.type !== "tool_result") return;
6082
- const content = block.content;
6083
- const output2 = typeof content === "string" ? content : content === void 0 ? "" : JSON.stringify(content);
6084
- out.push({
6085
- type: "agent.tool_result",
6086
- part: {
6087
- type: "tool_result",
6088
- index,
6089
- call_id: textOf2(block.tool_use_id),
6090
- tool_name: "",
6091
- status: block.is_error === true ? "error" : "ok",
6092
- result: { output: output2 }
6093
- }
6094
- });
6095
- });
6096
- return out;
6097
- }
6098
- var RENDERED_BLOCKS = /* @__PURE__ */ new Set(["text", "thinking", "image", "document", "tool_use", "tool_result"]);
6099
- function unsupportedBlock(content) {
6100
- if (!Array.isArray(content)) return false;
6101
- return content.some((raw) => {
6102
- if (typeof raw !== "object" || raw === null) return false;
6103
- const type = raw.type;
6104
- return typeof type === "string" && !RENDERED_BLOCKS.has(type);
6105
- });
6106
- }
6107
- function preservedAsJson(label, filename, payload, reason2) {
6108
- const text2 = JSON.stringify(payload);
6109
- const bytes = new TextEncoder().encode(text2);
6110
- let binary = "";
6111
- for (const byte of bytes) binary += String.fromCharCode(byte);
6112
- return {
6113
- events: [{ type: "agent.message", parts: [
6114
- { type: "text", index: 0, text: label },
6115
- { type: "file", index: 1, name: filename, media_type: "application/json", data: btoa(binary), size_bytes: bytes.length }
6116
- ] }],
6117
- notes: [{ kind: "unsupported", reason: reason2 }]
6118
- };
6119
- }
6120
- function decodeLine(line2) {
6121
- const verdict = triage(line2);
6122
- if (!verdict.keep) return { events: [], notes: [{ kind: "dropped", reason: verdict.reason }] };
6123
- const type = line2.type;
6124
- if (type === "attachment") {
6125
- const payload = typeof line2.attachment === "object" && line2.attachment !== null ? line2.attachment : line2;
6126
- if (payload.type === "queued_command") {
6127
- const text2 = textOf2(payload.prompt);
6128
- if (!text2) return { events: [], notes: [] };
6129
- return {
6130
- events: [{ type: "user.message", parts: [{ type: "text", index: 0, text: text2 }] }],
6131
- notes: []
6132
- };
6133
- }
6134
- if (payload.type === "file" || payload.type === "edited_text_file") {
6135
- const name = textOf2(payload.displayPath) || basename6(textOf2(payload.filename)) || "attachment.txt";
6136
- const content2 = payload.content;
6137
- const nested = content2 && typeof content2 === "object" ? content2 : {};
6138
- const file = nested.file && typeof nested.file === "object" ? nested.file : {};
6139
- const text2 = typeof content2 === "string" ? content2 : textOf2(file.content) || textOf2(nested.content) || textOf2(payload.snippet);
6140
- const bytes = new TextEncoder().encode(text2);
6141
- let binary = "";
6142
- for (const byte of bytes) binary += String.fromCharCode(byte);
6143
- if (!name) return { events: [], notes: [] };
6144
- return {
6145
- events: [
6146
- {
6147
- type: "user.message",
6148
- parts: [{ type: "file", index: 0, name, media_type: guessMediaType(name), ...text2 ? { data: btoa(binary), size_bytes: bytes.length } : {} }]
6149
- }
6150
- ],
6151
- notes: []
6152
- };
6153
- }
6154
- return preservedAsJson(
6155
- `Source attachment: ${textOf2(payload.type) || "unnamed"}`,
6156
- "source-attachment.json",
6157
- payload,
6158
- `attachment:${textOf2(payload.type) || "unnamed"} preserved as JSON`
6159
- );
6160
- }
6161
- const messageContent = typeof line2.message === "object" && line2.message !== null ? line2.message.content : null;
6162
- if (unsupportedBlock(messageContent)) {
6163
- return preservedAsJson(
6164
- `Source record: ${type || "untyped"} (it carries a block this reader does not render)`,
6165
- "source-record.json",
6166
- line2,
6167
- `unsupported-block:${type || "untyped"} preserved as JSON`
6168
- );
6169
- }
6170
- if (verdict.reason.startsWith("unclassified:")) {
6171
- return preservedAsJson(
6172
- `Source record: ${type || "untyped"}`,
6173
- "source-record.json",
6174
- line2,
6175
- `${verdict.reason} preserved as JSON`
6176
- );
6177
- }
6178
- const message2 = typeof line2.message === "object" && line2.message !== null ? line2.message : null;
6179
- if (!message2) return { events: [], notes: [] };
6180
- const content = message2.content;
6181
- if (type === "user") {
6182
- if (typeof content === "string") {
6183
- if (isInjectedTurn(line2) || !content.trim()) return { events: [], notes: [] };
6184
- return {
6185
- events: [{ type: "user.message", parts: [{ type: "text", index: 0, text: content }] }],
6186
- notes: []
6187
- };
6188
- }
6189
- if (!Array.isArray(content)) return { events: [], notes: [] };
6190
- if (looksInterrupted(content)) {
6191
- return {
6192
- events: [
6193
- { type: "agent.status", part: { type: "status", index: 0, level: "idle", text: "Conversation interrupted" } }
6194
- ],
6195
- notes: [{ kind: "interrupted" }]
6196
- };
6197
- }
6198
- const results = toolResults(content);
6199
- if (isInjectedTurn(line2)) {
6200
- if (results.length > 0) return { events: results, notes: [] };
6201
- if (isImageCompanion(content)) {
6202
- const parts2 = [];
6203
- let images = 0;
6204
- content.forEach((raw, index) => {
6205
- if (typeof raw !== "object" || raw === null) return;
6206
- const b = raw;
6207
- if (b.type === "image") {
6208
- const part = imageBlockToPart(b, index);
6209
- if (part) {
6210
- parts2.push(part);
6211
- images += 1;
6212
- }
6213
- } else if (typeof b.text === "string" && b.text) {
6214
- parts2.push({ type: "text", index, text: b.text });
6215
- }
6216
- });
6217
- if (parts2.length === 0) return { events: [], notes: [{ kind: "dropped", reason: "injected turn" }] };
6218
- return {
6219
- events: [{ type: "user.message", parts: parts2 }],
6220
- notes: [{ kind: "image-companion", count: images }]
6221
- };
6222
- }
6223
- return { events: [], notes: [{ kind: "dropped", reason: "injected turn" }] };
6224
- }
6225
- const parts = [];
6226
- content.forEach((raw, index) => {
6227
- if (typeof raw !== "object" || raw === null) return;
6228
- const b = raw;
6229
- if (b.type === "text") {
6230
- const text2 = textOf2(b.text);
6231
- if (text2.trim()) parts.push({ type: "text", index, text: text2 });
6232
- } else if (b.type === "image") {
6233
- const part = imageBlockToPart(b, index);
6234
- if (part) parts.push(part);
6235
- } else if (b.type === "document") {
6236
- const part = documentBlockToPart(b, index);
6237
- if (part) parts.push(part);
6238
- }
6239
- });
6240
- const events2 = [...results];
6241
- if (parts.length > 0) events2.push({ type: "user.message", parts });
6242
- return { events: events2, notes: [] };
6243
- }
6244
- if (type === "assistant" && Array.isArray(content)) {
6245
- const { parts, calls } = assistantParts(content);
6246
- const events2 = [];
6247
- if (parts.length > 0) events2.push({ type: "agent.message", parts });
6248
- events2.push(...calls);
6249
- return {
6250
- events: events2,
6251
- notes: [],
6252
- spec: {
6253
- llm: textOf2(message2.model) || void 0,
6254
- reasoningEffort: textOf2(line2.effort) || void 0
6255
- }
6256
- };
6257
- }
6258
- return { events: [], notes: [] };
6259
- }
6260
-
6261
- // ../../packages/spec/src/native/codex.ts
6262
- var EMPTY = { events: [], spec: {} };
6263
- function str2(value) {
6264
- return typeof value === "string" ? value : "";
6265
- }
6266
- function record(value) {
6267
- return typeof value === "object" && value !== null ? value : null;
6268
- }
6269
- function messageText(content) {
6270
- if (typeof content === "string") return content;
6271
- if (!Array.isArray(content)) return "";
6272
- return content.map((block) => {
6273
- const b = record(block);
6274
- if (!b) return "";
6275
- return str2(b.text) || str2(b.output_text);
6276
- }).join("");
6277
- }
6278
- function imageMediaType2(url) {
6279
- const data = /^data:([a-zA-Z0-9.+-]+\/[a-zA-Z0-9.+-]+)[;,]/.exec(url);
6280
- if (data) return data[1].toLowerCase();
6281
- const ext = /\.([a-zA-Z0-9]+)(?:[?#]|$)/.exec(url)?.[1]?.toLowerCase();
6282
- const byExtension = {
6283
- png: "image/png",
6284
- jpg: "image/jpeg",
6285
- jpeg: "image/jpeg",
6286
- gif: "image/gif",
6287
- webp: "image/webp",
6288
- svg: "image/svg+xml",
6289
- bmp: "image/bmp",
6290
- avif: "image/avif"
6291
- };
6292
- return ext && byExtension[ext] || "application/octet-stream";
6293
- }
6294
- function messageParts(content) {
6295
- if (typeof content === "string") {
6296
- return content ? { parts: [{ type: "text", index: 0, text: content }], text: content } : { parts: [], text: "" };
6297
- }
6298
- if (!Array.isArray(content)) return { parts: [], text: "" };
6299
- const parts = [];
6300
- let text2 = "";
6301
- for (const raw of content) {
6302
- const b = record(raw);
6303
- if (!b) continue;
6304
- if (b.type === "input_image" || b.type === "image" || b.type === "image_url") {
6305
- const url = str2(b.image_url) || str2(record(b.image_url)?.url) || str2(b.url);
6306
- const declared = str2(b.media_type) || str2(b.mime_type);
6307
- if (url && isEmbeddedImage(url)) parts.push({ type: "image", index: parts.length, media_type: declared || imageMediaType2(url), uri: url });
6308
- else if (url) parts.push({ type: "text", index: parts.length, text: imageLinkText(url) });
6309
- continue;
6310
- }
6311
- const chunk = str2(b.text) || str2(b.output_text);
6312
- if (!chunk) continue;
6313
- text2 += chunk;
6314
- const last = parts[parts.length - 1];
6315
- if (last && last.type === "text") last.text += chunk;
6316
- else parts.push({ type: "text", index: parts.length, text: chunk });
6317
- }
6318
- return { parts, text: text2 };
6319
- }
6320
- function reasoningText(payload) {
6321
- const direct = str2(payload.text);
6322
- if (direct) return direct;
6323
- const summary = payload.summary;
6324
- if (typeof summary === "string") return summary;
6325
- if (Array.isArray(summary)) {
6326
- return summary.map((entry) => typeof entry === "string" ? entry : str2(record(entry)?.text)).filter(Boolean).join("\n");
6327
- }
6328
- return "";
6329
- }
6330
- function callArgs(payload) {
6331
- const raw = payload.arguments;
6332
- if (typeof raw === "string" && raw.trim()) {
6333
- if (unsafeNumberSpans(raw).length > 0) return { arguments: raw };
6334
- try {
6335
- const parsed = JSON.parse(raw);
6336
- if (record(parsed)) return parsed;
6337
- return { arguments: parsed };
6338
- } catch {
6339
- return { arguments: raw };
6340
- }
6341
- }
6342
- return record(payload.action) ?? record(payload.input) ?? {};
6343
- }
6344
- var INJECTED_USER_OPENERS = [
6345
- "# AGENTS.md instructions",
6346
- "<INSTRUCTIONS>",
6347
- "<codex_internal_context",
6348
- "<in-app-browser-context",
6349
- "<user_instructions>",
6350
- "<environment_context>",
6351
- "[Context: repo="
6352
- ];
6353
- function looksInjected(text2) {
6354
- const head = text2.trimStart();
6355
- return INJECTED_USER_OPENERS.some((marker) => head.startsWith(marker));
6356
- }
6357
- function toolName(payload) {
6358
- const named = str2(payload.name);
6359
- if (named) return named;
6360
- if (payload.type === "local_shell_call") return "shell";
6361
- return str2(payload.type) || "tool";
6362
- }
6363
- function callIdOf(payload) {
6364
- return str2(payload.call_id);
6365
- }
6366
- function callOrOwnId(payload) {
6367
- return str2(payload.call_id) || str2(payload.id);
6368
- }
6369
- function decodeCodexLine(line2) {
6370
- const type = str2(line2.type);
6371
- const payload = record(line2.payload);
6372
- if (type === "session_meta") {
6373
- if (!payload) return EMPTY;
6374
- return {
6375
- events: [],
6376
- spec: {}
6377
- };
6378
- }
6379
- if (type === "turn_context") {
6380
- if (!payload) return EMPTY;
6381
- return {
6382
- events: [],
6383
- spec: {
6384
- llm: str2(payload.model) || void 0,
6385
- reasoningEffort: str2(payload.effort) || str2(payload.reasoning_effort) || void 0
6386
- }
6387
- };
6388
- }
6389
- if (type === "compacted") return { events: [], spec: {} };
6390
- if (type !== "event_msg" && type !== "response_item") return EMPTY;
6391
- if (!payload) return EMPTY;
6392
- const kind = str2(payload.type);
6393
- if (kind === "message") {
6394
- const role = str2(payload.role);
6395
- if (role === "developer" || role === "system") return EMPTY;
6396
- const { parts, text: text2 } = messageParts(payload.content);
6397
- if (parts.length === 0) return EMPTY;
6398
- if (role === "user" && text2.trim() && looksInjected(text2)) return EMPTY;
6399
- if (role === "user") return { events: [{ type: "user.message", parts }], spec: {} };
6400
- if (role === "assistant") return { events: [{ type: "agent.message", parts }], spec: {} };
6401
- return EMPTY;
6402
- }
6403
- if (kind === "agent_message" || kind === "agent_message_delta") {
6404
- const text2 = messageText(payload.content) || str2(payload.delta) || str2(payload.text);
6405
- if (!text2) return EMPTY;
6406
- const from = str2(payload.author) || "agent";
6407
- const to = str2(payload.recipient);
6408
- return { events: [{ type: "agent.message", parts: [{ type: "text", index: 0, text: `[${from}${to ? ` \u2192 ${to}` : ""}]
6409
- ${text2}` }] }], spec: {} };
6410
- }
6411
- if (kind === "reasoning") {
6412
- const text2 = reasoningText(payload);
6413
- if (!text2.trim()) return EMPTY;
6414
- return {
6415
- events: [
6416
- { type: "agent.reasoning", part: { type: "reasoning", index: 0, text: text2, redacted: false } }
6417
- ],
6418
- spec: {}
6419
- };
6420
- }
6421
- if (kind === "function_call" || kind === "local_shell_call" || kind === "custom_tool_call") {
6422
- const id2 = callOrOwnId(payload);
6423
- if (!id2) return EMPTY;
6424
- return {
6425
- events: [
6426
- {
6427
- type: "agent.tool_use",
6428
- part: {
6429
- type: "tool_call",
6430
- index: 0,
6431
- call_id: id2,
6432
- tool_name: toolName(payload),
6433
- args: callArgs(payload)
6434
- }
6435
- }
6436
- ],
6437
- spec: {}
6438
- };
6439
- }
6440
- if (kind === "function_call_output" || kind === "custom_tool_call_output") {
6441
- const id2 = callIdOf(payload);
6442
- if (!id2) return {
6443
- events: [{ type: "agent.message", parts: [{
6444
- type: "text",
6445
- index: 0,
6446
- text: `[Imported tool output: ${str2(payload.name) || "unknown tool"}; source has no call ID]
6447
- ${typeof payload.output === "string" ? payload.output : JSON.stringify(payload.output ?? "")}`
6448
- }] }],
6449
- spec: {},
6450
- unattachedResult: true
6451
- };
6452
- const output2 = payload.output;
6453
- const inner = record(output2);
6454
- const text2 = typeof output2 === "string" ? output2 : inner && typeof inner.output === "string" ? inner.output : JSON.stringify(output2 ?? "");
6455
- const failed = inner && inner.success === false || record(inner?.metadata)?.exit_code !== void 0 && record(inner?.metadata)?.exit_code !== 0;
6456
- return {
6457
- events: [
6458
- {
6459
- type: "agent.tool_result",
6460
- part: {
6461
- type: "tool_result",
6462
- index: 0,
6463
- call_id: id2,
6464
- tool_name: "",
6465
- status: failed ? "error" : "ok",
6466
- result: { output: text2 }
6467
- }
6468
- }
6469
- ],
6470
- spec: {}
6471
- };
6472
- }
6473
- if (kind === "turn_aborted") {
6474
- return {
6475
- events: [
6476
- {
6477
- type: "agent.status",
6478
- part: { type: "status", index: 0, level: "idle", text: "Turn interrupted" }
6479
- }
6480
- ],
6481
- spec: {}
6482
- };
6483
- }
6484
- if (type === "response_item" && kind) {
6485
- const text2 = JSON.stringify(line2);
6486
- const bytes = new TextEncoder().encode(text2);
6487
- let binary = "";
6488
- for (const byte of bytes) binary += String.fromCharCode(byte);
6489
- return {
6490
- events: [{ type: "agent.message", parts: [
6491
- { type: "text", index: 0, text: `Source record: ${kind} (this reader does not render it)` },
6492
- { type: "file", index: 1, name: "source-record.json", media_type: "application/json", data: btoa(binary), size_bytes: bytes.length }
6493
- ] }],
6494
- spec: {}
6495
- };
6496
- }
6497
- return EMPTY;
6498
- }
6499
-
6500
- // ../../packages/spec/src/native/index.ts
6501
- function parseNative(engine, records) {
6502
- const parse = { events: [], notes: [], spec: {}, unattachedResults: 0 };
6503
- const absorb = (spec) => {
6504
- for (const [key, value] of Object.entries(spec ?? {})) {
6505
- if (value !== void 0) parse.spec[key] = value;
6506
- }
6507
- };
6508
- for (const record3 of records) {
6509
- if (engine === "codex") {
6510
- const decoded2 = decodeCodexLine(record3);
6511
- parse.events.push(...decoded2.events);
6512
- if (decoded2.unattachedResult) parse.unattachedResults += 1;
6513
- absorb(decoded2.spec);
6514
- } else {
6515
- const decoded2 = decodeLine(record3);
6516
- parse.events.push(...decoded2.events);
6517
- parse.notes.push(...decoded2.notes);
6518
- absorb(decoded2.spec);
6519
- }
6520
- }
6521
- return parse;
6522
- }
6523
-
6524
- // ../../packages/conversation/src/platform-text.ts
6525
- var INPUT_SCOPE = /\n\n<agentsky-input-scope>[^\n]*<\/agentsky-input-scope>(?=$|\n\n<attachments>\n)/;
6526
- var SYSTEM_SECTION = /^<system-reminder>\n([\s\S]*?)\n<\/system-reminder>(?:\n\n|$)/;
6527
- var APP_CONTEXT = /\s*<app_context>[\s\S]*?(?:<\/app_context>|$)/g;
6528
- var HAS_APP_CONTEXT = /<app_context>/;
6529
- var HARNESS_TURN = /^\s*(?:<(task-notification|local-command-caveat|local-command-stdout|local-command-stderr|command-name|command-message|command-args)>[\s\S]*?<\/\1>\s*)+$/;
6530
- var RECOVERY_NOTICE_CLOSING = "Preserve completed work; do not repeat completed actions.";
6531
- var RECOVERY_NOTICE_OPENING = /^(?:The subscription usage limit that stopped the previous request has reset\.|.{0,240}?Continue the interrupted task from its current state\.)/s;
6532
- var EARLIER = /<earlier_conversation>\n([\s\S]*?)\n?<\/earlier_conversation>/;
6533
- function earlierTurns(system) {
6534
- const block = EARLIER.exec(system)?.[1];
6535
- if (!block) return [];
6536
- const turns = [];
6537
- for (const line2 of block.split("\n")) {
6538
- try {
6539
- const entry = JSON.parse(line2);
6540
- if (typeof entry.text !== "string" || !entry.text.trim()) continue;
6541
- turns.push({ role: entry.from === "Agent" ? "agent" : "user", text: entry.text, at: typeof entry.at === "string" ? entry.at : "" });
6542
- } catch {
6543
- continue;
6544
- }
6545
- }
6546
- return turns;
6547
- }
6548
- function isRecoveryNotice(text2) {
6549
- const trimmed = text2.trim();
6550
- return trimmed.endsWith(RECOVERY_NOTICE_CLOSING) && RECOVERY_NOTICE_OPENING.test(trimmed);
6551
- }
6552
- function personText(raw) {
6553
- let text2 = raw.replace(INPUT_SCOPE, "");
6554
- const earlier = [];
6555
- for (let section = SYSTEM_SECTION.exec(text2); section; section = SYSTEM_SECTION.exec(text2)) {
6556
- earlier.push(...earlierTurns(section[1] ?? ""));
6557
- text2 = text2.slice(section[0].length);
6558
- }
6559
- text2 = text2.replace(INPUT_SCOPE, "");
6560
- if (HAS_APP_CONTEXT.test(text2)) text2 = text2.replace(APP_CONTEXT, "").trim();
6561
- if (!text2.trim() || HARNESS_TURN.test(text2) || isRecoveryNotice(text2)) text2 = "";
6562
- return { text: text2, earlier };
6563
- }
6564
-
6565
- // ../../packages/conversation/src/read.ts
6566
- var THINKING_BLOCKS = /* @__PURE__ */ new Set(["thinking", "redacted_thinking"]);
6567
- var PRESERVED_RECORDS = /* @__PURE__ */ new Set(["source-record.json", "source-attachment.json"]);
6568
- function record2(value) {
6569
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
6570
- }
6571
- function str3(value) {
6572
- return typeof value === "string" ? value : "";
6573
- }
6574
- function jsonLines(text2) {
6575
- const lines2 = [];
6576
- for (const line2 of text2.split("\n")) {
6577
- if (!line2.trim()) continue;
6578
- try {
6579
- const parsed = record2(JSON.parse(line2));
6580
- if (parsed) lines2.push(parsed);
6581
- } catch {
6582
- continue;
6583
- }
6584
- }
6585
- return lines2;
6586
- }
6587
- function reasoningOf(block, index) {
6588
- return block.type === "thinking" ? { type: "reasoning", index, text: str3(block.thinking), redacted: false } : { type: "reasoning", index, text: "", redacted: true };
6589
- }
6590
- function withoutThinking(line2) {
6591
- const message2 = record2(line2.message);
6592
- if (line2.type !== "assistant" || !message2 || !Array.isArray(message2.content)) return { line: line2, reasoning: [] };
6593
- const reasoning = [];
6594
- const content = message2.content.filter((raw, index) => {
6595
- const block = record2(raw);
6596
- if (!block || !THINKING_BLOCKS.has(str3(block.type))) return true;
6597
- reasoning.push(reasoningOf(block, index));
6598
- return false;
6599
- });
6600
- return { line: { ...line2, message: { ...message2, content } }, reasoning };
6601
- }
6602
- var Fold = class {
6603
- messages = [];
6604
- calls = /* @__PURE__ */ new Map();
6605
- engine;
6606
- constructor(engine) {
6607
- this.engine = engine;
6608
- }
6609
- open(role, at) {
6610
- const message2 = { id: `m${this.messages.length}`, role, created_at: at, parts: [], metadata: { engine: this.engine } };
6611
- this.messages.push(message2);
6612
- return message2;
6613
- }
6614
- step(at) {
6615
- const last = this.messages.at(-1);
6616
- if (last && last.role === "agent" && !last.parts.some((part) => part.type === "tool_result")) return last;
6617
- return this.open("agent", at);
6618
- }
6619
- add(message2, part) {
6620
- message2.parts.push({ ...part, index: message2.parts.length });
6621
- }
6622
- reasoning(parts, at) {
6623
- if (!parts.length) return;
6624
- const message2 = this.step(at);
6625
- for (const part of parts) this.add(message2, part);
6626
- }
6627
- event(event, at) {
6628
- switch (event.type) {
6629
- case "user.message": {
6630
- const parts = [];
6631
- for (const part of event.parts) {
6632
- if (part.type === "file" && PRESERVED_RECORDS.has(part.name)) continue;
6633
- if (part.type !== "text") {
6634
- parts.push(part);
6635
- continue;
6636
- }
6637
- const { text: text2, earlier } = personText(part.text);
6638
- if (!this.messages.length) for (const turn of earlier) this.add(this.open(turn.role, turn.at || at), { type: "text", index: 0, text: turn.text });
6639
- if (text2) parts.push({ ...part, text: text2 });
6640
- }
6641
- if (!parts.length) return;
6642
- const message2 = this.open("user", at);
6643
- for (const part of parts) this.add(message2, part);
6644
- return;
6645
- }
6646
- case "agent.message": {
6647
- if (event.parts.some((part) => part.type === "file" && PRESERVED_RECORDS.has(part.name))) return;
6648
- const message2 = this.step(at);
6649
- for (const part of event.parts) this.add(message2, part);
6650
- return;
6651
- }
6652
- case "agent.reasoning":
6653
- this.add(this.step(at), event.part);
6654
- return;
6655
- case "agent.tool_use": {
6656
- const message2 = this.step(at);
6657
- this.add(message2, event.part);
6658
- this.calls.set(event.part.call_id, { message: message2, call: message2.parts.at(-1) });
6659
- return;
6660
- }
6661
- case "agent.tool_result": {
6662
- const owner = this.calls.get(event.part.call_id);
6663
- if (!owner) return;
6664
- this.add(owner.message, { ...event.part, tool_name: owner.call.tool_name });
6665
- return;
6666
- }
6667
- default:
6668
- return;
6669
- }
6670
- }
6671
- };
6672
- function claudeCode(lines2) {
6673
- const fold = new Fold("claude_code");
6674
- let nativeId = null;
6675
- let cwd = null;
6676
- let model = null;
6677
- for (const raw of lines2) {
6678
- if (raw.isSidechain === true) continue;
6679
- nativeId ??= str3(raw.sessionId) || null;
6680
- cwd ??= str3(raw.cwd) || null;
6681
- const at = str3(raw.timestamp);
6682
- const { line: line2, reasoning } = withoutThinking(raw);
6683
- const parse = parseNative("claude_code", [line2]);
6684
- if (parse.spec.llm && parse.spec.llm !== "<synthetic>") model = parse.spec.llm;
6685
- fold.reasoning(reasoning, at);
6686
- for (const event of parse.events) fold.event(event, at);
6687
- }
6688
- return { engine: "claude_code", nativeId, cwd, model, messages: fold.messages };
6689
- }
6690
- function codex(lines2) {
6691
- const fold = new Fold("codex");
6692
- let nativeId = null;
6693
- let cwd = null;
6694
- let model = null;
6695
- let rollout = null;
6696
- for (const line2 of lines2) {
6697
- const meta = line2.type === "session_meta" ? record2(line2.payload) : null;
6698
- if (meta) {
6699
- rollout ??= str3(meta.id) || null;
6700
- if (str3(meta.id) !== rollout) continue;
6701
- nativeId ??= rollout;
6702
- cwd ??= str3(meta.cwd) || null;
6703
- continue;
6704
- }
6705
- if (record2(line2.payload)?.author && record2(line2.payload)?.author !== "/root") continue;
6706
- const at = str3(line2.timestamp);
6707
- const parse = parseNative("codex", [line2]);
6708
- if (parse.spec.llm) model = parse.spec.llm;
6709
- const item = record2(line2.payload);
6710
- for (const event of parse.events) {
6711
- if (event.type === "agent.tool_use" && item?.type === "custom_tool_call" && typeof item.input === "string") {
6712
- fold.event({ ...event, part: { ...event.part, args: { input: item.input } } }, at);
6713
- } else fold.event(event, at);
6714
- }
6715
- }
6716
- return { engine: "codex", nativeId, cwd, model, messages: fold.messages };
6717
- }
6718
- function readConversation(engine, text2) {
6719
- const lines2 = jsonLines(text2);
6720
- return engine === "codex" ? codex(lines2) : claudeCode(lines2);
6721
- }
6722
-
6723
- // ../../packages/conversation/src/write.ts
6724
- import { randomBytes as randomBytes2, randomUUID as randomUUID4 } from "crypto";
6725
-
6726
- // ../../packages/conversation/src/conversation.ts
6727
- var ENGINE_LABEL = { claude_code: "Claude Code", codex: "Codex" };
6728
- var OTHER_LABELS = { hermes: "Hermes", openclaw: "OpenClaw", pi: "Pi", cursor: "Cursor", grok: "Grok", gemini: "Gemini" };
6729
- function engineLabel(engine) {
6730
- return ENGINE_LABEL[engine] ?? OTHER_LABELS[engine] ?? engine;
6731
- }
6732
- function isEngine(value) {
6733
- return value === "claude_code" || value === "codex";
6734
- }
6735
- function messageText2(message2) {
6736
- return message2.parts.filter((part) => part.type === "text").map((part) => part.text).join("\n");
6737
- }
6738
- function resultText(part) {
6739
- const output2 = part.result.output;
6740
- if (typeof output2 === "string") return output2;
6741
- return output2 === void 0 ? JSON.stringify(part.result) : JSON.stringify(output2);
6742
- }
6743
-
6744
- // ../../packages/conversation/src/fit.ts
6745
- var CONTEXT_BUDGET_CHARS = { claude_code: 48e4, codex: 64e4 };
6746
- var PORTABLE_BUDGET_CHARS = 2e5;
6747
- var MAX_TOOL_OUTPUT_CHARS = 6e4;
6748
- var IMAGE_CHARS = 6e3;
6749
- var SUMMARY_SHARE = 0.15;
6750
- var LINE_CHARS = 400;
6751
- function size(message2) {
6752
- let total = 0;
6753
- for (const part of message2.parts) {
6754
- if (part.type === "text") total += part.text.length;
6755
- else if (part.type === "tool_call") total += JSON.stringify(part.args).length + part.tool_name.length;
6756
- else if (part.type === "tool_result") total += Math.min(resultText(part).length, MAX_TOOL_OUTPUT_CHARS);
6757
- else if (part.type === "image" || part.type === "file") total += IMAGE_CHARS;
6758
- }
6759
- return total;
6760
- }
6761
- function clip(text2, max) {
6762
- const flat = text2.replace(/\s+/g, " ").trim();
6763
- return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
6764
- }
6765
- function fromBothEnds(entries, maxChars) {
6766
- const order = entries.map((_, index) => index % 2 ? entries.length - 1 - (index >> 1) : index >> 1);
6767
- const kept = /* @__PURE__ */ new Set();
6768
- let length = 0;
6769
- for (const index of order) {
6770
- if (length + entries[index].length + 1 > maxChars) break;
6771
- kept.add(index);
6772
- length += entries[index].length + 1;
6773
- }
6774
- const out = [];
6775
- entries.forEach((entry, index) => {
6776
- if (kept.has(index)) out.push(entry);
6777
- else if (kept.has(index - 1) || index === 0 && !kept.has(0)) out.push(`(${entries.length - kept.size} entries left out here)`);
6778
- });
6779
- return out;
6780
- }
6781
- var listAskedAndAnswered = (older, { maxChars }) => {
6782
- const tools = /* @__PURE__ */ new Map();
6783
- const all = [];
6784
- const asked = [];
6785
- for (const message2 of older) {
6786
- for (const part of message2.parts) if (part.type === "tool_call") tools.set(part.tool_name, (tools.get(part.tool_name) ?? 0) + 1);
6787
- const text2 = messageText2(message2);
6788
- if (!text2.trim()) continue;
6789
- const entry = `${message2.role === "user" ? "Asked" : "Answered"}: ${clip(text2, LINE_CHARS)}`;
6790
- all.push(entry);
6791
- if (message2.role === "user") asked.push(entry);
6792
- }
6793
- const used = [...tools].map(([name, count]) => `${name} \xD7${count}`).join(", ");
6794
- const tail = used ? `
6795
- Tools used in that part: ${used}.` : "";
6796
- const room = maxChars - tail.length;
6797
- const fits = (entries) => entries.reduce((sum, entry) => sum + entry.length + 1, 0) <= room;
6798
- const body = fits(all) ? all : fits(asked) ? asked : fromBothEnds(asked, room - 40);
6799
- return body.join("\n") + tail;
6800
- };
6801
- function startsTurn(message2) {
6802
- return message2.role === "user" && message2.parts.some((part) => part.type === "text" || part.type === "image");
6803
- }
6804
- function fitConversation(conversation, to, opts = {}) {
6805
- const budget = opts.budgetChars ?? (to ? CONTEXT_BUDGET_CHARS[to] : PORTABLE_BUDGET_CHARS);
6806
- const sizes = conversation.messages.map(size);
6807
- const total = sizes.reduce((sum, value) => sum + value, 0);
6808
- if (total <= budget) return { messages: conversation.messages, summarised: 0 };
6809
- const room = budget * (1 - SUMMARY_SHARE);
6810
- let start = conversation.messages.length;
6811
- let kept = 0;
6812
- for (let index = conversation.messages.length - 1; index >= 0; index -= 1) {
6813
- if (kept + sizes[index] > room) break;
6814
- kept += sizes[index];
6815
- start = index;
6816
- }
6817
- while (start < conversation.messages.length && !startsTurn(conversation.messages[start])) start += 1;
6818
- if (start >= conversation.messages.length) {
6819
- start = conversation.messages.length - 1;
6820
- while (start > 0 && !startsTurn(conversation.messages[start])) start -= 1;
6821
- }
6822
- const older = conversation.messages.slice(0, start);
6823
- const maxChars = Math.floor(budget * SUMMARY_SHARE);
6824
- const summary = (opts.summarize ?? listAskedAndAnswered)(older, { from: conversation.engine, to, maxChars }).slice(0, maxChars);
6825
- const first = older[0]?.created_at ?? "";
6826
- const note = {
6827
- id: "summary",
6828
- role: "user",
6829
- created_at: first,
6830
- parts: [{ type: "text", index: 0, text: `[This conversation was continued from ${engineLabel(conversation.engine)}. Its oldest ${older.length} messages were too long to carry and are summarised below; everything after this note is the original conversation, word for word.]
6831
-
6832
- ${summary}` }],
6833
- metadata: { summary_of: older.length }
6834
- };
6835
- return { messages: [note, ...conversation.messages.slice(start)], summarised: older.length };
6836
- }
6837
-
6838
- // ../../packages/conversation/src/tools.ts
6839
- var CLAUDE_CODE_TOOLS = /* @__PURE__ */ new Set([
6840
- "Bash",
6841
- "Read",
6842
- "Write",
6843
- "Edit",
6844
- "MultiEdit",
6845
- "Glob",
6846
- "Grep",
6847
- "LS",
6848
- "WebFetch",
6849
- "WebSearch",
6850
- "Task",
6851
- "Agent",
6852
- "TodoWrite",
6853
- "NotebookEdit",
6854
- "NotebookRead",
6855
- "BashOutput",
6856
- "KillShell",
6857
- "ExitPlanMode",
6858
- "Skill",
6859
- "SlashCommand"
6860
- ]);
6861
- var CODEX_FUNCTIONS = /* @__PURE__ */ new Set(["shell", "shell_command", "exec_command", "write_stdin", "update_plan", "view_image", "web_search"]);
6862
- function str4(value) {
6863
- return typeof value === "string" ? value : "";
6864
- }
6865
- function quote(value) {
6866
- return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
6867
- }
6868
- function absolute(path2, cwd) {
6869
- if (path2.startsWith("/") || !cwd) return path2;
6870
- return `${cwd.replace(/\/+$/, "")}/${path2.replace(/^\.\//, "")}`;
6871
- }
6872
- function relativeTo(path2, cwd) {
6873
- if (!cwd) return path2;
6874
- const root2 = `${cwd.replace(/\/+$/, "")}/`;
6875
- return path2.startsWith(root2) ? path2.slice(root2.length) : path2;
6876
- }
6877
- function lines(text2) {
6878
- const split = text2.split("\n");
6879
- if (split.at(-1) === "") split.pop();
6880
- return split;
6881
- }
6882
- function codexCommand(call) {
6883
- const args = call.args;
6884
- const workdir = str4(args.workdir) || str4(args.working_directory);
6885
- if (call.tool_name === "exec_command") return str4(args.cmd) ? { command: str4(args.cmd), workdir } : null;
6886
- if (call.tool_name === "shell_command") return str4(args.command) ? { command: str4(args.command), workdir } : null;
6887
- if (call.tool_name !== "shell") return null;
6888
- const argv = Array.isArray(args.command) ? args.command.filter((part) => typeof part === "string") : [];
6889
- if (!argv.length) return str4(args.command) ? { command: str4(args.command), workdir } : null;
6890
- if (argv.length === 3 && /(^|\/)(ba|z)?sh$/.test(argv[0]) && (argv[1] === "-lc" || argv[1] === "-c")) return { command: argv[2], workdir };
6891
- if (argv[0] === "apply_patch") return null;
6892
- return { command: argv.map(quote).join(" "), workdir };
6893
- }
6894
- function codexPatch(call) {
6895
- if (call.tool_name === "apply_patch") return str4(call.args.input) || str4(call.args.patch) || null;
6896
- const argv = Array.isArray(call.args.command) ? call.args.command : [];
6897
- return call.tool_name === "shell" && argv[0] === "apply_patch" && typeof argv[1] === "string" ? argv[1] : null;
6898
- }
6899
- function parsePatch(patch) {
6900
- const all = lines(patch.replace(/\r\n/g, "\n"));
6901
- if (all[0]?.trim() !== "*** Begin Patch" || all.at(-1)?.trim() !== "*** End Patch") return null;
6902
- const files2 = [];
6903
- for (const line2 of all.slice(1, -1)) {
6904
- const header2 = /^\*\*\* (Add|Update|Delete) File: (.+)$/.exec(line2);
6905
- if (header2) {
6906
- files2.push({ action: header2[1].toLowerCase(), path: header2[2].trim(), moveTo: null, body: [] });
6907
- continue;
6908
- }
6909
- const current = files2.at(-1);
6910
- if (!current) return null;
6911
- const move = /^\*\*\* Move to: (.+)$/.exec(line2);
6912
- if (move) current.moveTo = move[1].trim();
6913
- else current.body.push(line2);
6914
- }
6915
- return files2;
6916
- }
6917
- function patchToClaudeCode(patch, cwd) {
6918
- const files2 = parsePatch(patch);
6919
- if (!files2 || files2.length !== 1) return null;
6920
- const [file] = files2;
6921
- if (file.moveTo) return null;
6922
- if (file.action === "add") {
6923
- if (file.body.some((line2) => !line2.startsWith("+"))) return null;
6924
- return { name: "Write", input: { file_path: absolute(file.path, cwd), content: file.body.map((line2) => `${line2.slice(1)}
6925
- `).join("") } };
6926
- }
6927
- if (file.action !== "update") return null;
6928
- const body = file.body.filter((line2) => line2 !== "*** End of File");
6929
- if (body.filter((line2) => line2.startsWith("@@")).length > 1) return null;
6930
- const old = [];
6931
- const next = [];
6932
- for (const line2 of body.filter((line3) => !line3.startsWith("@@"))) {
6933
- if (line2.startsWith("-")) old.push(line2.slice(1));
6934
- else if (line2.startsWith("+")) next.push(line2.slice(1));
6935
- else if (line2.startsWith(" ") || line2 === "") {
6936
- old.push(line2.slice(1));
6937
- next.push(line2.slice(1));
6938
- } else return null;
6939
- }
6940
- if (!old.length) return null;
6941
- return { name: "Edit", input: { file_path: absolute(file.path, cwd), old_string: old.join("\n"), new_string: next.join("\n") } };
6942
- }
6943
- function toClaudeCode(call, cwd) {
6944
- if (CLAUDE_CODE_TOOLS.has(call.tool_name)) return { name: call.tool_name, input: call.args };
6945
- const patch = codexPatch(call);
6946
- if (patch) return patchToClaudeCode(patch, cwd);
6947
- const shell = codexCommand(call);
6948
- if (!shell) return null;
6949
- const inPlace = !shell.workdir || shell.workdir === cwd;
6950
- return { name: "Bash", input: { command: inPlace ? shell.command : `cd ${quote(shell.workdir)} && ${shell.command}` } };
6951
- }
6952
- function shellCall(command, cwd) {
6953
- return { kind: "function", name: "shell", arguments: { command: ["bash", "-lc", command], ...cwd ? { workdir: cwd } : {} } };
6954
- }
6955
- function patchCall(body) {
6956
- return { kind: "custom", name: "apply_patch", input: ["*** Begin Patch", ...body, "*** End Patch"].join("\n") };
6957
- }
6958
- function toCodex(call, cwd) {
6959
- const args = call.args;
6960
- if (call.tool_name === "apply_patch") return str4(args.input) ? { kind: "custom", name: "apply_patch", input: str4(args.input) } : null;
6961
- if (CODEX_FUNCTIONS.has(call.tool_name)) return { kind: "function", name: call.tool_name, arguments: args };
6962
- switch (call.tool_name) {
6963
- case "Bash":
6964
- return str4(args.command) ? shellCall(str4(args.command), cwd) : null;
6965
- case "Read": {
6966
- const path2 = str4(args.file_path);
6967
- if (!path2) return null;
6968
- const offset = typeof args.offset === "number" ? args.offset : null;
6969
- const limit = typeof args.limit === "number" ? args.limit : null;
6970
- if (offset === null && limit === null) return shellCall(`cat -n ${quote(path2)}`, cwd);
6971
- const first = offset ?? 1;
6972
- return shellCall(`cat -n ${quote(path2)} | sed -n '${first},${limit === null ? "$" : first + limit - 1}p'`, cwd);
6973
- }
6974
- case "Write": {
6975
- const path2 = str4(args.file_path);
6976
- if (!path2 || typeof args.content !== "string") return null;
6977
- return patchCall([`*** Add File: ${relativeTo(path2, cwd)}`, ...lines(args.content).map((line2) => `+${line2}`)]);
6978
- }
6979
- case "Edit": {
6980
- const path2 = str4(args.file_path);
6981
- if (!path2 || typeof args.old_string !== "string" || typeof args.new_string !== "string" || args.replace_all === true) return null;
6982
- return patchCall([`*** Update File: ${relativeTo(path2, cwd)}`, "@@", ...lines(args.old_string).map((line2) => `-${line2}`), ...lines(args.new_string).map((line2) => `+${line2}`)]);
6983
- }
6984
- default:
6985
- return null;
6986
- }
6987
- }
6988
-
6989
- // ../../packages/conversation/src/write.ts
6990
- function cut(text2) {
6991
- if (text2.length <= MAX_TOOL_OUTPUT_CHARS) return text2;
6992
- const half = Math.floor(MAX_TOOL_OUTPUT_CHARS / 2);
6993
- return `${text2.slice(0, half)}
6994
- [\u2026 ${text2.length - 2 * half} characters left out \u2026]
6995
- ${text2.slice(-half)}`;
6996
- }
6997
- function callAsText(from, call, result) {
6998
- const outcome = result ? `${result.status === "error" ? "It failed" : "It returned"}:
6999
- ${cut(resultText(result))}` : "No result was recorded.";
7000
- return `[In ${engineLabel(from)} I called ${call.tool_name} with ${JSON.stringify(call.args)}. ${outcome}]`;
7001
- }
7002
- function decoded(part) {
7003
- if (!part.data || !/^text\/|json/.test(part.media_type)) return `[Attached file: ${part.name}]`;
7004
- return `[Attached file: ${part.name}]
7005
- ${Buffer.from(part.data, "base64").toString("utf8")}`;
7006
- }
7007
- function imageData(part) {
7008
- if (part.data) return { mediaType: part.media_type, data: part.data };
7009
- const match2 = /^data:([^;,]+);base64,(.*)$/s.exec(part.uri ?? "");
7010
- return match2 ? { mediaType: match2[1], data: match2[2] } : null;
7011
- }
7012
- function plan(conversation, to, opts, map) {
7013
- const { messages, summarised } = fitConversation(conversation, to, { budgetChars: opts.budgetChars, summarize: opts.summarize });
7014
- const report = { messages: { user: 0, agent: 0 }, toolCalls: { mapped: 0, asText: 0 }, reasoningLeftOut: 0, summarised };
7015
- const planned = messages.map((message2) => {
7016
- const answered = new Set(message2.parts.filter((part) => part.type === "tool_result").map((part) => part.call_id));
7017
- const mapped = /* @__PURE__ */ new Map();
7018
- for (const part of message2.parts) {
7019
- if (part.type === "reasoning") report.reasoningLeftOut += 1;
7020
- if (part.type !== "tool_call") continue;
7021
- if (answered.has(part.call_id) && map(part)) {
7022
- mapped.set(part.call_id, true);
7023
- report.toolCalls.mapped += 1;
7024
- } else report.toolCalls.asText += 1;
7025
- }
7026
- return { message: message2, mapped };
7027
- });
7028
- return { planned, report };
7029
- }
7030
- function resultsOf(message2) {
7031
- return new Map(message2.parts.filter((part) => part.type === "tool_result").map((part) => [part.call_id, part]));
7032
- }
7033
- function iso(at, fallback) {
7034
- const parsed = Date.parse(at);
7035
- return Number.isFinite(parsed) ? new Date(parsed).toISOString() : fallback.toISOString();
7036
- }
7037
- function claudeProjectFolder(cwd) {
7038
- return cwd.replace(/[^a-zA-Z0-9]/g, "-");
7039
- }
7040
- function writeClaudeCode(conversation, opts = {}) {
7041
- const cwd = opts.cwd ?? conversation.cwd ?? "/";
7042
- const now = opts.now ?? /* @__PURE__ */ new Date();
7043
- const nativeId = opts.nativeId ?? randomUUID4();
7044
- const calls = /* @__PURE__ */ new Map();
7045
- const { planned, report } = plan(conversation, "claude_code", opts, (call) => {
7046
- const native = toClaudeCode(call, cwd);
7047
- if (native) calls.set(call.call_id, native);
7048
- return native;
7049
- });
7050
- const lines2 = [];
7051
- let parent = null;
7052
- const push = (type, message2, at) => {
7053
- const uuid2 = randomUUID4();
7054
- lines2.push(JSON.stringify({
7055
- parentUuid: parent,
7056
- isSidechain: false,
7057
- userType: "external",
7058
- cwd,
7059
- sessionId: nativeId,
7060
- version: opts.version ?? "2.1.0",
7061
- type,
7062
- message: message2,
7063
- uuid: uuid2,
7064
- timestamp: iso(at, now)
7065
- }));
7066
- parent = uuid2;
7067
- };
7068
- for (const { message: message2, mapped } of planned) {
7069
- if (message2.role === "user" || message2.role === "system") {
7070
- const content2 = [];
7071
- for (const part of message2.parts) {
7072
- if (part.type === "text") content2.push({ type: "text", text: part.text });
7073
- else if (part.type === "image") {
7074
- const image = imageData(part);
7075
- content2.push(image ? { type: "image", source: { type: "base64", media_type: image.mediaType, data: image.data } } : { type: "text", text: "[image]" });
7076
- } else if (part.type === "file") content2.push({ type: "text", text: decoded(part) });
7077
- }
7078
- if (!content2.length) continue;
7079
- report.messages.user += 1;
7080
- const only = content2.length === 1 && content2[0].type === "text" ? content2[0].text : null;
7081
- push("user", { role: "user", content: only ?? content2 }, message2.created_at);
7082
- continue;
7083
- }
7084
- const results = resultsOf(message2);
7085
- const content = [];
7086
- const answers = [];
7087
- for (const part of message2.parts) {
7088
- if (part.type === "text") content.push({ type: "text", text: part.text });
7089
- else if (part.type === "image") content.push({ type: "text", text: "[image]" });
7090
- else if (part.type === "tool_call") {
7091
- const result = results.get(part.call_id);
7092
- const native = calls.get(part.call_id);
7093
- if (mapped.has(part.call_id) && native && result) {
7094
- content.push({ type: "tool_use", id: part.call_id, name: native.name, input: native.input });
7095
- answers.push({ type: "tool_result", tool_use_id: part.call_id, content: cut(resultText(result)), ...result.status === "error" ? { is_error: true } : {} });
7096
- } else content.push({ type: "text", text: callAsText(conversation.engine, part, result) });
7097
- }
7098
- }
7099
- if (!content.length) continue;
7100
- report.messages.agent += 1;
7101
- push("assistant", {
7102
- id: `msg_${randomBytes2(12).toString("hex")}`,
7103
- type: "message",
7104
- role: "assistant",
7105
- model: conversation.model ?? "unknown",
7106
- content,
7107
- stop_reason: answers.length ? "tool_use" : "end_turn",
7108
- stop_sequence: null,
7109
- usage: { input_tokens: 0, output_tokens: 0 }
7110
- }, message2.created_at);
7111
- if (answers.length) push("user", { role: "user", content: answers }, message2.created_at);
7112
- }
7113
- return {
7114
- engine: "claude_code",
7115
- nativeId,
7116
- cwd,
7117
- path: `projects/${claudeProjectFolder(cwd)}/${nativeId}.jsonl`,
7118
- content: lines2.map((line2) => `${line2}
7119
- `).join(""),
7120
- resume: `claude --resume ${nativeId}`,
7121
- report
7122
- };
7123
- }
7124
- function rolloutStamp(at) {
7125
- return at.toISOString().slice(0, 19).replace(/:/g, "-");
7126
- }
7127
- function writeCodex(conversation, opts = {}) {
7128
- const cwd = opts.cwd ?? conversation.cwd ?? "/";
7129
- const now = opts.now ?? /* @__PURE__ */ new Date();
7130
- const nativeId = opts.nativeId ?? randomUUID4();
7131
- const calls = /* @__PURE__ */ new Map();
7132
- const { planned, report } = plan(conversation, "codex", opts, (call) => {
7133
- const native = toCodex(call, cwd);
7134
- if (native) calls.set(call.call_id, native);
7135
- return native;
7136
- });
7137
- const lines2 = [];
7138
- const push = (type, payload, at) => lines2.push(JSON.stringify({ timestamp: iso(at, now), type, payload }));
7139
- push("session_meta", {
7140
- id: nativeId,
7141
- timestamp: now.toISOString(),
7142
- cwd,
7143
- originator: "codex_cli_rs",
7144
- cli_version: opts.version ?? "0.61.0",
7145
- instructions: null,
7146
- source: "cli",
7147
- model_provider: "openai"
7148
- }, now.toISOString());
7149
- for (const { message: message2, mapped } of planned) {
7150
- if (message2.role === "user" || message2.role === "system") {
7151
- const content = [];
7152
- for (const part of message2.parts) {
7153
- if (part.type === "text") content.push({ type: "input_text", text: part.text });
7154
- else if (part.type === "image") {
7155
- const image = imageData(part);
7156
- content.push(image ? { type: "input_image", image_url: `data:${image.mediaType};base64,${image.data}` } : { type: "input_text", text: "[image]" });
7157
- } else if (part.type === "file") content.push({ type: "input_text", text: decoded(part) });
7158
- }
7159
- if (!content.length) continue;
7160
- report.messages.user += 1;
7161
- push("response_item", { type: "message", role: "user", content }, message2.created_at);
7162
- const text2 = content.filter((block) => block.type === "input_text").map((block) => block.text).join("\n");
7163
- push("event_msg", { type: "user_message", message: text2, images: [] }, message2.created_at);
7164
- continue;
7165
- }
7166
- const results = resultsOf(message2);
7167
- let wrote = false;
7168
- let pending = "";
7169
- const say = () => {
7170
- if (!pending) return;
7171
- push("response_item", { type: "message", role: "assistant", content: [{ type: "output_text", text: pending }] }, message2.created_at);
7172
- push("event_msg", { type: "agent_message", message: pending }, message2.created_at);
7173
- pending = "";
7174
- wrote = true;
7175
- };
7176
- for (const part of message2.parts) {
7177
- if (part.type === "text") pending = pending ? `${pending}
7178
-
7179
- ${part.text}` : part.text;
7180
- else if (part.type === "image") pending = pending ? `${pending}
7181
-
7182
- [image]` : "[image]";
7183
- else if (part.type === "tool_call") {
7184
- const result = results.get(part.call_id);
7185
- const native = calls.get(part.call_id);
7186
- if (!(mapped.has(part.call_id) && native && result)) {
7187
- const text2 = callAsText(conversation.engine, part, result);
7188
- pending = pending ? `${pending}
7189
-
7190
- ${text2}` : text2;
7191
- continue;
7192
- }
7193
- say();
7194
- push("response_item", native.kind === "custom" ? { type: "custom_tool_call", status: "completed", call_id: part.call_id, name: native.name, input: native.input } : { type: "function_call", name: native.name, arguments: JSON.stringify(native.arguments), call_id: part.call_id }, message2.created_at);
7195
- wrote = true;
7196
- } else if (part.type === "tool_result" && mapped.has(part.call_id)) {
7197
- say();
7198
- const native = calls.get(part.call_id);
7199
- const output2 = cut(resultText(part));
7200
- push(
7201
- "response_item",
7202
- native.kind === "custom" ? { type: "custom_tool_call_output", call_id: part.call_id, output: output2 } : { type: "function_call_output", call_id: part.call_id, output: JSON.stringify({ output: output2, metadata: { exit_code: part.status === "error" ? 1 : 0, duration_seconds: 0 } }) },
7203
- message2.created_at
7204
- );
7205
- }
7206
- }
7207
- say();
7208
- if (wrote) report.messages.agent += 1;
7209
- }
7210
- const day = now.toISOString().slice(0, 10).split("-").join("/");
7211
- return {
7212
- engine: "codex",
7213
- nativeId,
7214
- cwd,
7215
- path: `sessions/${day}/rollout-${rolloutStamp(now)}-${nativeId}.jsonl`,
7216
- content: lines2.map((line2) => `${line2}
7217
- `).join(""),
7218
- resume: `codex resume ${nativeId}`,
7219
- report
7220
- };
7221
- }
7222
- function writeConversation(to, conversation, opts = {}) {
7223
- return to === "codex" ? writeCodex(conversation, opts) : writeClaudeCode(conversation, opts);
7224
- }
7225
-
7226
- // ../../packages/conversation/src/index.ts
7227
- function convertSession(from, text2, to, opts = {}) {
7228
- return writeConversation(to, readConversation(from, text2), opts);
7229
- }
7230
-
7231
- // src/session-workspace.ts
7232
5912
  var SINGLE_IMPORT_MAX = 25 * 1024 * 1024;
7233
5913
  var PART_SIZE = 8 * 1024 * 1024;
7234
5914
  var SKIPPED3 = /* @__PURE__ */ new Set([".git", "node_modules"]);
@@ -7241,8 +5921,8 @@ async function listFiles2(id2, path2, hidden) {
7241
5921
  return api("GET", `${workspacePath(id2)}/files${qs ? `?${qs}` : ""}`);
7242
5922
  }
7243
5923
  function entryLine(e) {
7244
- const size2 = e.type === "directory" ? "-" : String(e.size ?? 0);
7245
- return `${e.type === "directory" ? "d" : "-"} ${size2.padStart(10)} ${(e.mtime ?? "").slice(0, 16).replace("T", " ")} ${e.name}${e.type === "directory" ? "/" : ""}`;
5924
+ const size = e.type === "directory" ? "-" : String(e.size ?? 0);
5925
+ return `${e.type === "directory" ? "d" : "-"} ${size.padStart(10)} ${(e.mtime ?? "").slice(0, 16).replace("T", " ")} ${e.name}${e.type === "directory" ? "/" : ""}`;
7246
5926
  }
7247
5927
  async function readFile(id2, path2) {
7248
5928
  return (await apiBytes("GET", `${workspacePath(id2)}/files/content?path=${encodeURIComponent(path2)}`)).bytes;
@@ -7287,7 +5967,7 @@ function folderArchive(dir, files2) {
7287
5967
  }
7288
5968
  async function importFolder(id2, dir, opts = {}) {
7289
5969
  const root2 = resolve10(dir);
7290
- const name = opts.name ?? basename7(root2);
5970
+ const name = opts.name ?? basename6(root2);
7291
5971
  const archive = opts.archive ?? folderArchive(root2, folderFiles(root2));
7292
5972
  if (archive.length <= SINGLE_IMPORT_MAX) {
7293
5973
  const res = await apiBytes("POST", `${workspacePath(id2)}/import?name=${encodeURIComponent(name)}`, { bytes: archive, mediaType: "application/gzip" });
@@ -7310,17 +5990,17 @@ async function importFolder(id2, dir, opts = {}) {
7310
5990
  return { path: upload.path ?? name, files: upload.files ?? 0 };
7311
5991
  }
7312
5992
  function renderAccess(a) {
7313
- const lines2 = [
5993
+ const lines = [
7314
5994
  `${a.session_id}${a.title ? ` \u2014 ${a.title}` : ""}`,
7315
5995
  ` ${a.visibility === "private" ? "private to its owner" : `visible to ${a.workspace.name} (${a.workspace.slug})`} \xB7 you are its ${a.access}`,
7316
5996
  ` owner: ${a.owner.name ?? a.owner.email ?? "unknown"}`
7317
5997
  ];
7318
- if (a.viewers) lines2.push(a.viewers.length ? ` viewers: ${a.viewers.map((v) => v.notification === "not_sent" ? `${v.email} (email not sent; send them the link)` : v.email).join(", ")}` : " viewers: none");
5998
+ if (a.viewers) lines.push(a.viewers.length ? ` viewers: ${a.viewers.map((v) => v.notification === "not_sent" ? `${v.email} (email not sent; send them the link)` : v.email).join(", ")}` : " viewers: none");
7319
5999
  if (a.logins_shared?.enabled) {
7320
6000
  const sites = a.logins_shared.sites?.join(", ") ?? "every site except Google";
7321
- lines2.push(` owner's logins shared: ${sites}${a.logins_shared.suspended ? " (not used while anyone with the link can send messages)" : ""}`);
6001
+ lines.push(` owner's logins shared: ${sites}${a.logins_shared.suspended ? " (not used while anyone with the link can send messages)" : ""}`);
7322
6002
  }
7323
- return lines2;
6003
+ return lines;
7324
6004
  }
7325
6005
  function accessPatch(opts) {
7326
6006
  if (opts.private && opts.members) throw new ApiError(400, "invalid_request", "pass --private or --members, not both");
@@ -7373,11 +6053,11 @@ function zipEntries(archive) {
7373
6053
  let at = archive.readUInt32LE(end + 16);
7374
6054
  for (let index = archive.readUInt16LE(end + 10); index > 0; index -= 1) {
7375
6055
  const method = archive.readUInt16LE(at + 10);
7376
- const size2 = archive.readUInt32LE(at + 20);
6056
+ const size = archive.readUInt32LE(at + 20);
7377
6057
  const nameLength = archive.readUInt16LE(at + 28);
7378
6058
  const local = archive.readUInt32LE(at + 42);
7379
6059
  const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);
7380
- const packed = archive.subarray(start, start + size2);
6060
+ const packed = archive.subarray(start, start + size);
7381
6061
  if (method !== 0 && method !== 8) throw new ApiError(422, "checkpoint_invalid", "the downloaded conversation uses an unsupported compression");
7382
6062
  entries.set(archive.subarray(at + 46, at + 46 + nameLength).toString("utf8"), method === 8 ? inflateRawSync(packed) : Buffer.from(packed));
7383
6063
  at += 46 + nameLength + archive.readUInt16LE(at + 30) + archive.readUInt16LE(at + 32);
@@ -7484,7 +6164,7 @@ async function handBack(sessionId) {
7484
6164
  // src/render.ts
7485
6165
  var dim = (s) => `\x1B[2m${s}\x1B[0m`;
7486
6166
  var red = (s) => `\x1B[31m${s}\x1B[0m`;
7487
- function clip2(value, max = 120) {
6167
+ function clip(value, max = 120) {
7488
6168
  const text2 = typeof value === "string" ? value : JSON.stringify(value);
7489
6169
  return text2.length > max ? `${text2.slice(0, max)}\u2026` : text2;
7490
6170
  }
@@ -7525,10 +6205,10 @@ function renderOther(event, data) {
7525
6205
  const part = data.part;
7526
6206
  switch (event) {
7527
6207
  case "agent.reasoning":
7528
- console.log(dim(`\xB7 ${clip2(part?.text ?? "")}`));
6208
+ console.log(dim(`\xB7 ${clip(part?.text ?? "")}`));
7529
6209
  break;
7530
6210
  case "agent.tool_use":
7531
- console.log(dim(`\u2192 ${String(part?.tool_name ?? "tool")}(${clip2(part?.args ?? {}, 80)})`));
6211
+ console.log(dim(`\u2192 ${String(part?.tool_name ?? "tool")}(${clip(part?.args ?? {}, 80)})`));
7532
6212
  break;
7533
6213
  case "agent.tool_result":
7534
6214
  console.log(dim(`\u2190 ${String(part?.tool_name ?? "tool")} ${String(part?.status ?? "")}`));
@@ -7718,62 +6398,62 @@ function scrub(text2, names) {
7718
6398
  return out.length > TEXT_MAX ? `${out.slice(0, TEXT_MAX)}
7719
6399
  \u2026[cut]` : out;
7720
6400
  }
7721
- function textOf3(event) {
6401
+ function textOf2(event) {
7722
6402
  if (typeof event.text === "string" && event.text.trim()) return event.text;
7723
6403
  if (Array.isArray(event.content)) {
7724
6404
  return event.content.map((block) => block.type === "text" && typeof block.text === "string" ? block.text : "").filter(Boolean).join("\n");
7725
6405
  }
7726
6406
  return "";
7727
6407
  }
7728
- function firstAsk(record3) {
7729
- const root2 = record3.threads.find((thread2) => thread2.relation === "primary") ?? record3.threads[0];
6408
+ function firstAsk(record) {
6409
+ const root2 = record.threads.find((thread2) => thread2.relation === "primary") ?? record.threads[0];
7730
6410
  if (!root2) return null;
7731
- for (const event of record3.events[root2.id] ?? []) {
6411
+ for (const event of record.events[root2.id] ?? []) {
7732
6412
  if (event.type === "user.message") {
7733
- const text2 = textOf3(event).trim();
6413
+ const text2 = textOf2(event).trim();
7734
6414
  if (text2) return text2;
7735
6415
  }
7736
6416
  }
7737
6417
  return null;
7738
6418
  }
7739
- function decisionsOf(record3) {
6419
+ function decisionsOf(record) {
7740
6420
  const out = [];
7741
- for (const thread2 of record3.threads) {
7742
- for (const event of record3.events[thread2.id] ?? []) {
6421
+ for (const thread2 of record.threads) {
6422
+ for (const event of record.events[thread2.id] ?? []) {
7743
6423
  if (event.type === "human.decision" || event.type === "outcome.observed") out.push({ ...event, thread_id: thread2.id });
7744
6424
  }
7745
6425
  }
7746
6426
  return out.sort((a, b) => (a.at ?? "").localeCompare(b.at ?? ""));
7747
6427
  }
7748
- function adoptedSession(record3) {
7749
- const decisions = decisionsOf(record3).filter((event) => event.type === "human.decision");
6428
+ function adoptedSession(record) {
6429
+ const decisions = decisionsOf(record).filter((event) => event.type === "human.decision");
7750
6430
  for (const event of [...decisions].reverse()) {
7751
6431
  if (event.kind === "adopt") return event.target_session_id ?? event.thread_id;
7752
6432
  if (event.kind === "vote" && event.target_session_id) return event.target_session_id;
7753
6433
  }
7754
6434
  return null;
7755
6435
  }
7756
- function stepsOf(record3, names) {
7757
- const root2 = record3.threads.find((thread2) => thread2.relation === "primary") ?? record3.threads[0];
6436
+ function stepsOf(record, names) {
6437
+ const root2 = record.threads.find((thread2) => thread2.relation === "primary") ?? record.threads[0];
7758
6438
  if (!root2) return [];
7759
- const events2 = record3.events[root2.id] ?? [];
6439
+ const events2 = record.events[root2.id] ?? [];
7760
6440
  const steps = [];
7761
6441
  events2.forEach((event, index) => {
7762
6442
  if (event.type !== "human.decision" || event.kind !== "revise" && event.kind !== "rerun") return;
7763
- const next = events2.slice(index + 1).find((later) => later.type === "user.message" && textOf3(later).trim());
7764
- const words2 = next ? textOf3(next) : event.reason ?? "";
6443
+ const next = events2.slice(index + 1).find((later) => later.type === "user.message" && textOf2(later).trim());
6444
+ const words2 = next ? textOf2(next) : event.reason ?? "";
7765
6445
  if (!words2.trim()) return;
7766
6446
  steps.push({ at: event.at ?? "", instruction: scrub(words2, names) });
7767
6447
  });
7768
6448
  return steps;
7769
6449
  }
7770
- function rubricOf(record3, instruction, names) {
7771
- if (record3.goal && record3.goal.criteria.length) {
7772
- const verdicts = new Map((record3.goal.last_evaluation?.criteria ?? []).map((row) => [row.id, row.verdict]));
6450
+ function rubricOf(record, instruction, names) {
6451
+ if (record.goal && record.goal.criteria.length) {
6452
+ const verdicts = new Map((record.goal.last_evaluation?.criteria ?? []).map((row) => [row.id, row.verdict]));
7773
6453
  return {
7774
6454
  version: 1,
7775
6455
  source: "goal",
7776
- criteria: record3.goal.criteria.map((criterion) => ({
6456
+ criteria: record.goal.criteria.map((criterion) => ({
7777
6457
  id: criterion.id,
7778
6458
  text: scrub(criterion.text, names),
7779
6459
  must: true,
@@ -7868,17 +6548,17 @@ cd "$(dirname "$0")"
7868
6548
  mkdir -p /workspace/outputs
7869
6549
  if [ -d files ]; then cp -R files/. /workspace/outputs/; fi
7870
6550
  `;
7871
- function buildHarborTask(record3, opts) {
6551
+ function buildHarborTask(record, opts) {
7872
6552
  const names = opts.redactNames;
7873
6553
  const out = /* @__PURE__ */ new Map();
7874
- const ask3 = record3.goal?.objective ?? firstAsk(record3) ?? record3.title ?? "Complete the task described by the workspace.";
6554
+ const ask3 = record.goal?.objective ?? firstAsk(record) ?? record.title ?? "Complete the task described by the workspace.";
7875
6555
  const instruction = scrub(ask3, names);
7876
- const root2 = record3.threads.find((thread2) => thread2.relation === "primary") ?? record3.threads[0];
7877
- const harnesses = [...new Set(record3.threads.map((thread2) => thread2.agent.harness))];
7878
- const decisions = decisionsOf(record3);
7879
- const adopted = adoptedSession(record3);
7880
- const steps = stepsOf(record3, names);
7881
- const idHash = createHash9("sha256").update(record3.task_id).digest("hex").slice(0, 16);
6556
+ const root2 = record.threads.find((thread2) => thread2.relation === "primary") ?? record.threads[0];
6557
+ const harnesses = [...new Set(record.threads.map((thread2) => thread2.agent.harness))];
6558
+ const decisions = decisionsOf(record);
6559
+ const adopted = adoptedSession(record);
6560
+ const steps = stepsOf(record, names);
6561
+ const idHash = createHash9("sha256").update(record.task_id).digest("hex").slice(0, 16);
7882
6562
  out.set("instruction.md", `${instruction.trim()}
7883
6563
 
7884
6564
  Write your deliverables under /workspace/outputs.
@@ -7891,18 +6571,18 @@ Write your deliverables under /workspace/outputs.
7891
6571
  tier: opts.tier,
7892
6572
  source: "agentsky-session-record",
7893
6573
  source_task: idHash,
7894
- exported_at: record3.exported_at,
6574
+ exported_at: record.exported_at,
7895
6575
  harnesses,
7896
- has_goal: Boolean(record3.goal),
6576
+ has_goal: Boolean(record.goal),
7897
6577
  decisions: decisions.length,
7898
6578
  steps: steps.length,
7899
6579
  adopted_session: adopted ?? "",
7900
- did_the_job: record3.completion_answer?.did_the_job ?? "unknown"
6580
+ did_the_job: record.completion_answer?.did_the_job ?? "unknown"
7901
6581
  },
7902
6582
  verifier: { kind: "rubric_judge", rubric: "tests/rubric.json", reward: "/logs/verifier/reward.json" }
7903
6583
  })
7904
6584
  );
7905
- const env = record3.environment ?? root2?.environment ?? null;
6585
+ const env = record.environment ?? root2?.environment ?? null;
7906
6586
  if (env && typeof env.repo === "string" && typeof env.commit === "string") {
7907
6587
  out.set(
7908
6588
  "environment/Dockerfile",
@@ -7918,7 +6598,7 @@ RUN git clone ${env.repo} repo && cd repo && git checkout ${env.commit}
7918
6598
  "This task is a real execution, not a resettable environment: the record carries no repository and commit to rebuild from.\nAuthor environment/Dockerfile by hand from solution/files (the task's own files at export) before running it with Harbor, or keep it as trajectory data.\n"
7919
6599
  );
7920
6600
  }
7921
- const rubric = rubricOf(record3, instruction, names);
6601
+ const rubric = rubricOf(record, instruction, names);
7922
6602
  out.set("tests/rubric.json", `${JSON.stringify(rubric, null, 2)}
7923
6603
  `);
7924
6604
  out.set("tests/judge.py", JUDGE_PY);
@@ -7926,12 +6606,12 @@ RUN git clone ${env.repo} repo && cd repo && git checkout ${env.commit}
7926
6606
  out.set("solution/solve.sh", SOLVE_SH);
7927
6607
  out.set(
7928
6608
  "solution/deliverables.json",
7929
- `${JSON.stringify({ files: record3.files.map((file) => ({ path: file.path, bytes: file.size_bytes ?? null })), adopted_session: adopted }, null, 2)}
6609
+ `${JSON.stringify({ files: record.files.map((file) => ({ path: file.path, bytes: file.size_bytes ?? null })), adopted_session: adopted }, null, 2)}
7930
6610
  `
7931
6611
  );
7932
6612
  for (const [path2, bytes] of opts.fileBytes ?? []) out.set(`solution/files/${path2}`, bytes);
7933
6613
  const scrubbedEvents = {};
7934
- for (const [threadId, events2] of Object.entries(record3.events)) {
6614
+ for (const [threadId, events2] of Object.entries(record.events)) {
7935
6615
  scrubbedEvents[threadId] = events2.map((event) => ({
7936
6616
  ...event,
7937
6617
  ...typeof event.text === "string" ? { text: scrub(event.text, names) } : {},
@@ -7940,7 +6620,7 @@ RUN git clone ${env.repo} repo && cd repo && git checkout ${env.commit}
7940
6620
  ..."parts" in event ? { parts: void 0 } : {}
7941
6621
  }));
7942
6622
  }
7943
- out.set("rollout/record.json", `${JSON.stringify({ ...record3, title: record3.title ? scrub(record3.title, names) : null, events: scrubbedEvents, goal: record3.goal ? { ...record3.goal, objective: scrub(record3.goal.objective, names) } : null }, null, 2)}
6623
+ out.set("rollout/record.json", `${JSON.stringify({ ...record, title: record.title ? scrub(record.title, names) : null, events: scrubbedEvents, goal: record.goal ? { ...record.goal, objective: scrub(record.goal.objective, names) } : null }, null, 2)}
7944
6624
  `);
7945
6625
  out.set("rollout/decisions.json", `${JSON.stringify(decisions.map((event) => ({ ...event, reason: typeof event.reason === "string" ? scrub(event.reason, names) : event.reason })), null, 2)}
7946
6626
  `);
@@ -7984,16 +6664,16 @@ async function fetchTaskRecord(taskRef) {
7984
6664
  }
7985
6665
  var FILE_BYTES_MAX = 50 * 1024 * 1024;
7986
6666
  async function exportTaskHarbor(taskRef, outDir, opts) {
7987
- const record3 = await fetchTaskRecord(taskRef);
6667
+ const record = await fetchTaskRecord(taskRef);
7988
6668
  const fileBytes = /* @__PURE__ */ new Map();
7989
6669
  let total = 0;
7990
- for (const file of record3.files) {
6670
+ for (const file of record.files) {
7991
6671
  if (total + (file.size_bytes ?? 0) > FILE_BYTES_MAX) break;
7992
- const bytes = await readTaskFile(record3.task_id, file.path);
6672
+ const bytes = await readTaskFile(record.task_id, file.path);
7993
6673
  total += bytes.byteLength;
7994
6674
  fileBytes.set(file.path, bytes);
7995
6675
  }
7996
- const files2 = buildHarborTask(record3, { ...opts, fileBytes });
6676
+ const files2 = buildHarborTask(record, { ...opts, fileBytes });
7997
6677
  const written = [];
7998
6678
  for (const [path2, content] of files2) {
7999
6679
  const target2 = join17(outDir, path2);
@@ -8001,7 +6681,7 @@ async function exportTaskHarbor(taskRef, outDir, opts) {
8001
6681
  writeFileSync10(target2, content, typeof content === "string" ? { mode: path2.endsWith(".sh") || path2.endsWith(".py") ? 493 : 420 } : void 0);
8002
6682
  written.push(path2);
8003
6683
  }
8004
- return { written, record: record3 };
6684
+ return { written, record };
8005
6685
  }
8006
6686
  function parseRedactNames(values) {
8007
6687
  return (values ?? []).map((value) => {
@@ -8121,8 +6801,8 @@ function line(section, row) {
8121
6801
  return joined([row.name, row.kind, row.path]);
8122
6802
  case "changes": {
8123
6803
  const checks = row.checks;
8124
- const lines2 = row.additions == null && row.deletions == null ? "" : `+${text(row.additions ?? 0)} -${text(row.deletions ?? 0)}`;
8125
- return joined([row.title, row.repo, row.state, lines2, checks ? `${checks.passed} of ${checks.total} checks passed` : "", row.url]);
6804
+ const lines = row.additions == null && row.deletions == null ? "" : `+${text(row.additions ?? 0)} -${text(row.deletions ?? 0)}`;
6805
+ return joined([row.title, row.repo, row.state, lines, checks ? `${checks.passed} of ${checks.total} checks passed` : "", row.url]);
8126
6806
  }
8127
6807
  case "members_plugins":
8128
6808
  return joined([row.kind, row.name, row.needs_sign_in ? "needs sign-in" : row.online ? "online" : ""]);
@@ -8133,14 +6813,14 @@ function line(section, row) {
8133
6813
  }
8134
6814
  }
8135
6815
  function renderSessionOverview(overview) {
8136
- const lines2 = [overview.title ? `${overview.title} (${overview.session_id})` : overview.session_id];
8137
- if (overview.context_percent !== void 0) lines2.push(`context ${overview.context_percent}% full`);
6816
+ const lines = [overview.title ? `${overview.title} (${overview.session_id})` : overview.session_id];
6817
+ if (overview.context_percent !== void 0) lines.push(`context ${overview.context_percent}% full`);
8138
6818
  for (const section of overview.sections) {
8139
- lines2.push("", section.id === "spend" ? `${TITLES.spend} ${usd2(section.total_usd)}` : TITLES[section.id] ?? section.id);
8140
- for (const row of section.rows) lines2.push(` ${line(section.id, row)}`);
8141
- if (section.id === "runs" && section.finished) lines2.push(` ${section.finished} finished`);
6819
+ lines.push("", section.id === "spend" ? `${TITLES.spend} ${usd2(section.total_usd)}` : TITLES[section.id] ?? section.id);
6820
+ for (const row of section.rows) lines.push(` ${line(section.id, row)}`);
6821
+ if (section.id === "runs" && section.finished) lines.push(` ${section.finished} finished`);
8142
6822
  }
8143
- return lines2.join("\n");
6823
+ return lines.join("\n");
8144
6824
  }
8145
6825
 
8146
6826
  // src/task-email.ts
@@ -8335,15 +7015,15 @@ function renderBrowserProfileShare(share) {
8335
7015
  }
8336
7016
  function renderBrowserProfile(profile) {
8337
7017
  const title = profile.scope === "mine" ? "your browser" : profile.scope === "shared" ? `shared with you by ${profile.owner?.email ?? profile.owner?.name ?? profile.owner?.id ?? "someone"}` : "shared with this workspace";
8338
- const lines2 = [`${title} revision: ${profile.revision} sites: ${profile.sites.length}`];
8339
- for (const site2 of profile.sites) lines2.push(` ${renderBrowserProfileSite(site2)}`);
8340
- for (const share of profile.shares ?? []) lines2.push(` ${renderBrowserProfileShare(share)}`);
8341
- return lines2.join("\n");
7018
+ const lines = [`${title} revision: ${profile.revision} sites: ${profile.sites.length}`];
7019
+ for (const site2 of profile.sites) lines.push(` ${renderBrowserProfileSite(site2)}`);
7020
+ for (const share of profile.shares ?? []) lines.push(` ${renderBrowserProfileShare(share)}`);
7021
+ return lines.join("\n");
8342
7022
  }
8343
7023
 
8344
7024
  // src/portable-import.ts
8345
7025
  import { existsSync as existsSync13, readdirSync as readdirSync9, readFileSync as readFileSync21, statSync as statSync7 } from "fs";
8346
- import { basename as basename8, join as join18, resolve as resolve11 } from "path";
7026
+ import { basename as basename7, join as join18, resolve as resolve11 } from "path";
8347
7027
  import { parse as parseToml4 } from "smol-toml";
8348
7028
  var isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
8349
7029
  function readJson4(path2) {
@@ -8425,7 +7105,7 @@ function planImport(path2) {
8425
7105
  const target2 = resolve11(path2);
8426
7106
  if (!existsSync13(target2)) throw new Error(`Nothing at ${path2}`);
8427
7107
  if (statSync7(target2).isFile()) {
8428
- const name2 = basename8(target2).replace(/\.(json|toml)$/, "");
7108
+ const name2 = basename7(target2).replace(/\.(json|toml)$/, "");
8429
7109
  if (target2.endsWith(".toml")) return { name: name2, format: "codex-config", skills: [], ...codexConfigServers(readFileSync21(target2, "utf-8")) };
8430
7110
  const value = readJson4(target2);
8431
7111
  if (value === null) throw new Error(`${path2} is not JSON or TOML`);
@@ -8462,7 +7142,7 @@ function planImport(path2) {
8462
7142
  skipped.push(...read.skipped);
8463
7143
  }
8464
7144
  for (const part of ["commands", "agents", "hooks"]) if (existsSync13(at(part))) skipped.push({ part, reason: part === "hooks" ? "hooks run code and are not imported" : `${part} import with the plugin from GitHub (sky plugins add --source github:\u2026)` });
8465
- const name = isObject(manifest) && typeof manifest.name === "string" ? manifest.name : basename8(target2);
7145
+ const name = isObject(manifest) && typeof manifest.name === "string" ? manifest.name : basename7(target2);
8466
7146
  return { name, format, skills: skillDirs(target2), servers, skipped };
8467
7147
  }
8468
7148
 
@@ -8613,22 +7293,22 @@ function fieldNames(node, components, seen, out) {
8613
7293
  return;
8614
7294
  }
8615
7295
  if (typeof node !== "object" || node === null) return;
8616
- const record3 = node;
8617
- if (typeof record3.$ref === "string") {
8618
- if (seen.has(record3.$ref)) return;
8619
- seen.add(record3.$ref);
8620
- const target2 = record3.$ref.replace(/^#\/components\//, "").split("/").reduce((at, key) => at?.[key], components);
7296
+ const record = node;
7297
+ if (typeof record.$ref === "string") {
7298
+ if (seen.has(record.$ref)) return;
7299
+ seen.add(record.$ref);
7300
+ const target2 = record.$ref.replace(/^#\/components\//, "").split("/").reduce((at, key) => at?.[key], components);
8621
7301
  fieldNames(target2, components, seen, out);
8622
7302
  return;
8623
7303
  }
8624
- if (typeof record3.in === "string" && typeof record3.name === "string") out.add(record3.name);
8625
- if (typeof record3.properties === "object" && record3.properties !== null) {
8626
- for (const [name, schema] of Object.entries(record3.properties)) {
7304
+ if (typeof record.in === "string" && typeof record.name === "string") out.add(record.name);
7305
+ if (typeof record.properties === "object" && record.properties !== null) {
7306
+ for (const [name, schema] of Object.entries(record.properties)) {
8627
7307
  out.add(name);
8628
7308
  fieldNames(schema, components, seen, out);
8629
7309
  }
8630
7310
  }
8631
- for (const key of ["schema", "items", "allOf", "oneOf", "anyOf", "content", "application/json"]) fieldNames(record3[key], components, seen, out);
7311
+ for (const key of ["schema", "items", "allOf", "oneOf", "anyOf", "content", "application/json"]) fieldNames(record[key], components, seen, out);
8632
7312
  }
8633
7313
  function operationSearch(operations, components) {
8634
7314
  const entries = operations.map((op) => {
@@ -8974,6 +7654,15 @@ function renderActed(result) {
8974
7654
  return [result.acted, result.session_id, result.url].filter(Boolean).join(" ");
8975
7655
  }
8976
7656
 
7657
+ // src/asks.ts
7658
+ import { createHash as createHash11 } from "crypto";
7659
+
7660
+ // ../../packages/spec/src/ask-decision.ts
7661
+ import { createHash as createHash10 } from "crypto";
7662
+ var ASK_DECISION_HEADER = "x-agentsky-ask-decision";
7663
+ var PERSON_REQUIRED = "person_required";
7664
+ var ASK_DECISION_TTL_MS = 2 * 60 * 1e3;
7665
+
8977
7666
  // src/asks.ts
8978
7667
  async function listAsks(query) {
8979
7668
  const params = new URLSearchParams();
@@ -8984,17 +7673,67 @@ async function listAsks(query) {
8984
7673
  if (query.direction) params.set("direction", query.direction);
8985
7674
  return api("GET", `/asks${params.size ? `?${params}` : ""}`);
8986
7675
  }
8987
- async function answerAsk(id2, opts) {
8988
- return api("POST", `/asks/${encodeURIComponent(id2)}/answer`, {
7676
+ function answerFields(opts) {
7677
+ return {
8989
7678
  ...opts.option ? { option_id: opts.option } : {},
8990
7679
  ...opts.text ? { text: opts.text } : {},
8991
7680
  ...opts.engine ? { agent_type: opts.engine } : {},
8992
7681
  ...opts.model ? { llm: opts.model } : {}
8993
- });
7682
+ };
7683
+ }
7684
+ function askAnswerCode(id2, opts) {
7685
+ return createHash11("sha256").update(`${id2}
7686
+ ${JSON.stringify(answerFields(opts))}`).digest("hex").slice(0, 6).toUpperCase();
7687
+ }
7688
+ function refusalToAnswerAsPerson(env) {
7689
+ if (!env.stdinTTY || !env.stdoutTTY) return "sky asks answer needs you at an interactive terminal for an Ask only you may answer: it does not read a piped answer, so an agent cannot answer for you. Run it yourself, or answer it in AgentSky.";
7690
+ if (env.tokenFromEnv) return "SKY_API_TOKEN is set, so sky would answer with that key, not your own sign-in. Unset it and run sky asks answer again.";
7691
+ if (!env.signedIn) return "sky is not signed in on this computer: run `sky auth login`, then answer again.";
7692
+ return null;
7693
+ }
7694
+ function renderPersonAnswer(ask3, opts) {
7695
+ const answer = opts.text ?? (opts.option ? `option ${opts.option}` : "this answer");
7696
+ return [
7697
+ ask3 ? `${ask3.who.name}: ${ask3.need}` : "An Ask only you may answer.",
7698
+ ...ask3?.detail ? [` ${ask3.detail}`] : [],
7699
+ ` Your answer: ${answer}`,
7700
+ "Approve sends this answer as yours. Anything else leaves it waiting."
7701
+ ];
7702
+ }
7703
+ var MAX_PAGES = 5;
7704
+ async function findAsk(id2) {
7705
+ let cursor;
7706
+ for (let page = 0; page < MAX_PAGES; page++) {
7707
+ const listed = await listAsks({ limit: "100", ...cursor ? { cursor } : {} });
7708
+ const found = listed.data.find((ask3) => ask3.id === id2);
7709
+ if (found) return found;
7710
+ if (!listed.next_cursor) return null;
7711
+ cursor = listed.next_cursor;
7712
+ }
7713
+ return null;
7714
+ }
7715
+ function isPersonOnly(error) {
7716
+ return error instanceof ApiError && error.status === 409 && error.code === PERSON_REQUIRED;
7717
+ }
7718
+ async function answerAsk(id2, opts, decisionId) {
7719
+ return api("POST", `/asks/${encodeURIComponent(id2)}/answer`, answerFields(opts), decisionId ? { headers: { [ASK_DECISION_HEADER]: decisionId } } : {});
7720
+ }
7721
+ async function recordDecision2(id2, opts) {
7722
+ const recorded = await api("POST", "/confirmations/ask-decisions", { ask_id: id2, answer: answerFields(opts) });
7723
+ return recorded.decision_id;
7724
+ }
7725
+ async function answerWithDecision(id2, opts, env, readCode, known) {
7726
+ const refusal = refusalToAnswerAsPerson(env);
7727
+ if (refusal) throw new Error(refusal);
7728
+ const code = askAnswerCode(id2, opts);
7729
+ const typed = await readCode(code, renderPersonAnswer(known, opts));
7730
+ if (typed.trim().toUpperCase() !== code) return { waiting: true };
7731
+ const decision = await recordDecision2(id2, opts);
7732
+ return { answered: await answerAsk(id2, opts, decision) };
8994
7733
  }
8995
7734
  function renderAsk(ask3) {
8996
7735
  const choices = ask3.answer.options.length ? ` (${ask3.answer.options.map((option) => `${option.id}: ${option.label}`).join(", ")})` : "";
8997
- const by = ask3.answer.answered_by === "person" ? ", only you, in the app" : "";
7736
+ const by = ask3.answer.answered_by === "person" ? ", only you" : "";
8998
7737
  const why = ask3.why ? ` \u2014 ${ask3.why}` : "";
8999
7738
  const member = (end) => end.name ?? (end.kind === "person" ? "you" : end.kind);
9000
7739
  const ends = ask3.from && ask3.to ? `
@@ -9202,15 +7941,15 @@ function fileTableFrom(dir) {
9202
7941
  }
9203
7942
  function renderDesignSystem(system) {
9204
7943
  const tokens = system.tokens;
9205
- const lines2 = [
7944
+ const lines = [
9206
7945
  `${system.artifact_id} ${system.title} v${system.version}${system.editable ? "" : " read-only"}`,
9207
7946
  tokens ? `themes ${tokens.themes.map((theme) => theme.id).join(", ")} \xB7 ${tokens.colors.length} colors \xB7 ${tokens.typeGroups.reduce((sum, group) => sum + group.styles.length, 0)} type styles \xB7 ${tokens.spacing.length} spacing \xB7 ${tokens.radius.length} radius` : "no tokens.json",
9208
7947
  `components: ${system.components.map((component) => component.name).join(", ") || "none"}`,
9209
7948
  `assets: ${system.assets.map((group) => `${group.name} (${group.files.length})`).join(", ") || "none"}`
9210
7949
  ];
9211
- if (system.last_change) lines2.push(`last change: ${system.last_change.by}${system.last_change.via ? ` via ${system.last_change.via}` : ""} at ${system.last_change.at}`);
9212
- for (const token of tokens?.dropped ?? []) lines2.push(`not read: ${token.family} ${token.name || "(unnamed)"}: ${token.reason}`);
9213
- return lines2.join("\n");
7950
+ if (system.last_change) lines.push(`last change: ${system.last_change.by}${system.last_change.via ? ` via ${system.last_change.via}` : ""} at ${system.last_change.at}`);
7951
+ for (const token of tokens?.dropped ?? []) lines.push(`not read: ${token.family} ${token.name || "(unnamed)"}: ${token.reason}`);
7952
+ return lines.join("\n");
9214
7953
  }
9215
7954
  async function designComments(id2, input) {
9216
7955
  return api(input ? "POST" : "GET", `/artifacts/${encodeURIComponent(id2)}/design-system/comments`, input);
@@ -9266,16 +8005,16 @@ function joinCodingPlan(dollars3, requestId2) {
9266
8005
  return api("POST", "/billing/coding-plan", { amount_usd: amount, request_id: requestId2 });
9267
8006
  }
9268
8007
  var cancelCodingPlan = () => api("DELETE", "/billing/coding-plan");
9269
- function renderCodingPlan(plan2) {
9270
- if (!plan2.active) {
9271
- const lines3 = [`coding plan: not a member (enrollment ${plan2.enrollment}; monthly amounts $${plan2.amounts_usd.join(", $")})`];
9272
- if (plan2.charge_failure) lines3.push(` last charge failed: ${plan2.charge_failure}`);
9273
- return lines3.join("\n");
8008
+ function renderCodingPlan(plan) {
8009
+ if (!plan.active) {
8010
+ const lines2 = [`coding plan: not a member (enrollment ${plan.enrollment}; monthly amounts $${plan.amounts_usd.join(", $")})`];
8011
+ if (plan.charge_failure) lines2.push(` last charge failed: ${plan.charge_failure}`);
8012
+ return lines2.join("\n");
9274
8013
  }
9275
- const until = plan2.current_period_end?.slice(0, 10) ?? "?";
9276
- const lines2 = [`coding plan: $${plan2.monthly_credit_usd}/month, paid until ${until}, ${plan2.renews ? "renews" : "does not renew"}`];
9277
- if (plan2.charge_failure) lines2.push(` last charge failed: ${plan2.charge_failure}`);
9278
- return lines2.join("\n");
8014
+ const until = plan.current_period_end?.slice(0, 10) ?? "?";
8015
+ const lines = [`coding plan: $${plan.monthly_credit_usd}/month, paid until ${until}, ${plan.renews ? "renews" : "does not renew"}`];
8016
+ if (plan.charge_failure) lines.push(` last charge failed: ${plan.charge_failure}`);
8017
+ return lines.join("\n");
9279
8018
  }
9280
8019
  function readRequestUsage(opts) {
9281
8020
  const query = usageQuery(opts);
@@ -9283,10 +8022,10 @@ function readRequestUsage(opts) {
9283
8022
  return api("GET", `/billing/usage/requests${query}${cursor}`);
9284
8023
  }
9285
8024
  function renderRequestUsage(page) {
9286
- const lines2 = page.rows.map((row) => `${row.at.slice(0, 19).replace("T", " ")} ${(row.apiKeyName ?? "").padEnd(16).slice(0, 16)} ${(row.model ?? "-").padEnd(28).slice(0, 28)} ${String(row.httpStatus ?? "-").padStart(3)} ${String(row.inputTokens ?? 0).padStart(9)} in ${String(row.outputTokens ?? 0).padStart(8)} out ${`$${(row.billedCostUsd ?? 0).toFixed(6)}`.padStart(11)}`);
9287
- if (!lines2.length) lines2.push("no API requests in this range");
9288
- if (page.nextCursor) lines2.push(`more: --cursor ${page.nextCursor}`);
9289
- return lines2.join("\n");
8025
+ const lines = page.rows.map((row) => `${row.at.slice(0, 19).replace("T", " ")} ${(row.apiKeyName ?? "").padEnd(16).slice(0, 16)} ${(row.model ?? "-").padEnd(28).slice(0, 28)} ${String(row.httpStatus ?? "-").padStart(3)} ${String(row.inputTokens ?? 0).padStart(9)} in ${String(row.outputTokens ?? 0).padStart(8)} out ${`$${(row.billedCostUsd ?? 0).toFixed(6)}`.padStart(11)}`);
8026
+ if (!lines.length) lines.push("no API requests in this range");
8027
+ if (page.nextCursor) lines.push(`more: --cursor ${page.nextCursor}`);
8028
+ return lines.join("\n");
9290
8029
  }
9291
8030
  var readReferralLinks = () => api("GET", "/billing/referral-links");
9292
8031
  function referralLinkBody(opts) {
@@ -9308,17 +8047,17 @@ function referralLinkBody(opts) {
9308
8047
  var createReferralLink = (opts) => api("POST", "/billing/referral-links", referralLinkBody(opts));
9309
8048
  var disableReferralLink = (id2) => api("POST", `/billing/referral-links/${encodeURIComponent(id2)}/disable`);
9310
8049
  function renderReferralLinks(dashboard) {
9311
- const lines2 = [`priced from ${dashboard.source_plan.name}: customers pay at least ${Math.round(dashboard.source_plan.multiplier * 100)}% of public price`];
8050
+ const lines = [`priced from ${dashboard.source_plan.name}: customers pay at least ${Math.round(dashboard.source_plan.multiplier * 100)}% of public price`];
9312
8051
  for (const link2 of dashboard.links) {
9313
8052
  const state = link2.disabled_at ? "disabled" : `expires ${link2.expires_at.slice(0, 10)}`;
9314
8053
  const audience = link2.audience_email ? ` for ${link2.audience_email} (${link2.email_status})` : "";
9315
- lines2.push(` ${link2.id} ${Math.round(link2.customer_multiplier * 100)}% ${link2.redeemed_count}/${link2.max_redemptions} used ${state}${audience}`);
9316
- lines2.push(` ${link2.url}`);
8054
+ lines.push(` ${link2.id} ${Math.round(link2.customer_multiplier * 100)}% ${link2.redeemed_count}/${link2.max_redemptions} used ${state}${audience}`);
8055
+ lines.push(` ${link2.url}`);
9317
8056
  }
9318
- if (!dashboard.links.length) lines2.push(" no links yet");
8057
+ if (!dashboard.links.length) lines.push(" no links yet");
9319
8058
  const earned = dashboard.earnings.reduce((sum, earning) => sum + earning.amount_usd, 0);
9320
- lines2.push(`earned $${earned.toFixed(2)} from ${dashboard.earnings.length} customer${dashboard.earnings.length === 1 ? "" : "s"}`);
9321
- return lines2.join("\n");
8059
+ lines.push(`earned $${earned.toFixed(2)} from ${dashboard.earnings.length} customer${dashboard.earnings.length === 1 ? "" : "s"}`);
8060
+ return lines.join("\n");
9322
8061
  }
9323
8062
  function multiplier(flag, value) {
9324
8063
  const trimmed = value.trim();
@@ -9975,7 +8714,7 @@ agent.command("export <id>").description("write an agent as a manifest file that
9975
8714
  console.log(`Wrote ${opts.output} (version ${version}) \u2014 change it and run \`sky agent apply -f ${opts.output}\`.`);
9976
8715
  })
9977
8716
  );
9978
- var agentSlack = agent.command("slack").description("make an agent its own Slack bot, with its own name, avatar, DM and assistant panel");
8717
+ var agentSlack = agent.command("slack").description("an agent's thread in your DM with AgentSky, or its own Slack bot");
9979
8718
  agentSlack.command("token").description("save the Slack app-configuration token agents' Slack apps are created with (refresh token, rotated by AgentSky from then on)").option("--refresh-token <token>", "a Slack app-configuration refresh token (xoxe-\u2026)").option("--from-slack-cli [team]", "take it from this computer's Slack CLI login (~/.slack/credentials.json); hands that login over, so run `slack login` again afterwards").action(
9980
8719
  run2(async (opts) => {
9981
8720
  const refreshToken = opts.refreshToken ?? (opts.fromSlackCli ? slackCliRefreshToken(typeof opts.fromSlackCli === "string" ? opts.fromSlackCli : void 0) : void 0);
@@ -10009,16 +8748,38 @@ agentSlack.command("unpublish <agent>").description("uninstall and delete the ag
10009
8748
  console.log(`Removed from Slack: ${done.slack_app_ids.join(", ")}`);
10010
8749
  })
10011
8750
  );
8751
+ agentSlack.command("connect <agent>").description("give the agent its own thread in your DM with the AgentSky Slack app, and open it").option("--no-open", "print the thread link instead of opening it").option("--json", "print the answer as JSON").action(
8752
+ run2(async (agentId, opts) => {
8753
+ const thread2 = await connectAgentSlackDm(agentId);
8754
+ if (opts.json) return void console.log(JSON.stringify(thread2, null, 2));
8755
+ if (thread2.open_url && opts.open !== false) openBrowser(thread2.open_url);
8756
+ console.log(thread2.open_url ? `Connected: ${thread2.open_url}` : "Connected.");
8757
+ })
8758
+ );
8759
+ agentSlack.command("dm <agent>").description("whether the agent has its thread in your DM with AgentSky, and the link that opens it").option("--json", "print the answer as JSON").action(
8760
+ run2(async (agentId, opts) => {
8761
+ const thread2 = await agentSlackDm(agentId);
8762
+ if (opts.json) return void console.log(JSON.stringify(thread2, null, 2));
8763
+ console.log(thread2.status === "published" ? `Connected: ${thread2.open_url}` : thread2.installed ? "Not connected; the AgentSky app is already allowed in Slack." : "Not connected.");
8764
+ })
8765
+ );
8766
+ agentSlack.command("disconnect <agent>").description("take the agent out of your DM with AgentSky; the app and your other agents stay").option("--json", "print the answer as JSON").action(
8767
+ run2(async (agentId, opts) => {
8768
+ const done = await disconnectAgentSlackDm(agentId);
8769
+ if (opts.json) return void console.log(JSON.stringify(done, null, 2));
8770
+ console.log("Disconnected. The AgentSky app and your other agents stay.");
8771
+ })
8772
+ );
10012
8773
  agent.command("record").description("how each harness and model did, as the session record tells it: sessions, decisions people recorded, spend").option("--since <date>", "ISO 8601 start (default: 30 days before --until)").option("--until <date>", "ISO 8601 end (default: now)").option("--json", "print the record as JSON").action(
10013
8774
  run2(async (opts) => {
10014
- const record3 = await readAgentRecord(opts);
8775
+ const record = await readAgentRecord(opts);
10015
8776
  if (opts.json) {
10016
- console.log(JSON.stringify(record3, null, 2));
8777
+ console.log(JSON.stringify(record, null, 2));
10017
8778
  return;
10018
8779
  }
10019
- console.log(`${record3.since.slice(0, 10)} \u2013 ${record3.until.slice(0, 10)}`);
10020
- if (!record3.agents.length) console.log("no sessions in this window");
10021
- for (const row of record3.agents) console.log(renderAgentRecord(row));
8780
+ console.log(`${record.since.slice(0, 10)} \u2013 ${record.until.slice(0, 10)}`);
8781
+ if (!record.agents.length) console.log("no sessions in this window");
8782
+ for (const row of record.agents) console.log(renderAgentRecord(row));
10022
8783
  })
10023
8784
  );
10024
8785
  agent.command("archive <id>").description("retire the spec \u2014 read-only, running sessions unaffected (admin scope)").action(
@@ -10507,12 +9268,12 @@ sessionSandbox.command("exec <ref> <command...>").description("run a shell comma
10507
9268
  sessionSandbox.command("write <ref> <path> [file]").description("write a file in the workspace from a local file, or from stdin when none is given").option("--run <run>", "one of your own executions in the session: write on its own pod").action(
10508
9269
  run2(async (ref, path2, file, opts) => {
10509
9270
  const bytes = file ? readFileSync28(file) : readFileSync28(0);
10510
- const { path: at, size: size2 } = await api(
9271
+ const { path: at, size } = await api(
10511
9272
  "PUT",
10512
9273
  `/sessions/${encodeURIComponent(await resolveSessionRef(ref))}/sandbox/files`,
10513
9274
  { path: path2, content_base64: bytes.toString("base64"), ...opts.run ? { run_id: opts.run } : {} }
10514
9275
  );
10515
- console.log(`${at} (${size2} bytes)`);
9276
+ console.log(`${at} (${size} bytes)`);
10516
9277
  })
10517
9278
  );
10518
9279
  session.command("show-in-panel <id>").description("show something in the session's right panel, for whoever is watching on the web or the Mac").requiredOption("--kind <kind>", SHOW_KIND_CHOICES.join(", ")).option("--id <id>", "the artifact id").option("--artifact-version <n>", "an artifact's version; default the latest", Number).option("--url <url>", "the GitHub pull request URL").action(
@@ -10822,7 +9583,7 @@ async function launchFromFile(path2, spec, opts) {
10822
9583
  console.log(`Launched ${created.id} (${created.agentType} \xB7 ${created.llm})`);
10823
9584
  printModelBilling(session2);
10824
9585
  console.log(opts.start ? " its first session is starting now" : " its first session starts on the first message");
10825
- if (!spec.llm && !opts.llm) console.log(` model: ${created.llm}, the ${created.agentType} default \u2014 set llm = "\u2026" in ${basename9(path2)} and run \`sky deploy\` to change it`);
9586
+ if (!spec.llm && !opts.llm) console.log(` model: ${created.llm}, the ${created.agentType} default \u2014 set llm = "\u2026" in ${basename8(path2)} and run \`sky deploy\` to change it`);
10826
9587
  console.log(` sky agent message ${created.id} "hello"`);
10827
9588
  console.log(` sky agent chat ${created.id}`);
10828
9589
  }
@@ -10830,7 +9591,7 @@ program.command("launch").description("scaffold ./agent.toml if absent, create t
10830
9591
  run2(async (opts) => {
10831
9592
  const path2 = resolve13(opts.file);
10832
9593
  if (!existsSync15(path2)) {
10833
- const name = basename9(process.cwd()).replace(/[^a-zA-Z0-9 _-]/g, "") || "my-agent";
9594
+ const name = basename8(process.cwd()).replace(/[^a-zA-Z0-9 _-]/g, "") || "my-agent";
10834
9595
  scaffoldAgentFile(path2, name);
10835
9596
  console.log(`Scaffolded ${opts.file} \u2014 edit it anytime; re-apply with \`sky deploy\`.`);
10836
9597
  }
@@ -11023,10 +9784,10 @@ Importing ${label} \u2026
11023
9784
  );
11024
9785
  var files = program.command("files").description("files: upload once, reference by id from any message");
11025
9786
  function renderSearchPage(page) {
11026
- const lines2 = page.hits.map((hit) => `${hit.id} ${hit.path ?? hit.title}${hit.line ? `:${hit.line}` : ""} ${hit.snippet.replace(/\s+/g, " ").trim()}`);
11027
- if (!lines2.length) lines2.push(page.partial ? "no hits on this page (some items could not be read)" : "no hits");
11028
- if (page.nextCursor) lines2.push(`\u2026 more: --cursor ${page.nextCursor}`);
11029
- return lines2.join("\n");
9787
+ const lines = page.hits.map((hit) => `${hit.id} ${hit.path ?? hit.title}${hit.line ? `:${hit.line}` : ""} ${hit.snippet.replace(/\s+/g, " ").trim()}`);
9788
+ if (!lines.length) lines.push(page.partial ? "no hits on this page (some items could not be read)" : "no hits");
9789
+ if (page.nextCursor) lines.push(`\u2026 more: --cursor ${page.nextCursor}`);
9790
+ return lines.join("\n");
11030
9791
  }
11031
9792
  files.command("export").description("export the workspace's uploads with their Session mounts as an agentsky.files.v1 bundle").option("--out <file>", "write the bundle here instead of printing it").option("--reference", "carry each body by hash only (a copy inside this deployment)").option("--include-deleted", "list deleted uploads too").action(
11032
9793
  run2(async (opts) => {
@@ -11237,8 +9998,8 @@ session.command("export <session>").description("write the session's record as a
11237
9998
  run2(async (sessionId, opts) => {
11238
9999
  const tier = opts.tier === "gold" || opts.tier === "exploratory" ? opts.tier : "silver";
11239
10000
  const outDir = opts.out ?? `./harbor-${sessionId.replace(/[^A-Za-z0-9_-]/g, "_")}`;
11240
- const { written, record: record3 } = await exportTaskHarbor(sessionId, outDir, { tier, redactNames: parseRedactNames(opts.redact) });
11241
- console.log(`Wrote ${written.length} files to ${outDir} (${record3.threads.length} thread${record3.threads.length === 1 ? "" : "s"}, ${record3.files.length} task file${record3.files.length === 1 ? "" : "s"}${record3.goal ? ", goal rubric" : ", no goal: derived rubric"})`);
10001
+ const { written, record } = await exportTaskHarbor(sessionId, outDir, { tier, redactNames: parseRedactNames(opts.redact) });
10002
+ console.log(`Wrote ${written.length} files to ${outDir} (${record.threads.length} thread${record.threads.length === 1 ? "" : "s"}, ${record.files.length} task file${record.files.length === 1 ? "" : "s"}${record.goal ? ", goal rubric" : ", no goal: derived rubric"})`);
11242
10003
  if (!written.includes("environment/Dockerfile")) console.log("environment/: not resettable from the record \u2014 see environment/README.md before running with Harbor");
11243
10004
  })
11244
10005
  );
@@ -11557,13 +10318,13 @@ var USE_EXPORT = {
11557
10318
  };
11558
10319
  plugins.command("import <path>").description("add another agent platform's plugin as AgentSky plugins: a Claude Code or Codex plugin folder, a Codex config.toml, an mcp.json (generic, Cursor, ACP or xAI) or a folder sky plugins export wrote; skills and remote MCP servers map 1:1").option("--dry-run", "print what it would add and leave out, and add nothing").option("--json", "print the plan and the results as JSON").action(
11559
10320
  run2(async (path2, opts) => {
11560
- const plan2 = planImport(path2);
11561
- const results = opts.dryRun ? [] : await runImport(plan2);
11562
- if (opts.json) return void console.log(JSON.stringify({ plan: plan2, results }, null, 2));
11563
- console.log(`${plan2.name} (${plan2.format}): ${plan2.skills.length} skills, ${plan2.servers.length} remote MCP servers${plan2.core ? `, the core plugin ${plan2.core}` : ""}.`);
11564
- for (const skill of plan2.skills) console.log(` skill ${skill.name}`);
11565
- for (const server of plan2.servers) console.log(` MCP server ${server.name} ${server.url}${server.tokenEnv ? ` (key from ${server.tokenEnv})` : ""}`);
11566
- for (const skipped of plan2.skipped) console.log(` left out ${skipped.part}: ${skipped.reason}`);
10321
+ const plan = planImport(path2);
10322
+ const results = opts.dryRun ? [] : await runImport(plan);
10323
+ if (opts.json) return void console.log(JSON.stringify({ plan, results }, null, 2));
10324
+ console.log(`${plan.name} (${plan.format}): ${plan.skills.length} skills, ${plan.servers.length} remote MCP servers${plan.core ? `, the core plugin ${plan.core}` : ""}.`);
10325
+ for (const skill of plan.skills) console.log(` skill ${skill.name}`);
10326
+ for (const server of plan.servers) console.log(` MCP server ${server.name} ${server.url}${server.tokenEnv ? ` (key from ${server.tokenEnv})` : ""}`);
10327
+ for (const skipped of plan.skipped) console.log(` left out ${skipped.part}: ${skipped.reason}`);
11567
10328
  for (const result of results) console.log(` ${result.part}: ${result.result}${result.plugin_id ? ` ${result.plugin_id}` : ""}${result.detail ? ` \u2014 ${result.detail}` : ""}`);
11568
10329
  })
11569
10330
  );
@@ -11672,11 +10433,20 @@ skills.command("mine").description("your own skills, which follow you to every w
11672
10433
  for (const skill of mine2) console.log(`${skill.id} ${skill.name ?? ""}${skill.base_skill_id ? " (your change to a shared skill)" : ""}`);
11673
10434
  })
11674
10435
  );
11675
- skills.command("local").description("the skills sky installed in this computer's engines (Claude Code, Codex, Cursor, Grok, Hermes), with each one's revision, layer and pin").option("--json", "print as JSON").action(
10436
+ skills.command("local").description("the skills sky installed in this computer's engines (Claude Code, Codex, Cursor, Grok, Hermes), with each one's revision, layer and pin").option("--json", "print as JSON").option("--off", "stop installing skills on this computer and remove the folders sky wrote; folders you wrote stay").option("--on", "install the workspace's skills on this computer again from the next sync").action(
11676
10437
  run2(async (opts) => {
11677
- const { loadLocalSkillState } = await import("./local-skills-EIUQL24E.js");
10438
+ const { loadLocalSkillState, skillTargets: skillTargets2, turnOffLocalSkills, turnOnLocalSkills } = await import("./local-skills-5LJST7EP.js");
10439
+ if (opts.off && opts.on) throw new Error("pass --off or --on, not both");
10440
+ if (opts.off) {
10441
+ const { detectLocalAgents: detectLocalAgents2 } = await import("./local-agents-O7PYSQGR.js");
10442
+ const { detectHermes: detectHermes2 } = await import("./mcp-register-XY4MR3ZZ.js");
10443
+ const removed = turnOffLocalSkills(skillTargets2(detectLocalAgents2(), detectHermes2()?.root ?? null, void 0, { all: true }));
10444
+ return void console.log(`Skills are no longer installed on this computer${removed.length ? `; removed ${removed.length} that sky wrote` : ""}. \`sky skills local --on\` turns it back on.`);
10445
+ }
10446
+ if (opts.on) return void console.log(turnOnLocalSkills() ? "Skills are installed on this computer again from the next sync; `sky skills sync` does it now." : "Skills are already installed on this computer.");
11678
10447
  const state = loadLocalSkillState();
11679
10448
  if (opts.json) return void console.log(JSON.stringify(state, null, 2));
10449
+ if (state.off) return void console.log("Skills are not installed on this computer (turned off); `sky skills local --on` turns it back on.");
11680
10450
  const names = Object.keys(state.skills).sort();
11681
10451
  if (!names.length) return void console.log("no skills installed by sky on this computer; run `sky skills sync`");
11682
10452
  console.log(`From ${state.workspace ?? "?"}, last checked ${state.checkedAt ?? "never"}:`);
@@ -11690,25 +10460,26 @@ skills.command("local").description("the skills sky installed in this computer's
11690
10460
  );
11691
10461
  skills.command("sync").description("install the workspace's skills and your own skills and changes in this computer's engines now; capture does this every 15 minutes").option("--workspace <slug>", "the workspace whose skills to install (default: where capture sends sessions, else your default)").option("--dry-run", "show what would change without writing").option("--json", "print the result as JSON").action(
11692
10462
  run2(async (opts) => {
11693
- const { describeLocalSkills, refreshLocalSkills } = await import("./local-skills-run-FSVTDDOW.js");
10463
+ const { describeLocalSkills, refreshLocalSkills } = await import("./local-skills-run-6SZJQSVF.js");
11694
10464
  const result = await refreshLocalSkills({ workspace: opts.workspace, dryRun: opts.dryRun });
11695
10465
  if (opts.json) return void console.log(JSON.stringify(result, null, 2));
10466
+ if (result.off) return void console.log("Skills are not installed on this computer (turned off); `sky skills local --on` turns it back on.");
11696
10467
  if (!result.checked) return void console.log("no engine that reads skills is installed on this computer");
11697
- const lines2 = describeLocalSkills(result);
11698
- console.log(lines2.length ? `Skills from ${result.workspace}:
11699
- ${lines2.join("\n")}` : `Skills from ${result.workspace} are current.`);
10468
+ const lines = describeLocalSkills(result);
10469
+ console.log(lines.length ? `Skills from ${result.workspace}:
10470
+ ${lines.join("\n")}` : `Skills from ${result.workspace} are current.`);
11700
10471
  })
11701
10472
  );
11702
10473
  skills.command("pin <name>").description("keep a skill installed on this computer at the revision it has now; syncs leave it until you unpin it").action(
11703
10474
  run2(async (name) => {
11704
- const { pinLocalSkill } = await import("./local-skills-EIUQL24E.js");
10475
+ const { pinLocalSkill } = await import("./local-skills-5LJST7EP.js");
11705
10476
  const pinned = pinLocalSkill(name);
11706
10477
  console.log(`${name} stays at ${pinned.revision_id} on this computer`);
11707
10478
  })
11708
10479
  );
11709
10480
  skills.command("unpin <name>").description("let a pinned skill follow its updates again from the next sync").action(
11710
10481
  run2(async (name) => {
11711
- const { unpinLocalSkill } = await import("./local-skills-EIUQL24E.js");
10482
+ const { unpinLocalSkill } = await import("./local-skills-5LJST7EP.js");
11712
10483
  console.log(unpinLocalSkill(name) ? `${name} follows its updates again` : `${name} was not pinned`);
11713
10484
  })
11714
10485
  );
@@ -11836,7 +10607,7 @@ library.command("list").description("your Library, newest first").option("--sear
11836
10607
  library.command("upload <path>").description("save a file from this computer to your Library").option("--workspace <key>", "place it in this workspace").option("--session <id>", "save it as a result of this conversation of yours; the same name there saves a new version").action(
11837
10608
  run2(async (path2, opts) => {
11838
10609
  const bytes = readFileSync28(path2);
11839
- const { artifact: artifact2 } = await uploadToLibrary({ bytes, name: basename9(path2), mediaType: "application/octet-stream" }, crypto.randomUUID(), opts.workspace, opts.session);
10610
+ const { artifact: artifact2 } = await uploadToLibrary({ bytes, name: basename8(path2), mediaType: "application/octet-stream" }, crypto.randomUUID(), opts.workspace, opts.session);
11840
10611
  console.log(renderLibraryArtifact(artifact2));
11841
10612
  })
11842
10613
  );
@@ -11968,10 +10739,29 @@ asks.command("list").description("what waits on you: who is waiting, what is nee
11968
10739
  if (page.partial?.length) console.log(`Could not read: ${page.partial.join(", ")}. This list is incomplete.`);
11969
10740
  })
11970
10741
  );
11971
- asks.command("answer <id>").description("answer one; a payment, signature, plugin install or other approval stays with you in the app").option("--option <id>", "the option to answer with").option("--text <text>", "the answer, where free text is allowed").option("--engine <agentType>", "who starts, for a Start").option("--model <llm>", "the model they run").option("--json", "print as JSON").action(
10742
+ asks.command("answer <id>").description("answer one; a payment, signature, plugin install or other approval is decided here after you type its code, at an interactive terminal signed in as yourself").option("--option <id>", "the option to answer with").option("--text <text>", "the answer, where free text is allowed").option("--engine <agentType>", "who starts, for a Start").option("--model <llm>", "the model they run").option("--json", "print as JSON").action(
11972
10743
  run2(async (id2, opts) => {
11973
- const result = await answerAsk(id2, opts);
11974
- console.log(opts.json ? JSON.stringify(result, null, 2) : renderAnswered(result));
10744
+ const env = { stdinTTY: Boolean(process.stdin.isTTY), stdoutTTY: Boolean(process.stdout.isTTY), tokenFromEnv: Boolean(process.env.SKY_API_TOKEN), signedIn: Boolean(loadConfig().token) };
10745
+ const known = await findAsk(id2).catch(() => null);
10746
+ const print = (result) => console.log(opts.json ? JSON.stringify(result, null, 2) : renderAnswered(result));
10747
+ const decide = async () => {
10748
+ const result = await answerWithDecision(id2, opts, env, async (code, lines) => {
10749
+ for (const line2 of lines) console.log(line2);
10750
+ const rl = createInterface5({ input: process.stdin, output: process.stdout });
10751
+ const typed = await new Promise((resolve14) => rl.question(`Type ${code} to answer as yourself, or press Enter to leave it waiting: `, resolve14));
10752
+ rl.close();
10753
+ return typed;
10754
+ }, known);
10755
+ if ("waiting" in result) return void console.log("Not answered: it is still waiting.");
10756
+ print(result.answered);
10757
+ };
10758
+ if (known?.answer.answered_by === "person") return decide();
10759
+ try {
10760
+ print(await answerAsk(id2, opts));
10761
+ } catch (error) {
10762
+ if (!isPersonOnly(error)) throw error;
10763
+ await decide();
10764
+ }
11975
10765
  })
11976
10766
  );
11977
10767
  async function listApprovalsCommand(opts) {
@@ -12083,7 +10873,7 @@ artifact.command("copy <id>").description("copy one version into a new artifact
12083
10873
  artifact.command("import [file]").description("bring in a file or, with --url, a public web page as a new artifact; its original is version 1's file").option("--url <url>", "a public https page to snapshot").option("--name <name>", "the artifact's name (default: the file's name or the page's title)").option("--task <session>", "the session whose shared folder holds it (default: your own imports folder)").option("--request-id <id>", "send the same value when retrying").action(
12084
10874
  run2(async (file, opts) => {
12085
10875
  if (Boolean(file) === Boolean(opts.url)) throw new Error("name a file or --url");
12086
- console.log(renderArtifact(await importArtifact({ ...file ? { file: { name: basename9(file), bytes: readFileSync28(file) } } : { url: opts.url }, name: opts.name, taskId: opts.task, requestId: opts.requestId })));
10876
+ console.log(renderArtifact(await importArtifact({ ...file ? { file: { name: basename8(file), bytes: readFileSync28(file) } } : { url: opts.url }, name: opts.name, taskId: opts.task, requestId: opts.requestId })));
12087
10877
  })
12088
10878
  );
12089
10879
  artifact.command("export <id>").description("download an artifact in one of its formats (pdf, png, docx, html, markdown, csv, xlsx...); no --format is every file as a zip").option("--format <format>", "a format `sky artifact inspect` lists under export_formats").option("--artifact-version <version>", "an earlier version").requiredOption("-o, --out <path>", "where to write the bytes").action(
@@ -12517,17 +11307,17 @@ skyManager.command("autopilot").description("what your agents carry: each change
12517
11307
  run2(async (opts) => {
12518
11308
  const answer = await api("GET", "/sky/autopilot");
12519
11309
  if (opts.json) return void console.log(JSON.stringify(answer, null, 2));
12520
- const lines2 = [];
12521
- lines2.push(`Needs you (${answer.needs_you.length + answer.work.filter((item) => item.needs_you).length})`);
12522
- for (const ask3 of answer.needs_you) lines2.push(` ${ask3.session_title ?? "Session"}: ${ask3.question} ${ask3.link}`);
12523
- for (const item of answer.work.filter((entry) => entry.needs_you)) lines2.push(` ${item.title}: ${item.ask}`);
12524
- lines2.push(`Work (${answer.work.length})`);
12525
- for (const item of answer.work) lines2.push(` [${LADDER_WORDS[item.stage] ?? item.stage}${item.evidence === "verified" ? "" : ", stated"}] ${item.title}${item.now ? ` \u2014 ${item.now}` : ""}`);
12526
- lines2.push(`Waiting (${answer.waits.length})`);
12527
- for (const wait of answer.waits) lines2.push(` ${wait.session_title ?? "Session"}: ${wait.what}${wait.last_seen ? ` (${wait.last_seen})` : ""}`);
12528
- lines2.push(`Decided for you today (${answer.decisions.length}); veto with: sky manager veto <id>`);
12529
- for (const decision of answer.decisions) lines2.push(` ${decision.id}${decision.status === "vetoed" ? " (vetoed)" : ""}: ${decision.what} \u2014 ${decision.why}`);
12530
- console.log(lines2.join("\n"));
11310
+ const lines = [];
11311
+ lines.push(`Needs you (${answer.needs_you.length + answer.work.filter((item) => item.needs_you).length})`);
11312
+ for (const ask3 of answer.needs_you) lines.push(` ${ask3.session_title ?? "Session"}: ${ask3.question} ${ask3.link}`);
11313
+ for (const item of answer.work.filter((entry) => entry.needs_you)) lines.push(` ${item.title}: ${item.ask}`);
11314
+ lines.push(`Work (${answer.work.length})`);
11315
+ for (const item of answer.work) lines.push(` [${LADDER_WORDS[item.stage] ?? item.stage}${item.evidence === "verified" ? "" : ", stated"}] ${item.title}${item.now ? ` \u2014 ${item.now}` : ""}`);
11316
+ lines.push(`Waiting (${answer.waits.length})`);
11317
+ for (const wait of answer.waits) lines.push(` ${wait.session_title ?? "Session"}: ${wait.what}${wait.last_seen ? ` (${wait.last_seen})` : ""}`);
11318
+ lines.push(`Decided for you today (${answer.decisions.length}); veto with: sky manager veto <id>`);
11319
+ for (const decision of answer.decisions) lines.push(` ${decision.id}${decision.status === "vetoed" ? " (vetoed)" : ""}: ${decision.what} \u2014 ${decision.why}`);
11320
+ console.log(lines.join("\n"));
12531
11321
  })
12532
11322
  );
12533
11323
  skyManager.command("veto <decision>").description("veto a decision an agent made for you; its session is told to undo it").action(
@@ -13494,22 +12284,22 @@ program.command("capabilities").description("deprecated: sky plugins list --view
13494
12284
  );
13495
12285
  var mcpCommand = program.command("mcp").description("the AgentSky MCP server on this computer");
13496
12286
  mcpCommand.command("serve").description("serve the AgentSky MCP server's short tool list over stdio, for a program that starts its servers itself (the Claude app's chat, as `sky setup` registers it); each request is sent with the token sky holds at that moment").action(run2(async () => {
13497
- const { serveMcp } = await import("./mcp-serve-NQJZL7YP.js");
12287
+ const { serveMcp } = await import("./mcp-serve-QROKKUJV.js");
13498
12288
  await serveMcp();
13499
12289
  }));
13500
12290
  var compute = program.command("compute").description("the computers you set up with sky: the engines on each and whether each has the workspace's plugins, skills, capture and settings (the Compute group in Settings)");
13501
12291
  compute.command("list", { isDefault: true }).description("every computer you set up with sky, newest report first, with what is not current on each engine").option("--json", "print the list as JSON").action(run2(async (opts) => {
13502
- const { listComputeMachines, renderMachines } = await import("./compute-TCUMLDEK.js");
12292
+ const { listComputeMachines, renderMachines } = await import("./compute-4MMGFJGE.js");
13503
12293
  const machines = await listComputeMachines();
13504
12294
  console.log(opts.json ? JSON.stringify({ machines }, null, 2) : renderMachines(machines));
13505
12295
  }));
13506
12296
  compute.command("repair <machine>").description("ask one of your computers to put its AgentSky setup right on its next scheduled run").option("--json", "print the answer as JSON").action(run2(async (machine, opts) => {
13507
- const { requestRepair } = await import("./compute-TCUMLDEK.js");
12297
+ const { requestRepair } = await import("./compute-4MMGFJGE.js");
13508
12298
  const answer = await requestRepair(machine);
13509
12299
  console.log(opts.json ? JSON.stringify({ machine: answer }, null, 2) : `${answer.name} repairs on its next run (at most 15 minutes while it is on).`);
13510
12300
  }));
13511
12301
  compute.command("remove <machine>").description("forget one of your computers; nothing on it changes (run `sky setup --remove` there to take AgentSky out)").action(run2(async (machine) => {
13512
- const { removeMachine } = await import("./compute-TCUMLDEK.js");
12302
+ const { removeMachine } = await import("./compute-4MMGFJGE.js");
13513
12303
  await removeMachine(machine);
13514
12304
  console.log(`Forgot ${machine}. It reports again on its next run unless \`sky setup --remove\` ran there.`);
13515
12305
  }));
@@ -13596,7 +12386,7 @@ function bundleBody(file, requestId2, extra = {}) {
13596
12386
  throw new Error(`${file} is not a JSON bundle`);
13597
12387
  }
13598
12388
  if (!bundle || typeof bundle !== "object" || Array.isArray(bundle)) throw new Error(`${file} is not a JSON bundle`);
13599
- const derived = `import_${createHash10("sha256").update(text2).digest("hex").slice(0, 32)}`;
12389
+ const derived = `import_${createHash12("sha256").update(text2).digest("hex").slice(0, 32)}`;
13600
12390
  return { ...bundle, request_id: requestId2 ?? derived, ...extra };
13601
12391
  }
13602
12392
  function bundleQuery(entries) {
@@ -14178,7 +12968,7 @@ harness.command("connect").description("run an ACP agent (the command after --)
14178
12968
  }));
14179
12969
  var traceCmd = program.command("trace").description("correlate this machine's agent work with the cloud sessions it starts (metadata only unless you choose content)");
14180
12970
  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(run2(async (opts) => {
14181
- const { readState, writeState, record: record3, installClaudeHooks, parseContentScopes, chosenPaths, fileEvent } = await import("./trace-GFC46TQC.js");
12971
+ const { readState, writeState, record, installClaudeHooks, parseContentScopes, chosenPaths, fileEvent } = await import("./trace-SJZ25T35.js");
14182
12972
  if (readState()) throw new Error("a trace is already running here \u2014 `sky trace stop` it first");
14183
12973
  const scopes = parseContentScopes(opts.capture);
14184
12974
  const chosen = chosenPaths(opts.file ?? [], opts.dir ?? []);
@@ -14201,7 +12991,7 @@ traceCmd.command("start").description("start a trace: a grant for this machine,
14201
12991
  ...scopes.length ? { content_scopes: scopes, files: chosen.files, dirs: chosen.dirs } : {}
14202
12992
  };
14203
12993
  writeState(state);
14204
- record3(() => [
12994
+ record(() => [
14205
12995
  { span_id: root2, parent_span_id: null, kind: "start", name: opts.name ?? "task" },
14206
12996
  ...chosen.files.flatMap((path2) => fileEvent(root2, path2, state) ?? [])
14207
12997
  ]);
@@ -14213,11 +13003,11 @@ traceCmd.command("start").description("start a trace: a grant for this machine,
14213
13003
  }));
14214
13004
  traceCmd.command("hook").description("record one Claude Code hook event read from stdin (run by the installed hooks; never fails, prints nothing)").action(async () => {
14215
13005
  try {
14216
- const { readState, record: record3, flush, grantSender, eventsForClaudeHook, contentForClaudeHook, clearState } = await import("./trace-GFC46TQC.js");
13006
+ const { readState, record, flush, grantSender, eventsForClaudeHook, contentForClaudeHook, clearState } = await import("./trace-SJZ25T35.js");
14217
13007
  const chunks = [];
14218
13008
  for await (const chunk of process.stdin) chunks.push(chunk);
14219
13009
  const input = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
14220
- if (!record3((state2) => [...eventsForClaudeHook(input, state2), ...contentForClaudeHook(input, state2)])) return;
13010
+ if (!record((state2) => [...eventsForClaudeHook(input, state2), ...contentForClaudeHook(input, state2)])) return;
14221
13011
  const state = readState();
14222
13012
  if (!state) return;
14223
13013
  const outcome = await flush(grantSender(state, 3e3));
@@ -14226,14 +13016,14 @@ traceCmd.command("hook").description("record one Claude Code hook event read fro
14226
13016
  }
14227
13017
  });
14228
13018
  traceCmd.command("flush").description("send what the spool holds, retrying with backoff").action(run2(async () => {
14229
- const { readState, flush, grantSender } = await import("./trace-GFC46TQC.js");
13019
+ const { readState, flush, grantSender } = await import("./trace-SJZ25T35.js");
14230
13020
  const state = readState();
14231
13021
  if (!state) throw new Error("no trace is running here");
14232
13022
  const outcome = await flush(grantSender(state), { attempts: 4 });
14233
13023
  console.log(`sent ${outcome.sent}, refused ${outcome.refused}, given up ${outcome.expired}, still pending ${outcome.pending}${outcome.stopped ? ` (stopped: ${outcome.stopped})` : ""}`);
14234
13024
  }));
14235
13025
  traceCmd.command("status").description("the running trace and its spool").action(run2(async () => {
14236
- const { readState, spoolStatus } = await import("./trace-GFC46TQC.js");
13026
+ const { readState, spoolStatus } = await import("./trace-SJZ25T35.js");
14237
13027
  const state = readState();
14238
13028
  if (!state) {
14239
13029
  console.log("No trace is running here.");
@@ -14243,7 +13033,7 @@ traceCmd.command("status").description("the running trace and its spool").action
14243
13033
  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`);
14244
13034
  }));
14245
13035
  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(run2(async (id2, opts) => {
14246
- const { readState } = await import("./trace-GFC46TQC.js");
13036
+ const { readState } = await import("./trace-SJZ25T35.js");
14247
13037
  const ref = id2 ?? readState()?.trace_id;
14248
13038
  if (!ref) throw new Error("name a trace, or start one here");
14249
13039
  const bundle = await api("GET", `/traces/${ref}`);
@@ -14270,10 +13060,10 @@ traceCmd.command("show [id]").description("the trace bundle: spans, the sessions
14270
13060
  for (const gap of bundle.gaps) console.log(` gap: ${gap.span_id} ${gap.reason}`);
14271
13061
  }));
14272
13062
  traceCmd.command("stop").description("end the root span, send what is left, and revoke this machine's grant").action(run2(async () => {
14273
- const { readState, record: record3, flush, grantSender, clearState } = await import("./trace-GFC46TQC.js");
13063
+ const { readState, record, flush, grantSender, clearState } = await import("./trace-SJZ25T35.js");
14274
13064
  const state = readState();
14275
13065
  if (!state) throw new Error("no trace is running here");
14276
- if (state.root_span) record3(() => [{ span_id: state.root_span, kind: "end", outcome: "completed" }]);
13066
+ if (state.root_span) record(() => [{ span_id: state.root_span, kind: "end", outcome: "completed" }]);
14277
13067
  const outcome = await flush(grantSender(readState() ?? state), { attempts: 4 });
14278
13068
  await api("DELETE", `/traces/${state.trace_id}/grants/${state.grant_id}`);
14279
13069
  clearState();
@@ -14283,7 +13073,7 @@ var recordCmd = traceCmd.command("record").description("record every Claude Code
14283
13073
  const { homedir: homedir12 } = await import("os");
14284
13074
  const { join: join21 } = await import("path");
14285
13075
  const vault2 = await import("./trace-vault-IUNYRVGZ.js");
14286
- const { installClaudeHooks, uninstallClaudeHooks } = await import("./trace-GFC46TQC.js");
13076
+ const { installClaudeHooks, uninstallClaudeHooks } = await import("./trace-SJZ25T35.js");
14287
13077
  const command = "sky trace record hook";
14288
13078
  const config = vault2.loadVaultConfig();
14289
13079
  const settings = resolve13(opts.settings ?? config.settings ?? join21(process.env.CLAUDE_CONFIG_DIR ?? join21(homedir12(), ".claude"), "settings.json"));
@@ -14347,8 +13137,8 @@ recordCmd.command("seal <session-dir>").description("seal the cut segments of on
14347
13137
  vault2.markPartial(resolve13(session2, "..", "..", ".."), session2.split(/[\\/]/).filter(Boolean).pop(), error);
14348
13138
  }
14349
13139
  });
14350
- 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("--exclude <folder>", "never upload a session that ran in <folder> or below it, to the library or as a session (repeatable; shared with the AgentSky Mac app when it is installed)", collect).option("--unexclude <folder>", "stop excluding <folder> (repeatable)", collect).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("--install-hooks", "also sync at the end of every Claude Code and Codex turn (their hook and notify settings)").option("--status", "what sync has done on this machine").option("--quiet", "print only failures").action(async (payload, opts) => {
14351
- const lib = await import("./trace-library-4F57EGL7.js");
13140
+ 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("--personal <workspace>", "your personal workspace: the only place a session holding personal data (passport, medical, insurance, phone, address \u2026) is uploaded").option("--allow-shared-private", "let sessions that hold personal data go to a workspace other than your personal one").option("--exclude <folder>", "never upload a session that ran in <folder> or below it, to the library or as a session (repeatable; shared with the AgentSky Mac app when it is installed)", collect).option("--unexclude <folder>", "stop excluding <folder> (repeatable)", collect).option("--session <ref>", "only this session: its id or transcript path (repeatable)", collect).option("--agent <id>", "only sessions of this agent (grok-bot, muse, claude_code, codex \u2026 as `--agents` lists them; 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("--install-hooks", "also sync at the end of every Claude Code and Codex turn (their hook and notify settings)").option("--status", "what sync has done on this machine").option("--quiet", "print only failures").action(async (payload, opts) => {
13141
+ const lib = await import("./trace-library-V23TEXG4.js");
14352
13142
  if (opts.hook) {
14353
13143
  try {
14354
13144
  let raw = payload ?? "";
@@ -14373,14 +13163,14 @@ traceCmd.command("sync [payload]").description("upload this machine's agent sess
14373
13163
  return;
14374
13164
  }
14375
13165
  if (opts.exclude || opts.unexclude) {
14376
- const { changeExclusions, macSettingsPath } = await import("./trace-exclusions-JEGMUPWQ.js");
13166
+ const { changeExclusions, macSettingsPath } = await import("./trace-exclusions-IC6OA2ND.js");
14377
13167
  const { dirname: dirname13 } = await import("path");
14378
13168
  const changed = changeExclusions(dirname13(lib.syncConfigPath()), { add: opts.exclude, remove: opts.unexclude });
14379
13169
  console.log(changed.exclusions.folders.length ? "Sync never uploads sessions that ran in:" : "No folder is excluded.");
14380
13170
  for (const folder of changed.exclusions.folders) console.log(` ${folder}`);
14381
13171
  if (changed.written === "mac") console.log(`Saved in the AgentSky Mac app's settings (${macSettingsPath()}), so the app leaves them out too.`);
14382
13172
  }
14383
- const changedSettings = opts.enable || opts.route || opts.default || opts.keepLocal;
13173
+ const changedSettings = opts.enable || opts.route || opts.default || opts.keepLocal || opts.personal;
14384
13174
  if (changedSettings) {
14385
13175
  if (opts.enable && !apiToken()) throw new Error("not logged in \u2014 run `sky auth login` first");
14386
13176
  const rules = opts.route ? opts.route.map((spec) => {
@@ -14393,7 +13183,8 @@ traceCmd.command("sync [payload]").description("upload this machine's agent sess
14393
13183
  rules,
14394
13184
  enabled: opts.enable ? true : config.enabled,
14395
13185
  enabledAt: opts.enable ? (/* @__PURE__ */ new Date()).toISOString() : config.enabledAt,
14396
- fallback: opts.keepLocal ? void 0 : opts.default ?? config.fallback
13186
+ fallback: opts.keepLocal ? void 0 : opts.default ?? config.fallback,
13187
+ personal: opts.personal ?? config.personal
14397
13188
  };
14398
13189
  lib.saveSyncConfig(next);
14399
13190
  console.log(`Trace sync is ${next.enabled ? "on" : "off"} on this machine. It reads only:`);
@@ -14401,6 +13192,7 @@ traceCmd.command("sync [payload]").description("upload this machine's agent sess
14401
13192
  console.log("and sends each session, redacted here first, to:");
14402
13193
  for (const rule of next.rules) console.log(` folder path contains "${rule.match}" \u2192 ${rule.workspace}`);
14403
13194
  console.log(` anything else \u2192 ${next.fallback ?? "stays on this machine"}`);
13195
+ console.log(` sessions holding personal data \u2192 ${next.personal ?? "stay on this machine (set --personal <workspace>)"} only`);
14404
13196
  console.log(`A repository's .agentsky.json "workspace" wins over these rules.`);
14405
13197
  if (next.sessions !== false) console.log("Each Claude Code and Codex conversation also becomes one session there, read by whoever that workspace's default for synced chats names, with the files it published, made and was given saved as its results.");
14406
13198
  }
@@ -14414,6 +13206,11 @@ traceCmd.command("sync [payload]").description("upload this machine's agent sess
14414
13206
  for (const input of opts.import ?? []) {
14415
13207
  const imported = await lib.importExport(input);
14416
13208
  console.log(`Added ${imported.sessions} ${imported.agent} session${imported.sessions === 1 ? "" : "s"} from ${input}.`);
13209
+ if (imported.sensitive) {
13210
+ const { describeFindings } = await import("./trace-privacy-DU3TL5EO.js");
13211
+ console.log(` ${imported.sensitive} of them hold personal data the export did not redact (${describeFindings({ sensitive: true, findings: imported.findings, messages_flagged: 0, messages: 0 })}).`);
13212
+ console.log(` Sync uploads those only to ${config.personal ?? "your personal workspace once you run `sky trace sync --personal <workspace>`"}; they stay on this computer otherwise.`);
13213
+ }
14417
13214
  }
14418
13215
  if (opts.installHooks) for (const line2 of lib.installSyncHooks()) console.log(line2);
14419
13216
  if (opts.installSchedule) {
@@ -14444,7 +13241,7 @@ traceCmd.command("sync [payload]").description("upload this machine's agent sess
14444
13241
  }
14445
13242
  console.log(`Trace sync is ${config.enabled ? "on" : "off"}${config.enabledAt ? ` (since ${config.enabledAt})` : ""}. Last full sweep: ${state.lastFullAt ?? "never"}.`);
14446
13243
  for (const [label, count] of [...counts].sort((a, b) => b[1] - a[1])) console.log(` ${count} ${label}`);
14447
- const { loadExclusions } = await import("./trace-exclusions-JEGMUPWQ.js");
13244
+ const { loadExclusions } = await import("./trace-exclusions-IC6OA2ND.js");
14448
13245
  for (const folder of loadExclusions(join21(lib.syncConfigPath(), "..")).folders) console.log(` excluded: ${folder}`);
14449
13246
  return;
14450
13247
  }
@@ -14454,6 +13251,8 @@ traceCmd.command("sync [payload]").description("upload this machine's agent sess
14454
13251
  only: opts.session,
14455
13252
  dryRun: opts.dryRun,
14456
13253
  limit: opts.limit,
13254
+ allowSharedPrivate: opts.allowSharedPrivate,
13255
+ agents: opts.agent,
14457
13256
  onProgress: opts.quiet ? void 0 : (line2) => console.log(line2)
14458
13257
  });
14459
13258
  if (!report) {
@@ -14461,7 +13260,7 @@ traceCmd.command("sync [payload]").description("upload this machine's agent sess
14461
13260
  return;
14462
13261
  }
14463
13262
  if (!opts.dryRun) {
14464
- const { describeLocalSkills, refreshLocalSkills } = await import("./local-skills-run-FSVTDDOW.js");
13263
+ const { describeLocalSkills, refreshLocalSkills } = await import("./local-skills-run-6SZJQSVF.js");
14465
13264
  try {
14466
13265
  const skills2 = await refreshLocalSkills({ hook: Boolean(opts.session?.length) });
14467
13266
  if (skills2 && !opts.quiet) for (const line2 of describeLocalSkills(skills2)) console.log(line2);
@@ -14472,20 +13271,64 @@ traceCmd.command("sync [payload]").description("upload this machine's agent sess
14472
13271
  if (!opts.quiet || report.failed) {
14473
13272
  if (report.legacySources) console.log(`Kept ${report.legacySources} unbound legacy source archives locally; no ownership was inferred.`);
14474
13273
  const where = Object.entries(report.byWorkspace).map(([workspace2, count]) => `${count} \u2192 ${workspace2}`).join(", ");
14475
- console.log(`${opts.dryRun ? "Would upload" : "Uploaded"} ${report.uploaded}${where ? ` (${where})` : ""}; unchanged ${report.unchanged}; saved as sessions ${report.sessions}; excluded ${report.excluded}; left out as paused ${report.paused}; kept local ${report.local}; empty ${report.empty}; another member's ${report.owned}; failed ${report.failed}. Scanned ${report.scanned}, ${report.changed} changed.`);
13274
+ console.log(`${opts.dryRun ? "Would upload" : "Uploaded"} ${report.uploaded}${where ? ` (${where})` : ""}; unchanged ${report.unchanged}; saved as sessions ${report.sessions}; excluded ${report.excluded}; left out as paused ${report.paused}; kept local ${report.local}${report.held ? ` (${report.held} of them hold personal data; rerun with --full after setting --personal to send them to it)` : ""}; empty ${report.empty}; another member's ${report.owned}; failed ${report.failed}. Scanned ${report.scanned}, ${report.changed} changed.`);
14476
13275
  for (const error of report.errors.slice(0, 20)) console.error(` ${error}`);
14477
13276
  }
14478
13277
  if (!opts.session && !opts.dryRun) {
14479
- const { upkeepComputer } = await import("./compute-report-LC2OH2QJ.js");
13278
+ const { upkeepComputer } = await import("./compute-report-LIMMRQY3.js");
14480
13279
  const said = await upkeepComputer().catch((error) => `AgentSky could not check this computer's setup: ${error instanceof Error ? error.message : String(error)}`);
14481
13280
  if (said) console.log(said);
14482
13281
  }
14483
13282
  if (report.failed) process.exitCode = 1;
14484
13283
  })();
14485
13284
  });
13285
+ traceCmd.command("handoff <session>").description("hand a collected session (Grok Bot, Muse, Instinct or any other source `trace sync --agents` lists) to Claude Code, Codex or an AgentSky agent, with its whole conversation").requiredOption("--to <target>", "claude_code | codex | agentsky | grok-bot (grok-bot: a Grok Bot trace export folder, from a Claude Code or Codex session file or any collected session; agentsky: written as a Claude Code session, then sent through `sky import`, which continues it in the cloud)").option("--dir <folder>", "the folder the engine works in", ".").option("--out <folder>", "grok-bot only: where the Grok Bot trace export (manifest.json + sessions/) is written").option("--workspace <workspace>", "agentsky only: the workspace the session goes to (default: your personal workspace)").option("--allow-shared-private", "agentsky only: let a session that holds personal data go to a workspace other than your personal one").option("--json", "print the result as JSON").action(
13286
+ run2(async (ref, opts) => {
13287
+ const handoff2 = await import("./trace-handoff-CD5LOS7B.js");
13288
+ if (!handoff2.HANDOFF_TARGETS.includes(opts.to)) throw new Error("--to takes claude_code, codex, agentsky or grok-bot");
13289
+ const lib = await import("./trace-library-V23TEXG4.js");
13290
+ const store = await lib.collectorStore();
13291
+ const found = await handoff2.findTrace(ref, store, lib.collectorDir());
13292
+ if (!found) throw new Error(`no collected session "${ref}": add an export with \`sky trace sync --import <export>\` first`);
13293
+ const config = lib.loadSyncConfig();
13294
+ if (opts.to === "grok-bot") {
13295
+ const { writeGrokBotExport } = await import("./grok-bot-export-7LSTXWJW.js");
13296
+ const out = resolve13(opts.out ?? opts.dir);
13297
+ const written = writeGrokBotExport([found.trace], out, found.trace.harness);
13298
+ if (opts.json) console.log(JSON.stringify({ target: "grok-bot", ...written }));
13299
+ else console.log(`Wrote ${written.rows} rows to ${written.manifest} and sessions/`);
13300
+ return;
13301
+ }
13302
+ const engine = opts.to === "codex" ? "codex" : "claude_code";
13303
+ if (opts.to === "agentsky") {
13304
+ const hold = handoff2.agentskyHold(found.trace, opts.workspace ?? config.personal, config, opts.allowSharedPrivate);
13305
+ if (hold) throw new Error(hold);
13306
+ }
13307
+ const landed = handoff2.handOff(found.trace, engine, resolve13(opts.dir), { transcript: found.path });
13308
+ let continueUrl;
13309
+ if (opts.to === "agentsky") {
13310
+ const { execFileSync } = await import("child_process");
13311
+ const out = execFileSync(process.execPath, [process.argv[1], "import", "--session", landed.nativeId, "--harness", "claude_code", "--yes", "--json"], { encoding: "utf8", env: process.env });
13312
+ continueUrl = out.trim().split("\n").filter(Boolean).map((line2) => {
13313
+ try {
13314
+ return JSON.parse(line2);
13315
+ } catch {
13316
+ return {};
13317
+ }
13318
+ }).map((row) => row.continue_url ?? row.url).find(Boolean);
13319
+ }
13320
+ if (opts.json) {
13321
+ console.log(JSON.stringify({ ...landed, continue_url: continueUrl }));
13322
+ return;
13323
+ }
13324
+ const { toolCalls, summarised } = landed.report;
13325
+ console.error(`Wrote ${landed.engine === "codex" ? "Codex" : "Claude Code"} session ${landed.nativeId}: ${landed.report.messages.user + landed.report.messages.agent} messages, ${toolCalls.mapped} tool calls in its own form, ${toolCalls.asText} as text${summarised ? `; the oldest ${summarised} messages are summarised at the top` : ""}.`);
13326
+ console.log(continueUrl ?? landed.resume);
13327
+ })
13328
+ );
14486
13329
  traceCmd.command("mac <machine>").description("which workspace's trace library one of your Macs fills; the AgentSky Mac app uploads that Mac's agent sessions there, redacted on the Mac first, exactly as `sky trace sync` would (machine ids: `sky api GET /desktop/machines`)").option("--on", "send this Mac's sessions to --workspace (or the current workspace), moving them from any other").option("--off", "stop this Mac's uploads to --workspace (or the current workspace)").option("--workspace <slug>", "the workspace to turn on or off (default: the current one)").option("--json", "print the answer as JSON").action(run2(async (machine, opts) => {
14487
13330
  if (opts.on && opts.off) throw new Error("choose --on or --off");
14488
- const { libraryRequest } = await import("./trace-library-4F57EGL7.js");
13331
+ const { libraryRequest } = await import("./trace-library-V23TEXG4.js");
14489
13332
  const workspace2 = opts.workspace ?? currentUniverse();
14490
13333
  if (!workspace2) throw new Error("name a workspace with --workspace");
14491
13334
  const answer = opts.on || opts.off ? await libraryRequest("PUT", `/trace-library/devices/${encodeURIComponent(machine)}`, workspace2, { enabled: Boolean(opts.on) }) : await libraryRequest("GET", `/trace-library/devices/${encodeURIComponent(machine)}`, workspace2);
@@ -14502,7 +13345,7 @@ traceCmd.command("search <query...>").description("search every session in a wor
14502
13345
  console.log(opts.json ? JSON.stringify(page, null, 2) : renderContextPage(page));
14503
13346
  }));
14504
13347
  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(run2(async (opts) => {
14505
- const { libraryRequest } = await import("./trace-library-4F57EGL7.js");
13348
+ const { libraryRequest } = await import("./trace-library-V23TEXG4.js");
14506
13349
  const workspace2 = opts.workspace ?? currentUniverse();
14507
13350
  if (!workspace2) throw new Error("name a workspace with --workspace");
14508
13351
  const page = await libraryRequest("GET", `/trace-library?limit=${opts.limit}`, workspace2);