@agentsky/sky 3.43.0 → 3.45.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.
@@ -1,10 +1,6 @@
1
- import {
2
- importPathAllowed,
3
- uploadLargeFile
4
- } from "./chunk-AB7SUDX4.js";
5
1
  import {
6
2
  installClaudeHooks
7
- } from "./chunk-4MVM65ET.js";
3
+ } from "./chunk-UHEJFBZJ.js";
8
4
  import {
9
5
  IncompleteSourceCaptureError,
10
6
  SOURCE_CAPTURE_VERSION,
@@ -20,42 +16,145 @@ import {
20
16
  savePendingSource,
21
17
  stillExcluded,
22
18
  writePrivateJson
23
- } from "./chunk-UJ7IXSJX.js";
19
+ } from "./chunk-YYDO5WB5.js";
24
20
  import {
25
21
  SessionSourceCollector,
26
22
  publicRemote,
27
23
  redactTraceText
28
- } from "./chunk-BIZJ4VZL.js";
24
+ } from "./chunk-AM6GOGA6.js";
29
25
  import {
30
- ApiError
31
- } from "./chunk-44XF4EGE.js";
26
+ ApiError,
27
+ api
28
+ } from "./chunk-WLTOVOTW.js";
32
29
  import {
33
30
  loadLocalSkillState,
34
31
  revisionAt
35
- } from "./chunk-J3KIEZXM.js";
32
+ } from "./chunk-WSQZHRE4.js";
36
33
  import {
37
34
  USER_AGENT
38
- } from "./chunk-4A4PDUT5.js";
35
+ } from "./chunk-7DFFA6GA.js";
39
36
  import {
40
37
  apiBase,
41
- apiToken
38
+ apiToken,
39
+ configPath
42
40
  } from "./chunk-XHZJG3QT.js";
43
- import "./chunk-MLKGABMK.js";
44
41
 
45
42
  // src/trace-library.ts
46
- import { createHash as createHash2 } from "crypto";
47
- import { createReadStream, existsSync as existsSync2, mkdirSync, mkdtempSync, readdirSync, readFileSync as readFileSync2, rmSync, statSync as statSync2, writeFileSync } from "fs";
43
+ import { createHash as createHash3 } from "crypto";
44
+ import { createReadStream, existsSync as existsSync3, mkdirSync as mkdirSync2, mkdtempSync, readdirSync as readdirSync2, readFileSync as readFileSync4, rmSync as rmSync2, statSync as statSync4, writeFileSync as writeFileSync2 } from "fs";
48
45
  import { createInterface } from "readline";
49
- import { homedir as homedir3, hostname } from "os";
50
- import { basename as basename2, dirname as dirname3, join as join2, sep as sep2 } from "path";
46
+ import { homedir as homedir4, hostname } from "os";
47
+ import { basename as basename4, dirname as dirname5, join as join4, sep as sep3 } from "path";
51
48
  import { fileURLToPath, pathToFileURL } from "url";
52
49
  import { createGunzip } from "zlib";
53
50
 
51
+ // src/resumable-upload.ts
52
+ import { createHash } from "crypto";
53
+ import { mkdirSync, openSync, readFileSync, readSync, closeSync, rmSync, statSync, writeFileSync } from "fs";
54
+ import { basename, dirname, join, resolve } from "path";
55
+ var SINGLE_REQUEST_MAX_BYTES = 32 * 1024 * 1024;
56
+ var MAX_ATTEMPTS = 8;
57
+ function statePath(path, size, mtimeMs, universe) {
58
+ const key = createHash("sha256").update(`${resolve(path)}\0${size}\0${mtimeMs}\0${universe ?? ""}`).digest("hex").slice(0, 32);
59
+ return join(dirname(configPath()), "uploads", `${key}.json`);
60
+ }
61
+ function loadSession(file, expiresInSeconds, universe) {
62
+ try {
63
+ const saved = JSON.parse(readFileSync(file, "utf8"));
64
+ if (saved.expiresInSeconds !== expiresInSeconds || saved.universe !== universe) return null;
65
+ if (Date.parse(saved.expires_at) - Date.now() < 3600 * 1e3) return null;
66
+ return saved;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+ function acknowledged(res) {
72
+ const range = res.headers.get("range")?.match(/^bytes=0-(\d+)$/);
73
+ return range ? Number(range[1]) + 1 : 0;
74
+ }
75
+ async function probe(session) {
76
+ const res = await fetch(session.upload_url, {
77
+ method: "PUT",
78
+ headers: { "user-agent": USER_AGENT, "content-range": `bytes */${session.size_bytes}` }
79
+ });
80
+ if (res.status === 200 || res.status === 201) return "done";
81
+ if (res.status === 308) return acknowledged(res);
82
+ if (res.status === 404 || res.status === 410) throw new ApiError(res.status, "upload_expired", "the upload session is gone");
83
+ throw new ApiError(res.status, "upload_failed", `upload status check failed: ${res.status} ${res.statusText}`);
84
+ }
85
+ async function sendChunk(session, fd, offset) {
86
+ const length = Math.min(session.chunk_size, session.size_bytes - offset);
87
+ const chunk = Buffer.alloc(length);
88
+ let read = 0;
89
+ while (read < length) read += readSync(fd, chunk, read, length - read, offset + read);
90
+ const res = await fetch(session.upload_url, {
91
+ method: "PUT",
92
+ headers: {
93
+ "user-agent": USER_AGENT,
94
+ "content-range": `bytes ${offset}-${offset + length - 1}/${session.size_bytes}`
95
+ },
96
+ body: chunk
97
+ });
98
+ if (res.status === 200 || res.status === 201) return "done";
99
+ if (res.status === 308) return acknowledged(res);
100
+ if (res.status >= 500 || res.status === 429) throw new Error(`transient ${res.status}`);
101
+ throw new ApiError(res.status, "upload_failed", `chunk upload failed: ${res.status} ${(await res.text()).slice(0, 200)}`);
102
+ }
103
+ async function transfer(session, path, onProgress) {
104
+ const fd = openSync(path, "r");
105
+ try {
106
+ let failures = 0;
107
+ let state = await probe(session);
108
+ while (state !== "done") {
109
+ onProgress(state, session.size_bytes);
110
+ try {
111
+ state = await sendChunk(session, fd, state);
112
+ failures = 0;
113
+ } catch (error) {
114
+ if (error instanceof ApiError || ++failures >= MAX_ATTEMPTS) throw error;
115
+ await new Promise((done) => setTimeout(done, Math.min(3e4, 500 * 2 ** failures)));
116
+ state = await probe(session);
117
+ }
118
+ }
119
+ onProgress(session.size_bytes, session.size_bytes);
120
+ } finally {
121
+ closeSync(fd);
122
+ }
123
+ }
124
+ async function uploadLargeFile(path, mediaType, expiresInSeconds, onProgress, universe) {
125
+ const { size, mtimeMs } = statSync(path);
126
+ const stateFile = statePath(path, size, mtimeMs, universe);
127
+ let session = loadSession(stateFile, expiresInSeconds, universe);
128
+ if (session) {
129
+ try {
130
+ await probe(session);
131
+ } catch (error) {
132
+ if (!(error instanceof ApiError) || error.status !== 404 && error.status !== 410) throw error;
133
+ session = null;
134
+ }
135
+ }
136
+ if (!session) {
137
+ session = await api("POST", "/files/uploads", {
138
+ filename: basename(path),
139
+ size_bytes: size,
140
+ mime_type: mediaType,
141
+ ...expiresInSeconds ? { expires_in_seconds: expiresInSeconds } : {}
142
+ }, { universe });
143
+ mkdirSync(dirname(stateFile), { recursive: true });
144
+ const saved = { ...session, path: resolve(path), mtimeMs, expiresInSeconds, universe };
145
+ writeFileSync(stateFile, JSON.stringify(saved), { mode: 384 });
146
+ }
147
+ await transfer(session, path, onProgress);
148
+ const file = await api("POST", `/files/uploads/${encodeURIComponent(session.id)}/complete`, void 0, { universe });
149
+ rmSync(stateFile, { force: true });
150
+ return file;
151
+ }
152
+
54
153
  // src/trace-references.ts
55
154
  import { execFileSync } from "child_process";
56
155
  import { existsSync } from "fs";
57
156
  import { homedir } from "os";
58
- import { dirname } from "path";
157
+ import { dirname as dirname2 } from "path";
59
158
  var PULL_URL = /github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/([1-9][0-9]{0,8})/g;
60
159
  var GMAIL_ID = /(?:message_?id|thread_?id)\\*"?\s*[:=]\s*\\*"?([0-9a-f]{16})\b/gi;
61
160
  var GMAIL_PATH = /(?:\/messages\/|\/threads\/|mail\.google\.com\/[^\s"\\]*[#/])([0-9a-f]{16})\b/g;
@@ -100,7 +199,7 @@ function gitRemoteAt(cwd) {
100
199
  if (remotes.has(cwd)) return remotes.get(cwd);
101
200
  let remote;
102
201
  const home = homedir();
103
- for (let folder = cwd; folder !== home && folder !== dirname(folder); folder = dirname(folder)) {
202
+ for (let folder = cwd; folder !== home && folder !== dirname2(folder); folder = dirname2(folder)) {
104
203
  if (!existsSync(folder)) continue;
105
204
  try {
106
205
  remote = execFileSync("git", ["-C", folder, "remote", "get-url", "origin"], { encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"] }).trim() || void 0;
@@ -114,10 +213,299 @@ function gitRemoteAt(cwd) {
114
213
  }
115
214
 
116
215
  // src/session-results.ts
117
- import { createHash } from "crypto";
118
- import { readFileSync, statSync } from "fs";
216
+ import { createHash as createHash2 } from "crypto";
217
+ import { readFileSync as readFileSync3, statSync as statSync3 } from "fs";
218
+ import { homedir as homedir3 } from "os";
219
+ import { basename as basename3, dirname as dirname4, extname, isAbsolute, join as join3, normalize, resolve as resolve3, sep as sep2 } from "path";
220
+
221
+ // src/import-workspace.ts
222
+ import { spawnSync } from "child_process";
223
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, realpathSync, statSync as statSync2 } from "fs";
119
224
  import { homedir as homedir2 } from "os";
120
- import { basename, dirname as dirname2, extname, isAbsolute, join, normalize, resolve, sep } from "path";
225
+ import { basename as basename2, dirname as dirname3, join as join2, relative, resolve as resolve2, sep } from "path";
226
+ import { parse as parseToml } from "smol-toml";
227
+ function importReadAllowed(path, allowed) {
228
+ if (!allowed) return true;
229
+ if (!allowed(path)) return false;
230
+ try {
231
+ return allowed(realpathSync(path));
232
+ } catch {
233
+ return false;
234
+ }
235
+ }
236
+ var SECRET_FILE = /(^|\/)(\.env(\..*)?|\.netrc|\.npmrc|\.pypirc|\.git-credentials|\.?credentials(\.json)?|auth\.json|\.claude\.json|id_(rsa|ed25519|ecdsa)[^/]*|.*\.(pem|key|p12|pfx|keystore|jks|kdbx|sqlite|db))$|\/\.ssh\/|\/\.aws\/|\/\.gnupg\/|\/\.docker\/config\.json$|\/Keychains\//i;
237
+ var SKIP_DIR = /(^|\/)(node_modules|\.git|\.next|dist|build|__pycache__|\.venv)(\/|$)/;
238
+ function importPathAllowed(path) {
239
+ const normalized = resolve2(path).split(sep).join("/");
240
+ return !SECRET_FILE.test(normalized) && !SKIP_DIR.test(normalized) && !/(^|\/)(\.ssh|\.aws|\.gnupg|Keychains)(\/|$)/i.test(normalized);
241
+ }
242
+ var MAX_TREE = 5e3;
243
+ var SKILL_LINE = /Base directory for this skill: (\/[^\n\r"'\\<>]+)/g;
244
+ function git(cwd, ...args) {
245
+ const run = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8", timeout: 1e4, maxBuffer: 32 * 1024 * 1024 });
246
+ return run.status === 0 ? run.stdout : null;
247
+ }
248
+ function repositoryRoot(cwd, allowed) {
249
+ if (!cwd || !importReadAllowed(cwd, allowed)) return null;
250
+ for (let dir = resolve2(cwd); ; dir = dirname3(dir)) {
251
+ if (!importReadAllowed(dir, allowed)) return null;
252
+ if (existsSync2(join2(dir, ".git"))) {
253
+ if (!importReadAllowed(join2(dir, ".git"), allowed)) return null;
254
+ const root = git(cwd, "rev-parse", "--show-toplevel")?.trim();
255
+ return root && importReadAllowed(root, allowed) ? realpathSync(root) : null;
256
+ }
257
+ if (dir === dirname3(dir)) return null;
258
+ }
259
+ }
260
+ var isFile = (path) => {
261
+ try {
262
+ return statSync2(path).isFile();
263
+ } catch {
264
+ return false;
265
+ }
266
+ };
267
+ var isDir = (path) => {
268
+ try {
269
+ return statSync2(path).isDirectory();
270
+ } catch {
271
+ return false;
272
+ }
273
+ };
274
+ function sharedInstructionPaths(home = homedir2(), allowed) {
275
+ const rules = join2(home, ".agents", "rules");
276
+ let ruleFiles = [];
277
+ try {
278
+ ruleFiles = (importReadAllowed(rules, allowed) ? readdirSync(rules) : []).filter((name) => name.endsWith(".md")).sort().map((name) => join2(rules, name));
279
+ } catch {
280
+ }
281
+ return [join2(home, "AGENTS.md"), join2(home, "MEMORY.md"), ...ruleFiles].filter((path) => importReadAllowed(path, allowed) && isFile(path));
282
+ }
283
+ function strings(value, out, depth = 0) {
284
+ if (depth > 12) return;
285
+ if (typeof value === "string") out.push(value);
286
+ else if (Array.isArray(value)) for (const item of value) strings(item, out, depth + 1);
287
+ else if (value && typeof value === "object") for (const item of Object.values(value)) strings(item, out, depth + 1);
288
+ }
289
+ function skillRoots(cwd, home) {
290
+ const claude = process.env.CLAUDE_CONFIG_DIR ?? join2(home, ".claude");
291
+ const codex = process.env.CODEX_HOME ?? join2(home, ".codex");
292
+ return [
293
+ ...cwd ? [join2(cwd, ".claude", "skills"), join2(cwd, ".agents", "skills")] : [],
294
+ join2(home, ".agents", "skills"),
295
+ join2(claude, "skills"),
296
+ join2(codex, "skills"),
297
+ join2(home, ".hermes", "skills")
298
+ ];
299
+ }
300
+ function pluginSkill(plugin, skill, home, allowed) {
301
+ const walk = (dir, depth, underPlugin) => {
302
+ if (depth > 7 || !importReadAllowed(dir, allowed)) return null;
303
+ let entries;
304
+ try {
305
+ entries = readdirSync(dir, { withFileTypes: true });
306
+ } catch {
307
+ return null;
308
+ }
309
+ for (const entry of entries) {
310
+ if (!entry.isDirectory() || entry.name === "node_modules" || entry.name === ".git") continue;
311
+ const path = join2(dir, entry.name);
312
+ if (entry.name === skill && basename2(dir) === "skills" && (underPlugin || path.includes(`${sep}${plugin}${sep}`)) && importReadAllowed(join2(path, "SKILL.md"), allowed) && isFile(join2(path, "SKILL.md"))) return realpathSync(path);
313
+ const found = walk(path, depth + 1, underPlugin);
314
+ if (found) return found;
315
+ }
316
+ return null;
317
+ };
318
+ return walk(join2(process.env.CLAUDE_CONFIG_DIR ?? join2(home, ".claude"), "plugins"), 0, false) ?? walk(join2(home, "Library", "Application Support", "Claude", "local-agent-mode-sessions", "skills-plugin"), 0, true);
319
+ }
320
+ function findSkill(name, cwd, home, allowed) {
321
+ const [scope, skill] = name.includes(":") ? name.split(":", 2) : [null, name];
322
+ if (scope && skill) return pluginSkill(scope, skill, home, allowed);
323
+ for (const root of skillRoots(cwd, home)) {
324
+ const direct = join2(root, name);
325
+ if (importReadAllowed(join2(direct, "SKILL.md"), allowed) && isFile(join2(direct, "SKILL.md"))) return realpathSync(direct);
326
+ }
327
+ return null;
328
+ }
329
+ function loadedSkills(records, touched, cwd, home = homedir2(), allowed) {
330
+ const dirs = /* @__PURE__ */ new Map();
331
+ const missing = /* @__PURE__ */ new Set();
332
+ const add = (dir, name = basename2(dir)) => {
333
+ if (!importReadAllowed(join2(dir, "SKILL.md"), allowed) || !isFile(join2(dir, "SKILL.md"))) return false;
334
+ const real = realpathSync(dir);
335
+ if (![...dirs.values()].includes(real)) dirs.set(name, real);
336
+ return true;
337
+ };
338
+ const called = [];
339
+ for (const record of records) {
340
+ const texts = [];
341
+ strings(record, texts);
342
+ for (const text of texts) for (const match of text.matchAll(SKILL_LINE)) add(match[1].trim().replace(/[.,;:)]+$/, ""));
343
+ const content = record?.message?.content;
344
+ if (!Array.isArray(content)) continue;
345
+ for (const block of content) {
346
+ const b = block;
347
+ if (b?.type === "tool_use" && b.name === "Skill" && typeof b.input?.skill === "string") called.push(b.input.skill.replace(/^\//, ""));
348
+ }
349
+ }
350
+ for (const path of touched) if (basename2(path) === "SKILL.md") add(dirname3(path));
351
+ for (const name of called) {
352
+ if (!name || dirs.has(name) || [...dirs.keys()].some((key) => key.endsWith(`:${name}`) || name.endsWith(`:${key}`))) continue;
353
+ const dir = findSkill(name, cwd, home, allowed);
354
+ if (!dir || !add(dir, name)) missing.add(name);
355
+ }
356
+ return { found: [...dirs].map(([name, dir]) => ({ name: name.replace(/[^A-Za-z0-9._:-]/g, "-"), dir })), missing: [...missing] };
357
+ }
358
+ function readJson(path, allowed) {
359
+ if (!importReadAllowed(path, allowed)) return null;
360
+ try {
361
+ const value = JSON.parse(readFileSync2(path, "utf8"));
362
+ return value && typeof value === "object" ? value : null;
363
+ } catch {
364
+ return null;
365
+ }
366
+ }
367
+ function names(value) {
368
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
369
+ const keys = Object.keys(value).sort();
370
+ return keys.length ? keys : void 0;
371
+ }
372
+ function safeUrl(raw) {
373
+ try {
374
+ const url = new URL(raw);
375
+ if (!/^https?:$/.test(url.protocol)) return null;
376
+ const query = [.../* @__PURE__ */ new Set([...url.searchParams.keys()])].sort();
377
+ return { url: `${url.protocol}//${url.host}${url.pathname}`, ...query.length ? { query } : {} };
378
+ } catch {
379
+ return null;
380
+ }
381
+ }
382
+ function serverEntry(name, def, scope) {
383
+ if (!def || typeof def !== "object") return null;
384
+ const env = names(def.env);
385
+ const headers = names(def.headers ?? def.http_headers);
386
+ if (typeof def.url === "string") {
387
+ const url = safeUrl(def.url);
388
+ if (!url) return null;
389
+ const type = def.type === "sse" ? "sse" : "http";
390
+ return { name, scope, transport: type, ...url, ...headers ? { headers } : {}, ...env ? { env } : {} };
391
+ }
392
+ if (typeof def.command !== "string" || !def.command) return null;
393
+ const args = Array.isArray(def.args) ? def.args.filter((arg) => typeof arg === "string") : [];
394
+ return { name, scope, transport: "stdio", command: def.command, ...args.length ? { args } : {}, ...env ? { env } : {} };
395
+ }
396
+ function mcpServers(harness, cwd, home = homedir2(), allowed) {
397
+ const out = [];
398
+ const push = (servers, scope) => {
399
+ if (!servers || typeof servers !== "object") return;
400
+ for (const [name, def] of Object.entries(servers)) {
401
+ const entry = serverEntry(name, def, scope);
402
+ if (entry && !out.some((existing) => existing.name === name)) out.push(entry);
403
+ }
404
+ };
405
+ if (harness === "claude_code") {
406
+ const config = readJson(join2(process.env.CLAUDE_CONFIG_DIR ? dirname3(process.env.CLAUDE_CONFIG_DIR) : home, ".claude.json"), allowed);
407
+ const projects = config?.projects && typeof config.projects === "object" ? config.projects : {};
408
+ const root = cwd && importReadAllowed(cwd, allowed) ? repositoryRoot(cwd, allowed) || cwd : "";
409
+ if (cwd) push(projects[cwd]?.mcpServers ?? projects[root]?.mcpServers, "local");
410
+ if (root) push(readJson(join2(root, ".mcp.json"), allowed)?.mcpServers, "project");
411
+ push(config?.mcpServers, "user");
412
+ }
413
+ if (harness === "codex") {
414
+ try {
415
+ const path = join2(process.env.CODEX_HOME ?? join2(home, ".codex"), "config.toml");
416
+ if (!importReadAllowed(path, allowed)) return out;
417
+ const config = parseToml(readFileSync2(path, "utf8"));
418
+ push(config.mcp_servers, "user");
419
+ } catch {
420
+ }
421
+ }
422
+ return out;
423
+ }
424
+ function remoteWithoutCredentials(remote) {
425
+ return remote.trim().replace(/\/\/[^@/]+@/, "//").replace(/^[^@/]+@([^:]+):/, "$1:");
426
+ }
427
+ function workspaceState(cwd, harness, skills, home = homedir2(), title = null, allowed) {
428
+ const present = !!cwd && importReadAllowed(cwd, allowed) && isDir(cwd);
429
+ const root = present ? repositoryRoot(cwd, allowed) : null;
430
+ let gitState = null;
431
+ let tree = [];
432
+ let patch = null;
433
+ if (root && importReadAllowed(root, allowed)) {
434
+ const dirty = (git(root, "status", "--porcelain=v1", "--untracked-files=normal") ?? "").split("\n").filter(Boolean).map((line) => line.slice(3));
435
+ const ahead = git(root, "rev-list", "--count", "@{upstream}..HEAD");
436
+ const remote = git(root, "remote", "get-url", "origin");
437
+ const branch = git(root, "rev-parse", "--abbrev-ref", "HEAD")?.trim() || null;
438
+ gitState = {
439
+ remote: remote ? remoteWithoutCredentials(remote) : null,
440
+ branch: branch === "HEAD" ? null : branch,
441
+ commit: git(root, "rev-parse", "HEAD")?.trim() || null,
442
+ dirty: dirty.slice(0, 500),
443
+ ahead: ahead === null ? null : Number(ahead.trim()) || 0
444
+ };
445
+ tree = (git(cwd, "-c", "core.quotePath=false", "ls-files") ?? "").split("\n").filter(Boolean);
446
+ if (dirty.length) {
447
+ const changed = (git(cwd, "diff", "HEAD", "--name-only", "-z", "--relative", "--", ".") ?? "").split("\0").filter(Boolean);
448
+ const paths = changed.filter((path) => {
449
+ const absolute = resolve2(cwd, path);
450
+ return importPathAllowed(absolute) && importReadAllowed(absolute, allowed) && (!existsSync2(absolute) || importPathAllowed(realpathSync(absolute)));
451
+ });
452
+ if (paths.length) patch = git(cwd, "diff", "HEAD", "--no-color", "--no-ext-diff", "--no-textconv", "--relative", "--", ...paths) || null;
453
+ }
454
+ }
455
+ return {
456
+ manifest: {
457
+ format: "agentsky.import-workspace",
458
+ format_version: 1,
459
+ harness,
460
+ title: title?.trim().slice(0, 120) || null,
461
+ cwd: cwd ? cwd.replace(home, "~") : null,
462
+ project: cwd ? basename2(root ?? cwd) : null,
463
+ git: gitState,
464
+ tree: tree.slice(0, MAX_TREE),
465
+ tree_truncated: tree.length > MAX_TREE,
466
+ skills: [...skills.found.map((skill) => ({ name: skill.name, found: true })), ...skills.missing.map((name) => ({ name, found: false }))],
467
+ mcp_servers: mcpServers(harness, cwd, home, allowed)
468
+ },
469
+ patch
470
+ };
471
+ }
472
+ function skillFiles(skill, allowed) {
473
+ const out = [];
474
+ const walk = (dir, depth) => {
475
+ if (depth > 8 || out.length > 400 || !importReadAllowed(dir, allowed)) return;
476
+ let entries;
477
+ try {
478
+ entries = readdirSync(dir, { withFileTypes: true });
479
+ } catch {
480
+ return;
481
+ }
482
+ for (const entry of entries) {
483
+ if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "__pycache__" || entry.name === ".venv") continue;
484
+ const path = join2(dir, entry.name);
485
+ if (entry.isDirectory()) walk(path, depth + 1);
486
+ else if (entry.isFile() && importReadAllowed(path, allowed)) out.push({ path, name: `skills/${skill.name}/${relative(skill.dir, path).split(sep).join("/")}` });
487
+ }
488
+ };
489
+ if (existsSync2(skill.dir)) walk(skill.dir, 0);
490
+ return out;
491
+ }
492
+ function codexThreadName(sessionId, home = homedir2()) {
493
+ let name = null;
494
+ try {
495
+ for (const line of readFileSync2(join2(process.env.CODEX_HOME ?? join2(home, ".codex"), "session_index.jsonl"), "utf8").split("\n")) {
496
+ if (!line.includes(sessionId)) continue;
497
+ try {
498
+ const entry = JSON.parse(line);
499
+ if (entry.id === sessionId && typeof entry.thread_name === "string" && entry.thread_name.trim()) name = entry.thread_name.trim();
500
+ } catch {
501
+ }
502
+ }
503
+ } catch {
504
+ }
505
+ return name;
506
+ }
507
+
508
+ // src/session-results.ts
121
509
  var MAX_RESULT_BYTES = 15 * 1024 * 1024;
122
510
  var RESULT_TYPES = {
123
511
  ".mp4": "video/mp4",
@@ -223,17 +611,17 @@ function turnsOf(records, cwd = "") {
223
611
  }
224
612
  return turns;
225
613
  }
226
- function strings(value, into = []) {
614
+ function strings2(value, into = []) {
227
615
  if (typeof value === "string") into.push(value);
228
- else if (Array.isArray(value)) for (const item of value) strings(item, into);
229
- else if (value && typeof value === "object") for (const item of Object.values(value)) strings(item, into);
616
+ else if (Array.isArray(value)) for (const item of value) strings2(item, into);
617
+ else if (value && typeof value === "object") for (const item of Object.values(value)) strings2(item, into);
230
618
  return into;
231
619
  }
232
620
  function resolved(candidate, cwd, home) {
233
621
  const text = candidate.replace(/^file:\/\//, "");
234
- if (text.startsWith("~/")) return join(home, text.slice(2));
622
+ if (text.startsWith("~/")) return join3(home, text.slice(2));
235
623
  if (isAbsolute(text)) return normalize(text);
236
- return cwd ? resolve(cwd, text) : null;
624
+ return cwd ? resolve3(cwd, text) : null;
237
625
  }
238
626
  function credential(file) {
239
627
  return !importPathAllowed(file);
@@ -242,13 +630,13 @@ function kept(file, home) {
242
630
  const inHome = file.startsWith(`${home}/`);
243
631
  if (!inHome && SCRATCH_ROOTS.some((root) => file.startsWith(root))) return false;
244
632
  if (!importPathAllowed(file)) return false;
245
- const relative = inHome ? file.slice(home.length + 1) : file.replace(/^\//, "");
246
- return !relative.split("/").slice(0, -1).some((part) => REBUILT.has(part));
633
+ const relative2 = inHome ? file.slice(home.length + 1) : file.replace(/^\//, "");
634
+ return !relative2.split("/").slice(0, -1).some((part) => REBUILT.has(part));
247
635
  }
248
636
  function inWebProject(file, home, stat) {
249
- for (let dir = dirname2(file); dir.startsWith(`${home}/`); dir = dirname2(dir)) {
637
+ for (let dir = dirname4(file); dir.startsWith(`${home}/`); dir = dirname4(dir)) {
250
638
  try {
251
- if (stat(join(dir, "package.json")).isFile()) return true;
639
+ if (stat(join3(dir, "package.json")).isFile()) return true;
252
640
  } catch {
253
641
  }
254
642
  }
@@ -261,8 +649,8 @@ function publishedPaths(tool) {
261
649
  return [input.file_path, ...Array.isArray(input.file_paths) ? input.file_paths : [], ...files.map((entry) => typeof entry === "string" ? entry : obj(entry)?.from)].filter((entry) => typeof entry === "string" && entry.length > 0);
262
650
  }
263
651
  function sessionResults(records, options = {}) {
264
- const home = options.home ?? homedir2();
265
- const stat = options.stat ?? statSync;
652
+ const home = options.home ?? homedir3();
653
+ const stat = options.stat ?? statSync3;
266
654
  const turns = turnsOf(records, options.cwd ?? "");
267
655
  const found = [];
268
656
  for (const turn of options.all ? turns : turns.slice(-1)) {
@@ -279,7 +667,7 @@ function sessionResults(records, options = {}) {
279
667
  return;
280
668
  }
281
669
  if (!info.isFile() || info.size === 0 || info.size > MAX_RESULT_BYTES || fresh && !(info.mtimeMs >= turn.since - 1e3)) return;
282
- found.push({ path: file, name: basename(file), mediaType, size: info.size, mtimeMs: Math.floor(info.mtimeMs), origin });
670
+ found.push({ path: file, name: basename3(file), mediaType, size: info.size, mtimeMs: Math.floor(info.mtimeMs), origin });
283
671
  };
284
672
  turn.pictures.forEach((picture, index) => {
285
673
  const data = Buffer.from(picture.data, "base64");
@@ -295,13 +683,13 @@ function sessionResults(records, options = {}) {
295
683
  const file = resolved(raw, tool.cwd, home);
296
684
  if (file && !credential(file)) add(file, "published", typeOf(file, true), false);
297
685
  }
298
- const texts = [...turn.tools.flatMap((tool) => strings(tool.input)), ...turn.said];
686
+ const texts = [...turn.tools.flatMap((tool) => strings2(tool.input)), ...turn.said];
299
687
  for (const text of texts) {
300
688
  for (const match of text.matchAll(PATH_LIKE)) {
301
- const tool = turn.tools.find((entry) => strings(entry.input).includes(text));
689
+ const tool = turn.tools.find((entry) => strings2(entry.input).includes(text));
302
690
  const file = resolved(match[0], tool?.cwd ?? options.cwd ?? "", home);
303
691
  if (!file || seen.has(file)) continue;
304
- const name = basename(file);
692
+ const name = basename3(file);
305
693
  const mediaType = typeOf(name, false);
306
694
  if (!mediaType || !said.includes(name) || !kept(file, home)) continue;
307
695
  if (mediaType === "text/html" && inWebProject(file, home, stat)) continue;
@@ -311,9 +699,9 @@ function sessionResults(records, options = {}) {
311
699
  }
312
700
  return found;
313
701
  }
314
- function pageWithImages(bytes, file, home = homedir2(), explicit = false) {
702
+ function pageWithImages(bytes, file, home = homedir3(), explicit = false) {
315
703
  const html = bytes.toString("utf8");
316
- const dir = dirname2(file);
704
+ const dir = dirname4(file);
317
705
  const images = /* @__PURE__ */ new Map();
318
706
  let total = bytes.length;
319
707
  for (const match of html.matchAll(LOCAL_REFERENCE)) {
@@ -321,15 +709,15 @@ function pageWithImages(bytes, file, home = homedir2(), explicit = false) {
321
709
  if (images.has(reference) || /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\/)/i.test(reference)) continue;
322
710
  let target;
323
711
  try {
324
- target = resolve(dir, decodeURI(reference.split(/[?#]/, 1)[0]));
712
+ target = resolve3(dir, decodeURI(reference.split(/[?#]/, 1)[0]));
325
713
  } catch {
326
714
  continue;
327
715
  }
328
716
  const mediaType = typeOf(target, false);
329
- if (!mediaType?.startsWith("image/") || !(explicit ? target.startsWith(`${dir}${sep}`) : kept(target, home))) continue;
717
+ if (!mediaType?.startsWith("image/") || !(explicit ? target.startsWith(`${dir}${sep2}`) : kept(target, home))) continue;
330
718
  let image;
331
719
  try {
332
- image = readFileSync(target);
720
+ image = readFileSync3(target);
333
721
  } catch {
334
722
  continue;
335
723
  }
@@ -342,7 +730,7 @@ function pageWithImages(bytes, file, home = homedir2(), explicit = false) {
342
730
  return Buffer.from(html.replace(LOCAL_REFERENCE, (whole, lead, quote, reference) => images.has(reference.trim()) ? `${lead}${quote}${images.get(reference.trim())}${quote}` : whole), "utf8");
343
731
  }
344
732
  function resultRequestId(...parts) {
345
- const hex = createHash("sha256").update(JSON.stringify(parts)).digest("hex");
733
+ const hex = createHash2("sha256").update(JSON.stringify(parts)).digest("hex");
346
734
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
347
735
  }
348
736
  var RateLimited = class extends Error {
@@ -362,7 +750,7 @@ async function call(fetcher, method, path, workspace, body, multipart2) {
362
750
  return answer;
363
751
  }
364
752
  function multipart(fields) {
365
- const boundary = `----sky${createHash("sha256").update(fields.requestId).digest("hex").slice(0, 24)}`;
753
+ const boundary = `----sky${createHash2("sha256").update(fields.requestId).digest("hex").slice(0, 24)}`;
366
754
  const filename = fields.name.replace(/[\r\n]/g, " ").replace(/"/g, "%22");
367
755
  const field = (key, value) => Buffer.from(`--${boundary}\r
368
756
  Content-Disposition: form-data; name="${key}"\r
@@ -387,7 +775,7 @@ function readRecords(files) {
387
775
  const records = [];
388
776
  for (const file of files) {
389
777
  if (file.endsWith(".gz")) continue;
390
- for (const line of readFileSync(file, "utf8").split("\n")) {
778
+ for (const line of readFileSync3(file, "utf8").split("\n")) {
391
779
  if (!line.trim()) continue;
392
780
  try {
393
781
  records.push(JSON.parse(line));
@@ -399,17 +787,17 @@ function readRecords(files) {
399
787
  }
400
788
  async function captureSessionResults(input, state, options = {}) {
401
789
  const fetcher = options.fetcher ?? fetch;
402
- const home = options.home ?? homedir2();
790
+ const home = options.home ?? homedir3();
403
791
  const key = `${input.harness}:${input.nativeId}`;
404
792
  const saved = new Set(state.saved);
405
793
  let count = 0;
406
794
  let limited = false;
407
795
  for (const result of sessionResults(readRecords(input.files), { cwd: input.cwd, home, all: !state.read.includes(key) })) {
408
- const version = result.path ? [`native:${input.nativeId}`, result.path, result.size, result.mtimeMs] : [`native:${input.nativeId}`, result.name, createHash("sha256").update(result.data).digest("hex")];
796
+ const version = result.path ? [`native:${input.nativeId}`, result.path, result.size, result.mtimeMs] : [`native:${input.nativeId}`, result.name, createHash2("sha256").update(result.data).digest("hex")];
409
797
  const id = JSON.stringify(version);
410
798
  if (saved.has(id)) continue;
411
799
  try {
412
- const read = result.data ?? readFileSync(result.path);
800
+ const read = result.data ?? readFileSync3(result.path);
413
801
  if (read.length !== result.size) continue;
414
802
  const bytes = result.path && result.mediaType === "text/html" ? pageWithImages(read, result.path, home, result.origin !== "delivered") : read;
415
803
  await call(fetcher, "POST", "/library/artifacts", input.workspace, void 0, multipart({ name: result.name, mediaType: result.mediaType, bytes, requestId: resultRequestId(...version), sessionId: input.sessionId }));
@@ -471,8 +859,8 @@ function skillReadsIn(rows, messages, state) {
471
859
  };
472
860
  rows.forEach((row, index) => {
473
861
  if (row.role === "tool") {
474
- const names = skillNamesRead(row.text).filter((name) => state.skills[name]);
475
- waiting.push(...names.map((name) => ({ name, ...row.at ? { at: row.at } : {} })));
862
+ const names2 = skillNamesRead(row.text).filter((name) => state.skills[name]);
863
+ waiting.push(...names2.map((name) => ({ name, ...row.at ? { at: row.at } : {} })));
476
864
  if (current?.role === "agent") settle(current.id);
477
865
  return;
478
866
  }
@@ -576,52 +964,61 @@ var RETRIES = 3;
576
964
  var RATE_LIMIT_RETRIES = 30;
577
965
  var HARNESS_PREAMBLES = ["<environment_context>", "<user_instructions>", "<permissions instructions>", "# AGENTS.md instructions", "<INSTRUCTIONS>", "<external_codex_apps_open_page>"];
578
966
  var titleOf = (text) => /^\s*</.test(text) ? void 0 : text.trim().slice(0, 120) || void 0;
579
- var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
967
+ var sleep = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
580
968
  var backoffMs = (attempt) => Math.min(3e4, 1e3 * 2 ** attempt);
581
969
  function skyDir() {
582
- return process.env.SKY_CONFIG_DIR ?? join2(homedir3(), ".config", "sky");
970
+ return process.env.SKY_CONFIG_DIR ?? join4(homedir4(), ".config", "sky");
583
971
  }
584
972
  function syncConfigPath() {
585
- return join2(skyDir(), "trace-sync.json");
973
+ return join4(skyDir(), "trace-sync.json");
586
974
  }
587
975
  function resultsStatePath() {
588
- return join2(skyDir(), "session-results.json");
976
+ return join4(skyDir(), "session-results.json");
589
977
  }
590
- function statePath() {
591
- return join2(skyDir(), "trace-sync-state.json");
978
+ function statePath2() {
979
+ return join4(skyDir(), "trace-sync-state.json");
592
980
  }
593
- function readJson(path, fallback) {
981
+ function readJson2(path, fallback) {
594
982
  try {
595
- return JSON.parse(readFileSync2(path, "utf8"));
983
+ return JSON.parse(readFileSync4(path, "utf8"));
596
984
  } catch {
597
985
  return fallback;
598
986
  }
599
987
  }
600
988
  function writeJson(path, value) {
601
- mkdirSync(dirname3(path), { recursive: true });
602
- writeFileSync(path, `${JSON.stringify(value, null, 2)}
989
+ mkdirSync2(dirname5(path), { recursive: true });
990
+ writeFileSync2(path, `${JSON.stringify(value, null, 2)}
603
991
  `, { mode: 384 });
604
992
  }
993
+ function lastUploads() {
994
+ const last = {};
995
+ for (const [key, file] of Object.entries(readJson2(statePath2(), { sessions: {} }).sessions)) {
996
+ if (!file.workspace) continue;
997
+ const harness = key.slice(0, key.indexOf(":"));
998
+ if (!last[harness] || file.at > last[harness]) last[harness] = file.at;
999
+ }
1000
+ return last;
1001
+ }
605
1002
  function loadSyncConfig() {
606
- return readJson(syncConfigPath(), { enabled: false, rules: [] });
1003
+ return readJson2(syncConfigPath(), { enabled: false, rules: [] });
607
1004
  }
608
1005
  function saveSyncConfig(config) {
609
1006
  writeJson(syncConfigPath(), config);
610
1007
  }
611
1008
  function claudeRoot() {
612
- return join2(process.env.CLAUDE_CONFIG_DIR ?? join2(homedir3(), ".claude"), "projects");
1009
+ return join4(process.env.CLAUDE_CONFIG_DIR ?? join4(homedir4(), ".claude"), "projects");
613
1010
  }
614
1011
  function codexRoot() {
615
- return process.env.CODEX_HOME ?? join2(homedir3(), ".codex");
1012
+ return process.env.CODEX_HOME ?? join4(homedir4(), ".codex");
616
1013
  }
617
1014
  var SKY_PARSED = /* @__PURE__ */ new Set(["claude-code", "codex"]);
618
1015
  var COLLECTOR_HARNESS = { "claude-code": "claude_code", codex: "codex" };
619
1016
  var collectorModules;
620
1017
  async function traceCollector() {
621
- const dir = join2(dirname3(fileURLToPath(import.meta.url)), "..", "vendor", "trace-collect");
1018
+ const dir = join4(dirname5(fileURLToPath(import.meta.url)), "..", "vendor", "trace-collect");
622
1019
  collectorModules ??= Promise.all([
623
- import(pathToFileURL(join2(dir, "collect.mjs")).href),
624
- import(pathToFileURL(join2(dir, "sinks", "agentsky.mjs")).href)
1020
+ import(pathToFileURL(join4(dir, "collect.mjs")).href),
1021
+ import(pathToFileURL(join4(dir, "sinks", "agentsky.mjs")).href)
625
1022
  ]).then(([collector, sink]) => ({ collector, sink }));
626
1023
  return collectorModules;
627
1024
  }
@@ -631,7 +1028,7 @@ function collectorHarness(harness) {
631
1028
  async function sourceFolders() {
632
1029
  const { collector } = await traceCollector();
633
1030
  const others = (await collector.describeSources()).filter((source) => !SKY_PARSED.has(source.id)).flatMap((source) => source.found);
634
- return [claudeRoot(), join2(codexRoot(), "sessions"), join2(codexRoot(), "archived_sessions"), ...others, collector.STORE];
1031
+ return [claudeRoot(), join4(codexRoot(), "sessions"), join4(codexRoot(), "archived_sessions"), ...others, collector.STORE];
635
1032
  }
636
1033
  async function supportedAgents() {
637
1034
  const { collector } = await traceCollector();
@@ -647,7 +1044,7 @@ function signatureOf(files) {
647
1044
  const parts = [];
648
1045
  for (const file of files) {
649
1046
  try {
650
- const stat = statSync2(file);
1047
+ const stat = statSync4(file);
651
1048
  parts.push(`${file}:${stat.size}:${Math.floor(stat.mtimeMs)}`);
652
1049
  } catch {
653
1050
  return null;
@@ -660,25 +1057,25 @@ function claudeSessions() {
660
1057
  const found = [];
661
1058
  let projects;
662
1059
  try {
663
- projects = readdirSync(root);
1060
+ projects = readdirSync2(root);
664
1061
  } catch {
665
1062
  return found;
666
1063
  }
667
1064
  for (const project of projects) {
668
- const dir = join2(root, project);
1065
+ const dir = join4(root, project);
669
1066
  let entries;
670
1067
  try {
671
- entries = readdirSync(dir);
1068
+ entries = readdirSync2(dir);
672
1069
  } catch {
673
1070
  continue;
674
1071
  }
675
1072
  for (const entry of entries) {
676
1073
  if (!entry.endsWith(".jsonl")) continue;
677
1074
  const sessionId = entry.slice(0, -".jsonl".length);
678
- const files = [join2(dir, entry)];
679
- const subagents = join2(dir, sessionId, "subagents");
1075
+ const files = [join4(dir, entry)];
1076
+ const subagents = join4(dir, sessionId, "subagents");
680
1077
  try {
681
- files.push(...readdirSync(subagents).filter((name) => name.endsWith(".jsonl")).sort().map((name) => join2(subagents, name)));
1078
+ files.push(...readdirSync2(subagents).filter((name) => name.endsWith(".jsonl")).sort().map((name) => join4(subagents, name)));
682
1079
  } catch {
683
1080
  }
684
1081
  const signature = signatureOf(files);
@@ -703,21 +1100,21 @@ async function firstLine(file) {
703
1100
  return "";
704
1101
  }
705
1102
  function codexIdCachePath() {
706
- return join2(skyDir(), "trace-sync-codex-ids.json");
1103
+ return join4(skyDir(), "trace-sync-codex-ids.json");
707
1104
  }
708
1105
  async function codexSessions() {
709
1106
  const byId = /* @__PURE__ */ new Map();
710
- const cached = readJson(codexIdCachePath(), {});
1107
+ const cached = readJson2(codexIdCachePath(), {});
711
1108
  const seen = {};
712
1109
  const walk = async (dir) => {
713
1110
  let entries;
714
1111
  try {
715
- entries = readdirSync(dir, { withFileTypes: true });
1112
+ entries = readdirSync2(dir, { withFileTypes: true });
716
1113
  } catch {
717
1114
  return;
718
1115
  }
719
1116
  for (const entry of entries) {
720
- const full = join2(dir, entry.name);
1117
+ const full = join4(dir, entry.name);
721
1118
  if (entry.isDirectory()) {
722
1119
  await walk(full);
723
1120
  continue;
@@ -736,13 +1133,13 @@ async function codexSessions() {
736
1133
  }
737
1134
  if (!id) continue;
738
1135
  seen[full] = { signature, id };
739
- const mtime = statSync2(full).mtimeMs;
1136
+ const mtime = statSync4(full).mtimeMs;
740
1137
  const known = byId.get(id);
741
1138
  if (!known || mtime > known.mtime) byId.set(id, { harness: "codex", sessionId: id, files: [full], signature, mtime });
742
1139
  }
743
1140
  };
744
- await walk(join2(codexRoot(), "sessions"));
745
- await walk(join2(codexRoot(), "archived_sessions"));
1141
+ await walk(join4(codexRoot(), "sessions"));
1142
+ await walk(join4(codexRoot(), "archived_sessions"));
746
1143
  try {
747
1144
  writeJson(codexIdCachePath(), seen);
748
1145
  } catch {
@@ -751,12 +1148,12 @@ async function codexSessions() {
751
1148
  }
752
1149
  function claudeSessionAt(path) {
753
1150
  const root = claudeRoot();
754
- if (!path.startsWith(`${root}${sep2}`) || !path.endsWith(".jsonl") || basename2(dirname3(dirname3(path))) !== basename2(root)) return null;
755
- const sessionId = basename2(path, ".jsonl");
1151
+ if (!path.startsWith(`${root}${sep3}`) || !path.endsWith(".jsonl") || basename4(dirname5(dirname5(path))) !== basename4(root)) return null;
1152
+ const sessionId = basename4(path, ".jsonl");
756
1153
  const files = [path];
757
- const subagents = join2(dirname3(path), sessionId, "subagents");
1154
+ const subagents = join4(dirname5(path), sessionId, "subagents");
758
1155
  try {
759
- files.push(...readdirSync(subagents).filter((name) => name.endsWith(".jsonl")).sort().map((name) => join2(subagents, name)));
1156
+ files.push(...readdirSync2(subagents).filter((name) => name.endsWith(".jsonl")).sort().map((name) => join4(subagents, name)));
760
1157
  } catch {
761
1158
  }
762
1159
  const signature = signatureOf(files);
@@ -993,13 +1390,13 @@ function isTrivial(session) {
993
1390
  return session.toolCalls === 0 && session.messages.length <= 2 && chars < 200;
994
1391
  }
995
1392
  function sessionDigest(session) {
996
- const hash = createHash2("sha256");
1393
+ const hash = createHash3("sha256");
997
1394
  hash.update(`${session.cwd ?? ""}${session.model ?? ""}`);
998
1395
  for (const message of session.messages) hash.update(`${message.role}\0${message.text}`);
999
1396
  return hash.digest("hex");
1000
1397
  }
1001
1398
  function projectOf(cwd) {
1002
- const parts = cwd.split(sep2).filter(Boolean);
1399
+ const parts = cwd.split(sep3).filter(Boolean);
1003
1400
  for (const marker of [".worktrees", "worktrees"]) {
1004
1401
  const at = parts.lastIndexOf(marker);
1005
1402
  if (at > 0) {
@@ -1008,52 +1405,52 @@ function projectOf(cwd) {
1008
1405
  }
1009
1406
  }
1010
1407
  let dir = cwd;
1011
- while (dir && dir !== dirname3(dir)) {
1012
- if (existsSync2(join2(dir, ".git"))) return basename2(dir);
1013
- dir = dirname3(dir);
1408
+ while (dir && dir !== dirname5(dir)) {
1409
+ if (existsSync3(join4(dir, ".git"))) return basename4(dir);
1410
+ dir = dirname5(dir);
1014
1411
  }
1015
1412
  return parts.at(-1);
1016
1413
  }
1017
1414
  function workspaceFile(cwd) {
1018
1415
  let dir = cwd;
1019
- while (dir && dir !== dirname3(dir)) {
1020
- const file = join2(dir, ".agentsky.json");
1021
- if (existsSync2(file)) {
1022
- const workspace = str2(readJson(file, {}).workspace);
1416
+ while (dir && dir !== dirname5(dir)) {
1417
+ const file = join4(dir, ".agentsky.json");
1418
+ if (existsSync3(file)) {
1419
+ const workspace = str2(readJson2(file, {}).workspace);
1023
1420
  if (workspace) return workspace;
1024
1421
  }
1025
- if (existsSync2(join2(dir, ".git"))) return void 0;
1026
- dir = dirname3(dir);
1422
+ if (existsSync3(join4(dir, ".git"))) return void 0;
1423
+ dir = dirname5(dir);
1027
1424
  }
1028
1425
  return void 0;
1029
1426
  }
1030
1427
  function gitConfigPath(root) {
1031
- const dotGit = join2(root, ".git");
1428
+ const dotGit = join4(root, ".git");
1032
1429
  try {
1033
- if (statSync2(dotGit).isDirectory()) return join2(dotGit, "config");
1034
- const pointer = readFileSync2(dotGit, "utf8").match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();
1430
+ if (statSync4(dotGit).isDirectory()) return join4(dotGit, "config");
1431
+ const pointer = readFileSync4(dotGit, "utf8").match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();
1035
1432
  if (!pointer) return void 0;
1036
- const gitdir = pointer.startsWith("/") ? pointer : join2(root, pointer);
1037
- const common = existsSync2(join2(gitdir, "commondir")) ? readFileSync2(join2(gitdir, "commondir"), "utf8").trim() : ".";
1038
- return join2(common.startsWith("/") ? common : join2(gitdir, common), "config");
1433
+ const gitdir = pointer.startsWith("/") ? pointer : join4(root, pointer);
1434
+ const common = existsSync3(join4(gitdir, "commondir")) ? readFileSync4(join4(gitdir, "commondir"), "utf8").trim() : ".";
1435
+ return join4(common.startsWith("/") ? common : join4(gitdir, common), "config");
1039
1436
  } catch {
1040
1437
  return void 0;
1041
1438
  }
1042
1439
  }
1043
1440
  function repoRemote(cwd) {
1044
1441
  let dir = cwd;
1045
- while (dir && dir !== dirname3(dir)) {
1046
- if (existsSync2(join2(dir, ".git"))) {
1442
+ while (dir && dir !== dirname5(dir)) {
1443
+ if (existsSync3(join4(dir, ".git"))) {
1047
1444
  const config = gitConfigPath(dir);
1048
1445
  if (!config) return void 0;
1049
1446
  try {
1050
- const text = readFileSync2(config, "utf8");
1447
+ const text = readFileSync4(config, "utf8");
1051
1448
  return text.match(/\[remote "origin"\][^[]*?url\s*=\s*(\S+)/)?.[1];
1052
1449
  } catch {
1053
1450
  return void 0;
1054
1451
  }
1055
1452
  }
1056
- dir = dirname3(dir);
1453
+ dir = dirname5(dir);
1057
1454
  }
1058
1455
  return void 0;
1059
1456
  }
@@ -1070,8 +1467,8 @@ ${repoRemote(cwd) ?? ""}`.toLowerCase();
1070
1467
  }
1071
1468
  function homeLabel(path) {
1072
1469
  if (!path) return void 0;
1073
- const home = homedir3();
1074
- return path === home || path.startsWith(`${home}${sep2}`) ? `~${path.slice(home.length)}` : path;
1470
+ const home = homedir4();
1471
+ return path === home || path.startsWith(`${home}${sep3}`) ? `~${path.slice(home.length)}` : path;
1075
1472
  }
1076
1473
  async function libraryRequest(method, path, workspace, body, timeoutMs = 12e4) {
1077
1474
  const token = apiToken();
@@ -1143,16 +1540,23 @@ function uploadBody(session, sha256, device) {
1143
1540
  outside_conversation: session.conversation.flatMap((inside, index) => inside ? [] : [index])
1144
1541
  };
1145
1542
  }
1543
+ function spanOf(body) {
1544
+ const moment = (value) => typeof value === "string" && Number.isFinite(Date.parse(value)) ? value : null;
1545
+ return { started_at: moment(body.started_at), ended_at: moment(body.ended_at) };
1546
+ }
1547
+ function capturePaused(error) {
1548
+ return error instanceof ApiError && error.status === 423 && error.code === "timeline_paused";
1549
+ }
1146
1550
  function lockPath() {
1147
- return join2(skyDir(), "trace-sync.lock");
1551
+ return join4(skyDir(), "trace-sync.lock");
1148
1552
  }
1149
1553
  function takeLock() {
1150
1554
  const path = lockPath();
1151
- mkdirSync(skyDir(), { recursive: true });
1555
+ mkdirSync2(skyDir(), { recursive: true });
1152
1556
  try {
1153
- mkdirSync(path);
1557
+ mkdirSync2(path);
1154
1558
  } catch {
1155
- const pid = Number(readJson(join2(path, "pid.json"), {}).pid);
1559
+ const pid = Number(readJson2(join4(path, "pid.json"), {}).pid);
1156
1560
  let alive = false;
1157
1561
  try {
1158
1562
  if (pid) {
@@ -1163,18 +1567,18 @@ function takeLock() {
1163
1567
  alive = false;
1164
1568
  }
1165
1569
  if (alive) return false;
1166
- rmSync(path, { recursive: true, force: true });
1570
+ rmSync2(path, { recursive: true, force: true });
1167
1571
  try {
1168
- mkdirSync(path);
1572
+ mkdirSync2(path);
1169
1573
  } catch {
1170
1574
  return false;
1171
1575
  }
1172
1576
  }
1173
- writeJson(join2(path, "pid.json"), { pid: process.pid });
1577
+ writeJson(join4(path, "pid.json"), { pid: process.pid });
1174
1578
  return true;
1175
1579
  }
1176
1580
  function releaseLock() {
1177
- rmSync(lockPath(), { recursive: true, force: true });
1581
+ rmSync2(lockPath(), { recursive: true, force: true });
1178
1582
  }
1179
1583
  async function pool(items, size, fn) {
1180
1584
  let next = 0;
@@ -1204,7 +1608,7 @@ async function verifyPendingFile(item, source) {
1204
1608
  response = await fetch(url, { redirect: "manual", headers: { "user-agent": USER_AGENT } });
1205
1609
  }
1206
1610
  if (!response.ok || !response.body) throw new Error(`Cannot verify stored source file (${response.status}).`);
1207
- const hash = createHash2("sha256");
1611
+ const hash = createHash3("sha256");
1208
1612
  let bytes = 0;
1209
1613
  const reader = response.body.getReader();
1210
1614
  try {
@@ -1220,15 +1624,15 @@ async function verifyPendingFile(item, source) {
1220
1624
  if (bytes !== source.bytes || hash.digest("hex") !== source.sha256) throw new Error("Stored source file does not match the pending archive; retained for retry.");
1221
1625
  }
1222
1626
  async function runSync(config, options) {
1223
- const state = readJson(statePath(), { sessions: {} });
1627
+ const state = readJson2(statePath2(), { sessions: {} });
1224
1628
  const full = options.full || !state.lastFullAt || Date.now() - Date.parse(state.lastFullAt) > FULL_SWEEP_MS;
1225
1629
  const device = config.device ?? hostname();
1226
- const report = { scanned: 0, changed: 0, uploaded: 0, unchanged: 0, local: 0, owned: 0, empty: 0, sessions: 0, excluded: 0, failed: 0, results: 0, legacySources: 0, byWorkspace: {}, errors: [] };
1227
- const results = readJson(resultsStatePath(), { read: [], saved: [] });
1630
+ const report = { scanned: 0, changed: 0, uploaded: 0, unchanged: 0, local: 0, owned: 0, empty: 0, sessions: 0, excluded: 0, paused: 0, failed: 0, results: 0, legacySources: 0, byWorkspace: {}, errors: [] };
1631
+ const results = readJson2(resultsStatePath(), { read: [], saved: [] });
1228
1632
  const saveResults = async (local, workspace, sessionId, cwd) => {
1229
1633
  if (!sessionHarness(local.harness)) return;
1230
1634
  try {
1231
- report.results += (await captureSessionResults({ harness: local.harness, nativeId: local.sessionId, sessionId, workspace, files: local.files, cwd: cwd?.replace(/^~(?=\/|$)/, homedir3()) }, results)).saved;
1635
+ report.results += (await captureSessionResults({ harness: local.harness, nativeId: local.sessionId, sessionId, workspace, files: local.files, cwd: cwd?.replace(/^~(?=\/|$)/, homedir4()) }, results)).saved;
1232
1636
  } catch (error) {
1233
1637
  (results.tries ??= {})[key(local)] = (results.tries[key(local)] ?? 0) + 1;
1234
1638
  report.errors.push(`${key(local)} \u2192 ${workspace}: results not saved yet: ${error.message}`);
@@ -1254,11 +1658,11 @@ async function runSync(config, options) {
1254
1658
  return true;
1255
1659
  };
1256
1660
  try {
1257
- report.legacySources = readdirSync(join2(skyDir(), "trace-sources")).filter((name) => /^[a-f0-9]{64}\.jsonl$/.test(name)).length;
1661
+ report.legacySources = readdirSync2(join4(skyDir(), "trace-sources")).filter((name) => /^[a-f0-9]{64}\.jsonl$/.test(name)).length;
1258
1662
  } catch {
1259
1663
  }
1260
1664
  if (report.legacySources) options.onProgress?.(`${report.legacySources} unbound legacy source archives remain local; they are not uploaded or removed.`);
1261
- const queueRoot = join2(skyDir(), "trace-pending");
1665
+ const queueRoot = join4(skyDir(), "trace-pending");
1262
1666
  const endpoint = canonicalSourceApiBase(apiBase());
1263
1667
  const restored = /* @__PURE__ */ new Map();
1264
1668
  let blocked = false;
@@ -1267,13 +1671,41 @@ async function runSync(config, options) {
1267
1671
  const collectorFailed = (error) => fail("other agents: unreadable", error);
1268
1672
  let discovered;
1269
1673
  const discover = async () => discovered ??= await discoverSessions(collectorFailed);
1674
+ const dropPaused = (item, local, workspace) => {
1675
+ report.paused++;
1676
+ record(local, { workspace, status: "paused" });
1677
+ writePrivateJson(statePath2(), state);
1678
+ removePendingSource(item);
1679
+ restored.set(key(local), local.signature);
1680
+ };
1681
+ const sendAcrossPause = async (item, local, workspace, sha256) => {
1682
+ const { work_objects: _objects, outside_conversation: outside, title: _title, ...previewBody } = item.manifest.body;
1683
+ const saved = await libraryRequest("PUT", `/trace-library/${local.harness}/${encodeURIComponent(local.sessionId)}`, workspace, { ...previewBody, sha256 });
1684
+ if (saved.status !== "withheld" && config.sessions !== false && sessionHarness(local.harness)) {
1685
+ const body = previewBody;
1686
+ const left = new Set(outside ?? []);
1687
+ const session = await saveTraceSession(libraryRequest, {
1688
+ harness: local.harness,
1689
+ sessionId: local.sessionId,
1690
+ workspace,
1691
+ body: { ...body, messages: body.messages.filter((_, index) => !left.has(index)) },
1692
+ skills: loadLocalSkillState()
1693
+ });
1694
+ if (session.status === "saved") report.sessions++;
1695
+ }
1696
+ if (!results.read.includes(key(local))) {
1697
+ results.read.push(key(local));
1698
+ writePrivateJson(resultsStatePath(), results);
1699
+ }
1700
+ dropPaused(item, local, workspace);
1701
+ };
1270
1702
  const send = async (item) => {
1271
1703
  const { workspace } = item.manifest;
1272
1704
  let capturing = false;
1273
1705
  let { local } = item.manifest;
1274
1706
  const queuedCwd = typeof item.manifest.body.cwd === "string" ? item.manifest.body.cwd : void 0;
1275
1707
  if (leftOut(local, queuedCwd)) {
1276
- writePrivateJson(statePath(), state);
1708
+ writePrivateJson(statePath2(), state);
1277
1709
  removePendingSource(item);
1278
1710
  restored.set(key(local), local.signature);
1279
1711
  return;
@@ -1302,12 +1734,16 @@ async function runSync(config, options) {
1302
1734
  }
1303
1735
  if (item.manifest.stage !== "ready") completePendingCapture(item, source);
1304
1736
  const statuses = await libraryRequest("POST", "/trace-library/check", workspace, {
1305
- sessions: [{ harness: local.harness, session_id: local.sessionId, sha256: source.sha256 }]
1737
+ sessions: [{ harness: local.harness, session_id: local.sessionId, sha256: source.sha256, span: spanOf(item.manifest.body) }]
1306
1738
  });
1307
1739
  if (statuses.sessions[0]?.status === "owned") {
1308
1740
  report.owned++;
1309
1741
  throw new Error("Another member owns this source; pending archive retained.");
1310
1742
  }
1743
+ if (statuses.sessions[0]?.status === "paused") {
1744
+ await sendAcrossPause(item, local, workspace, source.sha256);
1745
+ return;
1746
+ }
1311
1747
  if (item.manifest.fileId) await verifyPendingFile(item, source);
1312
1748
  else {
1313
1749
  const file = await uploadLargeFile(source.path, "application/x-ndjson", void 0, () => {
@@ -1336,7 +1772,7 @@ async function runSync(config, options) {
1336
1772
  const saved = await libraryRequest("PUT", `/trace-library/${local.harness}/${encodeURIComponent(local.sessionId)}`, workspace, { ...previewBody, sha256: source.sha256 });
1337
1773
  savePendingSource(item, { previewSaved: true, link: saved.linked_task ?? null });
1338
1774
  const link = item.manifest.link;
1339
- const linkKey = createHash2("sha256").update(JSON.stringify(link ?? null)).digest("hex").slice(0, 16);
1775
+ const linkKey = createHash3("sha256").update(JSON.stringify(link ?? null)).digest("hex").slice(0, 16);
1340
1776
  await libraryRequest("POST", "/events", workspace, { events: [{
1341
1777
  idempotency_key: `trace-source:${source.sha256}:${linkKey}`,
1342
1778
  ...link ? { session_id: link.session_id, task_id: link.task_id } : {},
@@ -1360,12 +1796,16 @@ async function runSync(config, options) {
1360
1796
  bodies: [{ role: "transcript", media_type: "application/x-ndjson", file_id: item.manifest.fileId, complete: source.complete }]
1361
1797
  }] });
1362
1798
  record(local, { workspace, sha256: source.sha256, status: source.complete ? "stored" : "stored_with_gaps" });
1363
- writePrivateJson(statePath(), state);
1799
+ writePrivateJson(statePath2(), state);
1364
1800
  removePendingSource(item);
1365
1801
  restored.set(key(local), local.signature);
1366
1802
  report.uploaded++;
1367
1803
  report.byWorkspace[workspace] = (report.byWorkspace[workspace] ?? 0) + 1;
1368
1804
  } catch (error) {
1805
+ if (!capturing && capturePaused(error)) {
1806
+ dropPaused(item, local, workspace);
1807
+ return;
1808
+ }
1369
1809
  if (capturing) unreadable.add(key(local));
1370
1810
  else blocked = true;
1371
1811
  fail(`${key(local)} \u2192 ${workspace}`, error);
@@ -1392,7 +1832,7 @@ async function runSync(config, options) {
1392
1832
  const lifted = (s) => state.sessions[key(s)]?.status === "excluded" && !stillExcluded(exclusions, state.sessions[key(s)]?.excludedBy ?? "");
1393
1833
  const awaitingResults = (s) => config.sessions !== false && sessionHarness(s.harness) && !results.read.includes(key(s)) && ["stored", "stored_with_gaps"].includes(state.sessions[key(s)]?.status ?? "") && (results.tries?.[key(s)] ?? 0) < RESULTS_TRIES && s.files.some((file) => {
1394
1834
  try {
1395
- return Date.now() - statSync2(file).mtimeMs < RESULTS_BACKFILL_MS;
1835
+ return Date.now() - statSync4(file).mtimeMs < RESULTS_BACKFILL_MS;
1396
1836
  } catch {
1397
1837
  return false;
1398
1838
  }
@@ -1429,10 +1869,14 @@ async function runSync(config, options) {
1429
1869
  const prepared = await prepare(local);
1430
1870
  if (!prepared) return;
1431
1871
  if (options.dryRun) {
1432
- const directory = mkdtempSync(join2(skyDir(), "trace-dry-run-"));
1872
+ const directory = mkdtempSync(join4(skyDir(), "trace-dry-run-"));
1433
1873
  try {
1434
1874
  const source2 = await captureTraceSource(local, directory, { workspace: prepared.workspace, apiBase: endpoint });
1435
- const checked = await libraryRequest("POST", "/trace-library/check", prepared.workspace, { sessions: [{ harness: local.harness, session_id: local.sessionId, sha256: source2.sha256 }] });
1875
+ const checked = await libraryRequest("POST", "/trace-library/check", prepared.workspace, { sessions: [{ harness: local.harness, session_id: local.sessionId, sha256: source2.sha256, span: spanOf(prepared.body) }] });
1876
+ if (checked.sessions[0]?.status === "paused") {
1877
+ report.paused++;
1878
+ return;
1879
+ }
1436
1880
  if (checked.sessions[0]?.status === "owned") {
1437
1881
  report.owned++;
1438
1882
  return;
@@ -1440,7 +1884,7 @@ async function runSync(config, options) {
1440
1884
  report.uploaded++;
1441
1885
  report.byWorkspace[prepared.workspace] = (report.byWorkspace[prepared.workspace] ?? 0) + 1;
1442
1886
  } finally {
1443
- rmSync(directory, { recursive: true, force: true });
1887
+ rmSync2(directory, { recursive: true, force: true });
1444
1888
  }
1445
1889
  return;
1446
1890
  }
@@ -1454,7 +1898,8 @@ async function runSync(config, options) {
1454
1898
  completePendingCapture(item, source);
1455
1899
  ready.push(item);
1456
1900
  } catch (error) {
1457
- fail(`${key(local)}: source capture failed`, error);
1901
+ if (capturePaused(error)) report.paused++;
1902
+ else fail(`${key(local)}: source capture failed`, error);
1458
1903
  }
1459
1904
  });
1460
1905
  await pool(ready, UPLOAD_CONCURRENCY, send);
@@ -1463,7 +1908,7 @@ async function runSync(config, options) {
1463
1908
  }
1464
1909
  if (!options.dryRun) {
1465
1910
  if (full && !options.only?.length && !options.limit && report.failed === 0) state.lastFullAt = (/* @__PURE__ */ new Date()).toISOString();
1466
- writePrivateJson(statePath(), state);
1911
+ writePrivateJson(statePath2(), state);
1467
1912
  }
1468
1913
  return report;
1469
1914
  }
@@ -1476,8 +1921,8 @@ function hookSessionRef(payload) {
1476
1921
  }
1477
1922
  }
1478
1923
  var LAUNCHD_LABEL = "dev.agentsky.trace-sync";
1479
- function launchdPlistPath(home = homedir3()) {
1480
- return join2(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
1924
+ function launchdPlistPath(home = homedir4()) {
1925
+ return join4(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
1481
1926
  }
1482
1927
  function launchdPlist(command, logPath) {
1483
1928
  const escape = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
@@ -1502,25 +1947,25 @@ ${command.map((part) => ` <string>${escape(part)}</string>`).join("\n")}
1502
1947
  function installLaunchd(command, logPath) {
1503
1948
  if (process.platform !== "darwin") throw new Error("the schedule installer covers macOS; on Linux add `*/15 * * * * sky trace sync --quiet` to your crontab");
1504
1949
  const plist = launchdPlistPath();
1505
- mkdirSync(dirname3(plist), { recursive: true });
1506
- writeFileSync(plist, launchdPlist(command, logPath));
1950
+ mkdirSync2(dirname5(plist), { recursive: true });
1951
+ writeFileSync2(plist, launchdPlist(command, logPath));
1507
1952
  return plist;
1508
1953
  }
1509
1954
  var SYNC_HOOK_COMMAND = "sky trace sync --hook";
1510
- function installSyncHooks(home = homedir3(), codexHome = process.env.CODEX_HOME || join2(home, ".codex")) {
1955
+ function installSyncHooks(home = homedir4(), codexHome = process.env.CODEX_HOME || join4(home, ".codex")) {
1511
1956
  const lines = [];
1512
- const claudeSettings = join2(home, ".claude", "settings.json");
1957
+ const claudeSettings = join4(home, ".claude", "settings.json");
1513
1958
  installClaudeHooks(claudeSettings, SYNC_HOOK_COMMAND, { Stop: [{ hooks: [{ type: "command", command: SYNC_HOOK_COMMAND, timeout: 10 }] }] });
1514
1959
  lines.push(`Claude Code: syncs at the end of every turn (${claudeSettings}).`);
1515
- const codexConfig = join2(codexHome, "config.toml");
1516
- const text = existsSync2(codexConfig) ? readFileSync2(codexConfig, "utf8") : "";
1960
+ const codexConfig = join4(codexHome, "config.toml");
1961
+ const text = existsSync3(codexConfig) ? readFileSync4(codexConfig, "utf8") : "";
1517
1962
  const topLevel = text.split(/^\s*\[/m, 1)[0] ?? "";
1518
1963
  const notify = /^\s*notify\s*=.*$/m.exec(topLevel)?.[0];
1519
1964
  if (notify && !notify.includes("trace")) lines.push(`Codex: left as it is, because ${codexConfig} already has ${notify.trim()}; the 15-minute schedule (--install-schedule) still picks its sessions up.`);
1520
1965
  else if (notify) lines.push(`Codex: already syncs at the end of every turn (${codexConfig}).`);
1521
1966
  else {
1522
- mkdirSync(dirname3(codexConfig), { recursive: true });
1523
- writeFileSync(codexConfig, `notify = ["sky", "trace", "sync", "--hook"]
1967
+ mkdirSync2(dirname5(codexConfig), { recursive: true });
1968
+ writeFileSync2(codexConfig, `notify = ["sky", "trace", "sync", "--hook"]
1524
1969
  ${text}`);
1525
1970
  lines.push(`Codex: syncs at the end of every turn (${codexConfig}).`);
1526
1971
  }
@@ -1529,31 +1974,46 @@ ${text}`);
1529
1974
  function syncDir() {
1530
1975
  return skyDir();
1531
1976
  }
1977
+
1532
1978
  export {
1533
- LAUNCHD_LABEL,
1534
- SYNC_HOOK_COMMAND,
1535
- collectorBody,
1979
+ importReadAllowed,
1980
+ importPathAllowed,
1981
+ repositoryRoot,
1982
+ sharedInstructionPaths,
1983
+ loadedSkills,
1984
+ workspaceState,
1985
+ skillFiles,
1986
+ codexThreadName,
1987
+ SINGLE_REQUEST_MAX_BYTES,
1988
+ transfer,
1989
+ uploadLargeFile,
1990
+ syncConfigPath,
1991
+ lastUploads,
1992
+ loadSyncConfig,
1993
+ saveSyncConfig,
1536
1994
  collectorHarness,
1537
- discoverSessions,
1538
- hookSessionRef,
1995
+ sourceFolders,
1996
+ supportedAgents,
1539
1997
  importExport,
1540
- installLaunchd,
1541
- installSyncHooks,
1542
- isTrivial,
1543
- launchdPlist,
1544
- launchdPlistPath,
1545
- libraryRequest,
1546
- loadSyncConfig,
1998
+ discoverSessions,
1999
+ collectorBody,
1547
2000
  parseClaudeSession,
1548
2001
  parseCodexSession,
2002
+ isTrivial,
2003
+ sessionDigest,
1549
2004
  projectOf,
1550
2005
  repoRemote,
1551
2006
  routeSession,
1552
- saveSyncConfig,
1553
- sessionDigest,
1554
- sourceFolders,
1555
- supportedAgents,
1556
- syncConfigPath,
1557
- syncDir,
1558
- syncTraces
2007
+ libraryRequest,
2008
+ spanOf,
2009
+ capturePaused,
2010
+ syncTraces,
2011
+ hookSessionRef,
2012
+ LAUNCHD_LABEL,
2013
+ launchdPlistPath,
2014
+ launchdPlist,
2015
+ installLaunchd,
2016
+ SYNC_HOOK_COMMAND,
2017
+ installSyncHooks,
2018
+ syncDir
1559
2019
  };