@agentsky/sky 3.42.0 → 3.44.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.
@@ -0,0 +1,1969 @@
1
+ import {
2
+ installClaudeHooks
3
+ } from "./chunk-KTSUD2BU.js";
4
+ import {
5
+ IncompleteSourceCaptureError,
6
+ SOURCE_CAPTURE_VERSION,
7
+ beginPendingSource,
8
+ canonicalSourceApiBase,
9
+ captureTraceSource,
10
+ completePendingCapture,
11
+ excludedBy,
12
+ listPendingSources,
13
+ loadExclusions,
14
+ recoverPendingSource,
15
+ removePendingSource,
16
+ savePendingSource,
17
+ stillExcluded,
18
+ writePrivateJson
19
+ } from "./chunk-UJ7IXSJX.js";
20
+ import {
21
+ SessionSourceCollector,
22
+ publicRemote,
23
+ redactTraceText
24
+ } from "./chunk-BIZJ4VZL.js";
25
+ import {
26
+ ApiError,
27
+ api
28
+ } from "./chunk-W2WEEVIM.js";
29
+ import {
30
+ loadLocalSkillState,
31
+ revisionAt
32
+ } from "./chunk-ZVNQJPMS.js";
33
+ import {
34
+ USER_AGENT
35
+ } from "./chunk-CXRMG3HQ.js";
36
+ import {
37
+ apiBase,
38
+ apiToken,
39
+ configPath
40
+ } from "./chunk-XHZJG3QT.js";
41
+
42
+ // src/trace-library.ts
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";
45
+ import { createInterface } from "readline";
46
+ import { homedir as homedir4, hostname } from "os";
47
+ import { basename as basename4, dirname as dirname5, join as join4, sep as sep3 } from "path";
48
+ import { fileURLToPath, pathToFileURL } from "url";
49
+ import { createGunzip } from "zlib";
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
+
153
+ // src/trace-references.ts
154
+ import { execFileSync } from "child_process";
155
+ import { existsSync } from "fs";
156
+ import { homedir } from "os";
157
+ import { dirname as dirname2 } from "path";
158
+ var PULL_URL = /github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/([1-9][0-9]{0,8})/g;
159
+ var GMAIL_ID = /(?:message_?id|thread_?id)\\*"?\s*[:=]\s*\\*"?([0-9a-f]{16})\b/gi;
160
+ var GMAIL_PATH = /(?:\/messages\/|\/threads\/|mail\.google\.com\/[^\s"\\]*[#/])([0-9a-f]{16})\b/g;
161
+ var OPENS_PULL = /"(?:command|cmd|input|arguments)\\*"\s*:.*\bgh\s+pr\s+create\b/;
162
+ var RESULT_WINDOW = 8;
163
+ var MAX_PULLS = 80;
164
+ var MAX_GMAIL = 100;
165
+ var TraceReferences = class {
166
+ pulls = /* @__PURE__ */ new Map();
167
+ gmail = /* @__PURE__ */ new Set();
168
+ opening = 0;
169
+ scan(line) {
170
+ const awaiting = this.opening > 0;
171
+ if (awaiting) this.opening--;
172
+ let credited = false;
173
+ for (const match of line.matchAll(PULL_URL)) {
174
+ const id = `${match[1]}/${match[2]}#${match[3]}`.toLowerCase();
175
+ if (id.startsWith("owner/repo#")) continue;
176
+ if (awaiting && !credited) {
177
+ this.pulls.set(id, "authored");
178
+ credited = true;
179
+ this.opening = 0;
180
+ } else if (!this.pulls.has(id)) this.pulls.set(id, "referenced");
181
+ }
182
+ if (OPENS_PULL.test(line)) this.opening = RESULT_WINDOW;
183
+ if (/gmail|mail\.google\.com/i.test(line)) {
184
+ for (const match of line.matchAll(GMAIL_ID)) this.gmail.add(match[1].toLowerCase());
185
+ for (const match of line.matchAll(GMAIL_PATH)) this.gmail.add(match[1].toLowerCase());
186
+ }
187
+ }
188
+ objects() {
189
+ const pulls = [...this.pulls].sort((a, b) => Number(b[1] === "authored") - Number(a[1] === "authored")).slice(0, MAX_PULLS);
190
+ return [
191
+ ...pulls.map(([id, role]) => ({ type: "pr", id, role })),
192
+ ...[...this.gmail].slice(0, MAX_GMAIL).map((id) => ({ type: "gmail_message", id, role: "referenced" }))
193
+ ];
194
+ }
195
+ };
196
+ var remotes = /* @__PURE__ */ new Map();
197
+ function gitRemoteAt(cwd) {
198
+ if (!cwd) return void 0;
199
+ if (remotes.has(cwd)) return remotes.get(cwd);
200
+ let remote;
201
+ const home = homedir();
202
+ for (let folder = cwd; folder !== home && folder !== dirname2(folder); folder = dirname2(folder)) {
203
+ if (!existsSync(folder)) continue;
204
+ try {
205
+ remote = execFileSync("git", ["-C", folder, "remote", "get-url", "origin"], { encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"] }).trim() || void 0;
206
+ } catch {
207
+ remote = void 0;
208
+ }
209
+ break;
210
+ }
211
+ remotes.set(cwd, remote);
212
+ return remote;
213
+ }
214
+
215
+ // src/session-results.ts
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";
224
+ import { homedir as homedir2 } from "os";
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
509
+ var MAX_RESULT_BYTES = 15 * 1024 * 1024;
510
+ var RESULT_TYPES = {
511
+ ".mp4": "video/mp4",
512
+ ".mov": "video/quicktime",
513
+ ".webm": "video/webm",
514
+ ".m4v": "video/x-m4v",
515
+ ".mp3": "audio/mpeg",
516
+ ".wav": "audio/wav",
517
+ ".m4a": "audio/mp4",
518
+ ".aac": "audio/aac",
519
+ ".ogg": "audio/ogg",
520
+ ".flac": "audio/flac",
521
+ ".png": "image/png",
522
+ ".jpg": "image/jpeg",
523
+ ".jpeg": "image/jpeg",
524
+ ".gif": "image/gif",
525
+ ".webp": "image/webp",
526
+ ".svg": "image/svg+xml",
527
+ ".pdf": "application/pdf",
528
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
529
+ ".doc": "application/msword",
530
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
531
+ ".xls": "application/vnd.ms-excel",
532
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
533
+ ".ppt": "application/vnd.ms-powerpoint",
534
+ ".csv": "text/csv",
535
+ ".tsv": "text/tab-separated-values",
536
+ ".html": "text/html",
537
+ ".htm": "text/html",
538
+ ".md": "text/markdown",
539
+ ".markdown": "text/markdown",
540
+ ".txt": "text/plain",
541
+ ".json": "application/json"
542
+ };
543
+ var OTHER_TYPES = { ".css": "text/css", ".js": "text/javascript", ".zip": "application/zip", ".heic": "image/heic", ".pages": "application/vnd.apple.pages", ".numbers": "application/vnd.apple.numbers" };
544
+ var PUBLISHING_TOOLS = /* @__PURE__ */ new Set(["Artifact"]);
545
+ var SCRATCH_ROOTS = ["/tmp/", "/private/tmp/", "/var/folders/", "/private/var/folders/"];
546
+ var REBUILT = /* @__PURE__ */ new Set(["node_modules", ".git", ".venv", "venv", "__pycache__", ".next", ".nuxt", ".turbo", ".cache", "dist", "build", "out", "target", "DerivedData", "Library", ".Trash"]);
547
+ var PATH_LIKE = /(?:~\/|\.{1,2}\/|\/)?(?:[^\s'"`()<>|;&*?,:=]+\/)*[^\s'"`()<>|;&*?,:=/]+\.[A-Za-z0-9]{1,8}(?![A-Za-z0-9])/g;
548
+ var ATTACHED = /^Attached files:\n((?:- .+(?:\n|$))+)/m;
549
+ var LOCAL_REFERENCE = /(\s(?:src|href)\s*=\s*)(["'])([^"'<>]+)\2/gi;
550
+ var CODEX_CONTEXT = /^\s*(?:<environment_context>|<user_instructions>|<turn_aborted>|# AGENTS\.md instructions)/;
551
+ var obj = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
552
+ var str = (value) => typeof value === "string" ? value : "";
553
+ function typeOf(name, any) {
554
+ const ext = extname(name).toLowerCase();
555
+ return RESULT_TYPES[ext] ?? (any ? OTHER_TYPES[ext] ?? "application/octet-stream" : null);
556
+ }
557
+ function pictureOf(block) {
558
+ const source = obj(block.source);
559
+ if (block.type === "image" && source?.type === "base64" && typeof source.data === "string") return { mediaType: str(source.media_type) || "image/png", data: source.data };
560
+ const inline = block.type === "input_image" ? /^data:(image\/[a-z0-9.+-]+);base64,(.+)$/i.exec(str(block.image_url)) : null;
561
+ return inline ? { mediaType: inline[1], data: inline[2] } : null;
562
+ }
563
+ function turnsOf(records, cwd = "") {
564
+ const turns = [];
565
+ let context = cwd;
566
+ const start = (at, texts, pictures) => turns.push({ since: Date.parse(str(at)) || 0, texts, pictures, said: [], tools: [] });
567
+ for (const raw of records) {
568
+ const record = obj(raw);
569
+ if (!record) continue;
570
+ const payload = obj(record.payload);
571
+ if (record.type === "turn_context" || record.type === "session_meta") context = str(payload?.cwd) || context;
572
+ const here = str(record.cwd) || context;
573
+ const content = obj(record.message)?.content;
574
+ if (record.type === "user") {
575
+ const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content.map(obj).filter(Boolean) : [];
576
+ if (blocks.some((block) => block.type === "tool_result") || record.isMeta === true) continue;
577
+ const texts = blocks.filter((block) => block.type === "text").map((block) => str(block.text));
578
+ if (!texts.some((text) => text.trim()) && !blocks.some((block) => block.type === "image")) continue;
579
+ start(record.timestamp, texts, blocks.map(pictureOf).filter(Boolean));
580
+ continue;
581
+ }
582
+ if (record.type === "assistant" && Array.isArray(content)) {
583
+ const turn = turns.at(-1);
584
+ for (const block of content.map(obj)) {
585
+ if (!turn || !block) continue;
586
+ if (block.type === "text") turn.said.push(str(block.text));
587
+ if (block.type === "tool_use") turn.tools.push({ name: str(block.name), input: block.input, cwd: here });
588
+ }
589
+ continue;
590
+ }
591
+ if (record.type !== "response_item" || !payload) continue;
592
+ if (payload.type === "message") {
593
+ const blocks = Array.isArray(payload.content) ? payload.content.map(obj).filter(Boolean) : [];
594
+ const texts = blocks.filter((block) => block.type === "input_text" || block.type === "output_text" || block.type === "text").map((block) => str(block.text));
595
+ if (payload.role === "user") {
596
+ if (texts.every((text) => !text.trim() || CODEX_CONTEXT.test(text)) && !blocks.some((block) => block.type === "input_image")) continue;
597
+ start(record.timestamp, texts.filter((text) => !CODEX_CONTEXT.test(text)), blocks.map(pictureOf).filter(Boolean));
598
+ } else if (payload.role === "assistant") turns.at(-1)?.said.push(...texts);
599
+ continue;
600
+ }
601
+ if (payload.type === "function_call" || payload.type === "custom_tool_call" || payload.type === "local_shell_call") {
602
+ let input = payload.arguments ?? payload.input ?? payload.action ?? "";
603
+ if (typeof input === "string") {
604
+ try {
605
+ input = JSON.parse(input);
606
+ } catch {
607
+ }
608
+ }
609
+ turns.at(-1)?.tools.push({ name: str(payload.name), input, cwd: str(obj(input)?.workdir) || here });
610
+ }
611
+ }
612
+ return turns;
613
+ }
614
+ function strings2(value, into = []) {
615
+ if (typeof value === "string") into.push(value);
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);
618
+ return into;
619
+ }
620
+ function resolved(candidate, cwd, home) {
621
+ const text = candidate.replace(/^file:\/\//, "");
622
+ if (text.startsWith("~/")) return join3(home, text.slice(2));
623
+ if (isAbsolute(text)) return normalize(text);
624
+ return cwd ? resolve3(cwd, text) : null;
625
+ }
626
+ function credential(file) {
627
+ return !importPathAllowed(file);
628
+ }
629
+ function kept(file, home) {
630
+ const inHome = file.startsWith(`${home}/`);
631
+ if (!inHome && SCRATCH_ROOTS.some((root) => file.startsWith(root))) return false;
632
+ if (!importPathAllowed(file)) return false;
633
+ const relative2 = inHome ? file.slice(home.length + 1) : file.replace(/^\//, "");
634
+ return !relative2.split("/").slice(0, -1).some((part) => REBUILT.has(part));
635
+ }
636
+ function inWebProject(file, home, stat) {
637
+ for (let dir = dirname4(file); dir.startsWith(`${home}/`); dir = dirname4(dir)) {
638
+ try {
639
+ if (stat(join3(dir, "package.json")).isFile()) return true;
640
+ } catch {
641
+ }
642
+ }
643
+ return false;
644
+ }
645
+ function publishedPaths(tool) {
646
+ if (!PUBLISHING_TOOLS.has(tool.name)) return [];
647
+ const input = obj(tool.input) ?? {};
648
+ const files = obj(input.files) ? Object.values(input.files) : [];
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);
650
+ }
651
+ function sessionResults(records, options = {}) {
652
+ const home = options.home ?? homedir3();
653
+ const stat = options.stat ?? statSync3;
654
+ const turns = turnsOf(records, options.cwd ?? "");
655
+ const found = [];
656
+ for (const turn of options.all ? turns : turns.slice(-1)) {
657
+ const said = turn.said.join("\n");
658
+ if (!said.trim()) continue;
659
+ const seen = /* @__PURE__ */ new Set();
660
+ const add = (file, origin, mediaType, fresh) => {
661
+ if (seen.has(file)) return;
662
+ seen.add(file);
663
+ let info;
664
+ try {
665
+ info = stat(file);
666
+ } catch {
667
+ return;
668
+ }
669
+ if (!info.isFile() || info.size === 0 || info.size > MAX_RESULT_BYTES || fresh && !(info.mtimeMs >= turn.since - 1e3)) return;
670
+ found.push({ path: file, name: basename3(file), mediaType, size: info.size, mtimeMs: Math.floor(info.mtimeMs), origin });
671
+ };
672
+ turn.pictures.forEach((picture, index) => {
673
+ const data = Buffer.from(picture.data, "base64");
674
+ if (!data.length || data.length > MAX_RESULT_BYTES) return;
675
+ const ext = picture.mediaType.split("/")[1]?.replace("jpeg", "jpg").replace(/[^a-z0-9]/gi, "") || "png";
676
+ found.push({ name: `pasted-${new Date(turn.since || 0).toISOString().slice(0, 10)}-${index + 1}.${ext}`, mediaType: picture.mediaType, size: data.length, origin: "sent", data });
677
+ });
678
+ for (const line of (ATTACHED.exec(turn.texts.join("\n"))?.[1] ?? "").split("\n")) {
679
+ const file = line.replace(/^- /, "").trim();
680
+ if (isAbsolute(file) && !credential(normalize(file))) add(normalize(file), "sent", typeOf(file, true), false);
681
+ }
682
+ for (const tool of turn.tools) for (const raw of publishedPaths(tool)) {
683
+ const file = resolved(raw, tool.cwd, home);
684
+ if (file && !credential(file)) add(file, "published", typeOf(file, true), false);
685
+ }
686
+ const texts = [...turn.tools.flatMap((tool) => strings2(tool.input)), ...turn.said];
687
+ for (const text of texts) {
688
+ for (const match of text.matchAll(PATH_LIKE)) {
689
+ const tool = turn.tools.find((entry) => strings2(entry.input).includes(text));
690
+ const file = resolved(match[0], tool?.cwd ?? options.cwd ?? "", home);
691
+ if (!file || seen.has(file)) continue;
692
+ const name = basename3(file);
693
+ const mediaType = typeOf(name, false);
694
+ if (!mediaType || !said.includes(name) || !kept(file, home)) continue;
695
+ if (mediaType === "text/html" && inWebProject(file, home, stat)) continue;
696
+ add(file, "delivered", mediaType, true);
697
+ }
698
+ }
699
+ }
700
+ return found;
701
+ }
702
+ function pageWithImages(bytes, file, home = homedir3(), explicit = false) {
703
+ const html = bytes.toString("utf8");
704
+ const dir = dirname4(file);
705
+ const images = /* @__PURE__ */ new Map();
706
+ let total = bytes.length;
707
+ for (const match of html.matchAll(LOCAL_REFERENCE)) {
708
+ const reference = match[3].trim();
709
+ if (images.has(reference) || /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\/)/i.test(reference)) continue;
710
+ let target;
711
+ try {
712
+ target = resolve3(dir, decodeURI(reference.split(/[?#]/, 1)[0]));
713
+ } catch {
714
+ continue;
715
+ }
716
+ const mediaType = typeOf(target, false);
717
+ if (!mediaType?.startsWith("image/") || !(explicit ? target.startsWith(`${dir}${sep2}`) : kept(target, home))) continue;
718
+ let image;
719
+ try {
720
+ image = readFileSync3(target);
721
+ } catch {
722
+ continue;
723
+ }
724
+ const uri = `data:${mediaType};base64,${image.toString("base64")}`;
725
+ total += uri.length - reference.length;
726
+ if (total > MAX_RESULT_BYTES) return bytes;
727
+ images.set(reference, uri);
728
+ }
729
+ if (!images.size) return bytes;
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");
731
+ }
732
+ function resultRequestId(...parts) {
733
+ const hex = createHash2("sha256").update(JSON.stringify(parts)).digest("hex");
734
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
735
+ }
736
+ var RateLimited = class extends Error {
737
+ };
738
+ async function call(fetcher, method, path, workspace, body, multipart2) {
739
+ const token = apiToken();
740
+ if (!token) throw new Error("not logged in \u2014 run `sky auth login`");
741
+ const response = await fetcher(`${apiBase()}${path}`, {
742
+ method,
743
+ headers: { authorization: `Bearer ${token}`, "x-universe": workspace, ...multipart2 ? { "content-type": multipart2.type } : body ? { "content-type": "application/json" } : {} },
744
+ body: multipart2 ? new Uint8Array(multipart2.body) : body ? JSON.stringify(body) : void 0,
745
+ signal: AbortSignal.timeout(12e4)
746
+ });
747
+ if (response.status === 429) throw new RateLimited("rate limited");
748
+ const answer = await response.json().catch(() => null);
749
+ if (!response.ok) throw new Error(str(obj(answer?.error)?.message) || `${method} ${path} failed (${response.status})`);
750
+ return answer;
751
+ }
752
+ function multipart(fields) {
753
+ const boundary = `----sky${createHash2("sha256").update(fields.requestId).digest("hex").slice(0, 24)}`;
754
+ const filename = fields.name.replace(/[\r\n]/g, " ").replace(/"/g, "%22");
755
+ const field = (key, value) => Buffer.from(`--${boundary}\r
756
+ Content-Disposition: form-data; name="${key}"\r
757
+ \r
758
+ ${value}\r
759
+ `, "utf8");
760
+ return { type: `multipart/form-data; boundary=${boundary}`, body: Buffer.concat([
761
+ Buffer.from(`--${boundary}\r
762
+ Content-Disposition: form-data; name="file"; filename="${filename}"\r
763
+ Content-Type: ${fields.mediaType}\r
764
+ \r
765
+ `, "utf8"),
766
+ fields.bytes,
767
+ Buffer.from("\r\n", "utf8"),
768
+ field("requestId", fields.requestId),
769
+ field("sessionId", fields.sessionId),
770
+ Buffer.from(`--${boundary}--\r
771
+ `, "utf8")
772
+ ]) };
773
+ }
774
+ function readRecords(files) {
775
+ const records = [];
776
+ for (const file of files) {
777
+ if (file.endsWith(".gz")) continue;
778
+ for (const line of readFileSync3(file, "utf8").split("\n")) {
779
+ if (!line.trim()) continue;
780
+ try {
781
+ records.push(JSON.parse(line));
782
+ } catch {
783
+ }
784
+ }
785
+ }
786
+ return records;
787
+ }
788
+ async function captureSessionResults(input, state, options = {}) {
789
+ const fetcher = options.fetcher ?? fetch;
790
+ const home = options.home ?? homedir3();
791
+ const key = `${input.harness}:${input.nativeId}`;
792
+ const saved = new Set(state.saved);
793
+ let count = 0;
794
+ let limited = false;
795
+ for (const result of sessionResults(readRecords(input.files), { cwd: input.cwd, home, all: !state.read.includes(key) })) {
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")];
797
+ const id = JSON.stringify(version);
798
+ if (saved.has(id)) continue;
799
+ try {
800
+ const read = result.data ?? readFileSync3(result.path);
801
+ if (read.length !== result.size) continue;
802
+ const bytes = result.path && result.mediaType === "text/html" ? pageWithImages(read, result.path, home, result.origin !== "delivered") : read;
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 }));
804
+ saved.add(id);
805
+ state.saved.push(id);
806
+ count++;
807
+ } catch (error) {
808
+ if (error instanceof RateLimited) {
809
+ limited = true;
810
+ break;
811
+ }
812
+ }
813
+ }
814
+ if (!limited && !state.read.includes(key)) state.read.push(key);
815
+ if (state.saved.length > 2e4) state.saved.splice(0, state.saved.length - 2e4);
816
+ if (state.read.length > 5e3) state.read.splice(0, state.read.length - 5e3);
817
+ return { saved: count };
818
+ }
819
+
820
+ // src/trace-session.ts
821
+ var SESSION_HARNESSES = ["claude_code", "codex"];
822
+ var UPLOADED_MESSAGE_PREFIX = "trace:";
823
+ var SESSION_BACKFILL_DAYS = 30;
824
+ var BATCH_MESSAGES = 200;
825
+ var BATCH_BYTES = 3 * 1024 * 1024;
826
+ var MESSAGE_BYTES = 384 * 1024;
827
+ var HARNESS_BLOCKS = /<(system-reminder|local-command-stdout|local-command-stderr|command-message|command-args|task-notification)>[\s\S]*?<\/\1>/g;
828
+ var SKILL_FILE = /(?:^|[/\s'"=])skills\/([a-z0-9][a-z0-9-]*)\/SKILL\.md/g;
829
+ var WRITING_TOOL = /write|edit|create|delete|patch|apply/i;
830
+ var WRITES_SKILL_FILE = /(?:>|\btee\b|\bsed\s+-i|\brm\b|\bmv\b|\bcp\b|\btouch\b)[^|;&]*SKILL\.md/;
831
+ var TOOL_CALL = /^([A-Za-z_][\w.:-]*) ([{[][\s\S]*)$/;
832
+ function skillNamesRead(text) {
833
+ const call2 = TOOL_CALL.exec(text);
834
+ if (!call2) return [];
835
+ const tool = call2[1];
836
+ const args = call2[2];
837
+ if (tool === "Skill") {
838
+ try {
839
+ const parsed = JSON.parse(args);
840
+ return [parsed.skill, parsed.name].filter((name) => typeof name === "string").map((name) => name.split(":").at(-1));
841
+ } catch {
842
+ return [];
843
+ }
844
+ }
845
+ if (WRITING_TOOL.test(tool) || WRITES_SKILL_FILE.test(args)) return [];
846
+ return [...args.matchAll(SKILL_FILE)].map((match) => match[1]);
847
+ }
848
+ function skillReadsIn(rows, messages, state) {
849
+ const kept2 = new Set(messages.map((message) => message.id));
850
+ const reads = /* @__PURE__ */ new Map();
851
+ let current = null;
852
+ let waiting = [];
853
+ const settle = (messageId) => {
854
+ for (const read of waiting) {
855
+ const revision = revisionAt(state, read.name, read.at);
856
+ if (revision && kept2.has(messageId) && !reads.has(revision)) reads.set(revision, { revision_id: revision, message_id: messageId });
857
+ }
858
+ waiting = [];
859
+ };
860
+ rows.forEach((row, index) => {
861
+ if (row.role === "tool") {
862
+ const names2 = skillNamesRead(row.text).filter((name) => state.skills[name]);
863
+ waiting.push(...names2.map((name) => ({ name, ...row.at ? { at: row.at } : {} })));
864
+ if (current?.role === "agent") settle(current.id);
865
+ return;
866
+ }
867
+ const role = row.role === "user" ? "user" : "agent";
868
+ const text = role === "user" ? row.text.replace(HARNESS_BLOCKS, "").trim() : row.text;
869
+ if (!text) return;
870
+ if (!current || current.role !== role) current = { id: `${UPLOADED_MESSAGE_PREFIX}${index}`, role };
871
+ if (role === "agent") settle(current.id);
872
+ });
873
+ return [...reads.values()];
874
+ }
875
+ function sessionHarness(harness) {
876
+ return SESSION_HARNESSES.includes(harness);
877
+ }
878
+ var bytesOf = (value) => Buffer.byteLength(JSON.stringify(value));
879
+ function transcriptMessages(rows, startedAt) {
880
+ const messages = [];
881
+ let at = startedAt && Number.isFinite(Date.parse(startedAt)) ? new Date(startedAt).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString();
882
+ let current = null;
883
+ rows.forEach((row, index) => {
884
+ if (row.at && Number.isFinite(Date.parse(row.at))) at = new Date(row.at).toISOString();
885
+ if (row.role === "tool") return;
886
+ const role = row.role === "user" ? "user" : "agent";
887
+ const text = role === "user" ? row.text.replace(HARNESS_BLOCKS, "").trim() : row.text;
888
+ if (!text) return;
889
+ if (!current || current.role !== role) {
890
+ current = { id: `${UPLOADED_MESSAGE_PREFIX}${index}`, role, created_at: at, parts: [], bytes: 0 };
891
+ messages.push(current);
892
+ }
893
+ const part = { type: "text", index: current.parts.length, text };
894
+ const size = bytesOf(part);
895
+ if (current.bytes + size > MESSAGE_BYTES) return;
896
+ current.parts.push(part);
897
+ current.bytes += size;
898
+ });
899
+ return messages.filter((message) => message.parts.length).map(({ id, role, created_at, parts }) => ({ id, role, created_at, parts }));
900
+ }
901
+ function messageBatches(messages) {
902
+ const batches = [];
903
+ let batch = [];
904
+ let bytes = 0;
905
+ for (const message of messages) {
906
+ const size = bytesOf(message);
907
+ if (batch.length && (batch.length >= BATCH_MESSAGES || bytes + size > BATCH_BYTES)) {
908
+ batches.push(batch);
909
+ batch = [];
910
+ bytes = 0;
911
+ }
912
+ batch.push(message);
913
+ bytes += size;
914
+ }
915
+ if (batch.length) batches.push(batch);
916
+ return batches;
917
+ }
918
+ var refusal = (error) => error instanceof ApiError && error.status !== 429 && (error.status >= 400 && error.status < 500 || error.status === 503);
919
+ async function saveTraceSession(request, input, now = Date.now()) {
920
+ const { harness, sessionId, workspace, body } = input;
921
+ const last = Date.parse(body.ended_at ?? body.started_at ?? "");
922
+ if (Number.isFinite(last) && last < now - SESSION_BACKFILL_DAYS * 864e5) return { status: "older" };
923
+ try {
924
+ const opened = await request("POST", "/threads/local", workspace, {
925
+ harness,
926
+ sourceSessionId: sessionId,
927
+ origin: "terminal",
928
+ ...body.model ? { llm: body.model } : {},
929
+ ...body.title ? { title: body.title.slice(0, 120) } : {},
930
+ ...body.cwd ? { folder: body.cwd } : {},
931
+ machine: body.device.slice(0, 120)
932
+ });
933
+ if (opened.workspace) return { status: "elsewhere", sessionId: opened.sessionId, workspace: opened.workspace };
934
+ let stored = 0;
935
+ const transcript = transcriptMessages(body.messages, body.started_at);
936
+ const reads = input.skills ? skillReadsIn(body.messages, transcript, input.skills).slice(0, 200) : [];
937
+ const batches = messageBatches(transcript);
938
+ for (const [index, messages] of batches.entries()) {
939
+ const last2 = index === batches.length - 1;
940
+ const answer = await request("PUT", `/sessions/${encodeURIComponent(opened.sessionId)}/mirror`, workspace, {
941
+ messages,
942
+ ...index === 0 && body.title ? { title: body.title.slice(0, 120) } : {},
943
+ ...last2 && reads.length ? { skills_read: reads } : {}
944
+ });
945
+ stored += answer.stored;
946
+ }
947
+ return { status: "saved", sessionId: opened.sessionId, stored };
948
+ } catch (error) {
949
+ if (refusal(error)) return { status: "refused", code: error.code };
950
+ throw error;
951
+ }
952
+ }
953
+
954
+ // src/trace-library.ts
955
+ var MESSAGE_MAX_BYTES = 8 * 1024;
956
+ var TOOL_MAX_BYTES = 2 * 1024;
957
+ var MESSAGES_MAX = 2e4;
958
+ var BODY_MAX_BYTES = 7 * 1024 * 1024;
959
+ var UPLOAD_CONCURRENCY = 4;
960
+ var FULL_SWEEP_MS = 7 * 24 * 60 * 60 * 1e3;
961
+ var RESULTS_BACKFILL_MS = SESSION_BACKFILL_DAYS * 24 * 60 * 60 * 1e3;
962
+ var RESULTS_TRIES = 3;
963
+ var RETRIES = 3;
964
+ var RATE_LIMIT_RETRIES = 30;
965
+ var HARNESS_PREAMBLES = ["<environment_context>", "<user_instructions>", "<permissions instructions>", "# AGENTS.md instructions", "<INSTRUCTIONS>", "<external_codex_apps_open_page>"];
966
+ var titleOf = (text) => /^\s*</.test(text) ? void 0 : text.trim().slice(0, 120) || void 0;
967
+ var sleep = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
968
+ var backoffMs = (attempt) => Math.min(3e4, 1e3 * 2 ** attempt);
969
+ function skyDir() {
970
+ return process.env.SKY_CONFIG_DIR ?? join4(homedir4(), ".config", "sky");
971
+ }
972
+ function syncConfigPath() {
973
+ return join4(skyDir(), "trace-sync.json");
974
+ }
975
+ function resultsStatePath() {
976
+ return join4(skyDir(), "session-results.json");
977
+ }
978
+ function statePath2() {
979
+ return join4(skyDir(), "trace-sync-state.json");
980
+ }
981
+ function readJson2(path, fallback) {
982
+ try {
983
+ return JSON.parse(readFileSync4(path, "utf8"));
984
+ } catch {
985
+ return fallback;
986
+ }
987
+ }
988
+ function writeJson(path, value) {
989
+ mkdirSync2(dirname5(path), { recursive: true });
990
+ writeFileSync2(path, `${JSON.stringify(value, null, 2)}
991
+ `, { mode: 384 });
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
+ }
1002
+ function loadSyncConfig() {
1003
+ return readJson2(syncConfigPath(), { enabled: false, rules: [] });
1004
+ }
1005
+ function saveSyncConfig(config) {
1006
+ writeJson(syncConfigPath(), config);
1007
+ }
1008
+ function claudeRoot() {
1009
+ return join4(process.env.CLAUDE_CONFIG_DIR ?? join4(homedir4(), ".claude"), "projects");
1010
+ }
1011
+ function codexRoot() {
1012
+ return process.env.CODEX_HOME ?? join4(homedir4(), ".codex");
1013
+ }
1014
+ var SKY_PARSED = /* @__PURE__ */ new Set(["claude-code", "codex"]);
1015
+ var COLLECTOR_HARNESS = { "claude-code": "claude_code", codex: "codex" };
1016
+ var collectorModules;
1017
+ async function traceCollector() {
1018
+ const dir = join4(dirname5(fileURLToPath(import.meta.url)), "..", "vendor", "trace-collect");
1019
+ collectorModules ??= Promise.all([
1020
+ import(pathToFileURL(join4(dir, "collect.mjs")).href),
1021
+ import(pathToFileURL(join4(dir, "sinks", "agentsky.mjs")).href)
1022
+ ]).then(([collector, sink]) => ({ collector, sink }));
1023
+ return collectorModules;
1024
+ }
1025
+ function collectorHarness(harness) {
1026
+ return COLLECTOR_HARNESS[harness] ?? harness.replace(/[^a-z0-9_-]/g, "_").slice(0, 40);
1027
+ }
1028
+ async function sourceFolders() {
1029
+ const { collector } = await traceCollector();
1030
+ const others = (await collector.describeSources()).filter((source) => !SKY_PARSED.has(source.id)).flatMap((source) => source.found);
1031
+ return [claudeRoot(), join4(codexRoot(), "sessions"), join4(codexRoot(), "archived_sessions"), ...others, collector.STORE];
1032
+ }
1033
+ async function supportedAgents() {
1034
+ const { collector } = await traceCollector();
1035
+ return (await collector.describeSources()).map(({ id, name, kind, found }) => ({ id, name, kind, found: found.length > 0 }));
1036
+ }
1037
+ async function importExport(input) {
1038
+ const { collector } = await traceCollector();
1039
+ const result = await collector.importFile(input);
1040
+ if (result.error) throw new Error(result.error);
1041
+ return { agent: result.name ?? result.id ?? "export", sessions: result.total ?? 0 };
1042
+ }
1043
+ function signatureOf(files) {
1044
+ const parts = [];
1045
+ for (const file of files) {
1046
+ try {
1047
+ const stat = statSync4(file);
1048
+ parts.push(`${file}:${stat.size}:${Math.floor(stat.mtimeMs)}`);
1049
+ } catch {
1050
+ return null;
1051
+ }
1052
+ }
1053
+ return parts.join("|");
1054
+ }
1055
+ function claudeSessions() {
1056
+ const root = claudeRoot();
1057
+ const found = [];
1058
+ let projects;
1059
+ try {
1060
+ projects = readdirSync2(root);
1061
+ } catch {
1062
+ return found;
1063
+ }
1064
+ for (const project of projects) {
1065
+ const dir = join4(root, project);
1066
+ let entries;
1067
+ try {
1068
+ entries = readdirSync2(dir);
1069
+ } catch {
1070
+ continue;
1071
+ }
1072
+ for (const entry of entries) {
1073
+ if (!entry.endsWith(".jsonl")) continue;
1074
+ const sessionId = entry.slice(0, -".jsonl".length);
1075
+ const files = [join4(dir, entry)];
1076
+ const subagents = join4(dir, sessionId, "subagents");
1077
+ try {
1078
+ files.push(...readdirSync2(subagents).filter((name) => name.endsWith(".jsonl")).sort().map((name) => join4(subagents, name)));
1079
+ } catch {
1080
+ }
1081
+ const signature = signatureOf(files);
1082
+ if (signature) found.push({ harness: "claude_code", sessionId, files, signature });
1083
+ }
1084
+ }
1085
+ return found;
1086
+ }
1087
+ async function* readLines(file) {
1088
+ const raw = createReadStream(file);
1089
+ const input = file.endsWith(".gz") ? raw.pipe(createGunzip()) : raw;
1090
+ const reader = createInterface({ input, crlfDelay: Infinity });
1091
+ try {
1092
+ for await (const line of reader) yield line;
1093
+ } finally {
1094
+ reader.close();
1095
+ raw.destroy();
1096
+ }
1097
+ }
1098
+ async function firstLine(file) {
1099
+ for await (const line of readLines(file)) return line.length > 1024 * 1024 ? "" : line;
1100
+ return "";
1101
+ }
1102
+ function codexIdCachePath() {
1103
+ return join4(skyDir(), "trace-sync-codex-ids.json");
1104
+ }
1105
+ async function codexSessions() {
1106
+ const byId = /* @__PURE__ */ new Map();
1107
+ const cached = readJson2(codexIdCachePath(), {});
1108
+ const seen = {};
1109
+ const walk = async (dir) => {
1110
+ let entries;
1111
+ try {
1112
+ entries = readdirSync2(dir, { withFileTypes: true });
1113
+ } catch {
1114
+ return;
1115
+ }
1116
+ for (const entry of entries) {
1117
+ const full = join4(dir, entry.name);
1118
+ if (entry.isDirectory()) {
1119
+ await walk(full);
1120
+ continue;
1121
+ }
1122
+ if (!entry.name.startsWith("rollout-") || !/\.jsonl(\.gz)?$/.test(entry.name)) continue;
1123
+ const signature = signatureOf([full]);
1124
+ if (!signature) continue;
1125
+ let id = cached[full]?.signature === signature ? cached[full].id : void 0;
1126
+ if (!id) {
1127
+ try {
1128
+ const meta = JSON.parse(await firstLine(full));
1129
+ if (meta?.type === "session_meta" && typeof meta.payload?.id === "string") id = meta.payload.id;
1130
+ } catch {
1131
+ continue;
1132
+ }
1133
+ }
1134
+ if (!id) continue;
1135
+ seen[full] = { signature, id };
1136
+ const mtime = statSync4(full).mtimeMs;
1137
+ const known = byId.get(id);
1138
+ if (!known || mtime > known.mtime) byId.set(id, { harness: "codex", sessionId: id, files: [full], signature, mtime });
1139
+ }
1140
+ };
1141
+ await walk(join4(codexRoot(), "sessions"));
1142
+ await walk(join4(codexRoot(), "archived_sessions"));
1143
+ try {
1144
+ writeJson(codexIdCachePath(), seen);
1145
+ } catch {
1146
+ }
1147
+ return [...byId.values()].map(({ mtime: _mtime, ...session }) => session);
1148
+ }
1149
+ function claudeSessionAt(path) {
1150
+ const root = claudeRoot();
1151
+ if (!path.startsWith(`${root}${sep3}`) || !path.endsWith(".jsonl") || basename4(dirname5(dirname5(path))) !== basename4(root)) return null;
1152
+ const sessionId = basename4(path, ".jsonl");
1153
+ const files = [path];
1154
+ const subagents = join4(dirname5(path), sessionId, "subagents");
1155
+ try {
1156
+ files.push(...readdirSync2(subagents).filter((name) => name.endsWith(".jsonl")).sort().map((name) => join4(subagents, name)));
1157
+ } catch {
1158
+ }
1159
+ const signature = signatureOf(files);
1160
+ return signature ? { harness: "claude_code", sessionId, files, signature } : null;
1161
+ }
1162
+ async function collectorSessions() {
1163
+ const { collector } = await traceCollector();
1164
+ const report = await collector.collect();
1165
+ const failed = report.filter((entry) => entry.error);
1166
+ if (failed.length) throw new Error(failed.map((entry) => `${entry.id}: ${entry.error}`).join("; "));
1167
+ const harness = (await collector.loadSources()).map((source) => source.id).filter((id) => !SKY_PARSED.has(id));
1168
+ const found = /* @__PURE__ */ new Map();
1169
+ for await (const { file, trace, id } of collector.sessions({ harness, children: true })) {
1170
+ const signature = signatureOf([file]);
1171
+ if (!signature) continue;
1172
+ const session = { harness: collectorHarness(trace.harness), sessionId: String(id).slice(0, 200), files: [file], signature, trace };
1173
+ found.set(`${session.harness}:${session.sessionId}`, session);
1174
+ }
1175
+ return [...found.values()];
1176
+ }
1177
+ async function discoverSessions(onCollectorError) {
1178
+ let others = [];
1179
+ try {
1180
+ others = await collectorSessions();
1181
+ } catch (error) {
1182
+ if (!onCollectorError) throw error;
1183
+ onCollectorError(error);
1184
+ }
1185
+ return [...claudeSessions(), ...await codexSessions(), ...others];
1186
+ }
1187
+ function asRecord(value) {
1188
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1189
+ }
1190
+ function str2(value) {
1191
+ return typeof value === "string" && value.length ? value : void 0;
1192
+ }
1193
+ function toolResultText(content) {
1194
+ if (typeof content === "string") return content;
1195
+ if (Array.isArray(content)) return content.map((part) => str2(asRecord(part)?.text) ?? "").filter(Boolean).join("\n");
1196
+ return "";
1197
+ }
1198
+ function stringify(value) {
1199
+ if (typeof value === "string") return value;
1200
+ try {
1201
+ return JSON.stringify(value);
1202
+ } catch {
1203
+ return "";
1204
+ }
1205
+ }
1206
+ var Collector = class {
1207
+ messages = [];
1208
+ conversation = [];
1209
+ partial = false;
1210
+ bytes = 0;
1211
+ push(role, text, at, inConversation = true) {
1212
+ const trimmed = text.replace(/\u0000/g, "").trim();
1213
+ if (!trimmed) return;
1214
+ if (this.messages.length >= MESSAGES_MAX) {
1215
+ this.partial = true;
1216
+ return;
1217
+ }
1218
+ const safe = redactTraceText(trimmed, role === "tool" ? TOOL_MAX_BYTES : MESSAGE_MAX_BYTES);
1219
+ if (safe.truncated) this.partial = true;
1220
+ this.bytes += Buffer.byteLength(safe.text) + 80;
1221
+ this.messages.push({ role, text: safe.text, ...at ? { at } : {} });
1222
+ this.conversation.push(inConversation);
1223
+ }
1224
+ };
1225
+ function isoOrUndefined(value) {
1226
+ const text = str2(value);
1227
+ if (!text) return void 0;
1228
+ const time = Date.parse(text);
1229
+ return Number.isFinite(time) ? new Date(time).toISOString() : void 0;
1230
+ }
1231
+ async function collectorBody(trace, device, scrubber) {
1232
+ const { collector, sink } = await traceCollector();
1233
+ const scrubbed = (scrubber ?? collector.scrubberFor()).scrub(trace);
1234
+ return sink.toLibrary({ ...scrubbed, cwd: trace.cwd, stats: trace.stats }, device);
1235
+ }
1236
+ async function parseClaudeSession(session) {
1237
+ const out = { harness: "claude_code", sessionId: session.sessionId, userTurns: 0, toolCalls: 0, partial: false, messages: [], conversation: [] };
1238
+ const collector = new Collector();
1239
+ const source = new SessionSourceCollector();
1240
+ const references = new TraceReferences();
1241
+ for (const [index, file] of session.files.entries()) {
1242
+ for await (const line of readLines(file)) {
1243
+ if (!line.trim()) continue;
1244
+ references.scan(line);
1245
+ let record;
1246
+ try {
1247
+ record = asRecord(JSON.parse(line));
1248
+ } catch {
1249
+ out.partial = true;
1250
+ continue;
1251
+ }
1252
+ if (!record) continue;
1253
+ source.push(index === 0 ? record : { ...record, isSidechain: true });
1254
+ const at = isoOrUndefined(record.timestamp);
1255
+ if (index === 0) {
1256
+ out.cwd ??= str2(record.cwd);
1257
+ out.gitBranch ??= str2(record.gitBranch);
1258
+ if (at) {
1259
+ out.startedAt ??= at;
1260
+ out.endedAt = at;
1261
+ }
1262
+ }
1263
+ const message = asRecord(record.message);
1264
+ if (!message || record.isMeta === true) continue;
1265
+ const own = index === 0 && record.isSidechain !== true && record.parent_tool_use_id == null;
1266
+ if (record.type === "user") {
1267
+ const spoken = own && asRecord(record.origin)?.kind !== "task-notification" && record.promptSource !== "system" && typeof record.wakeupSource !== "string";
1268
+ const content = message.content;
1269
+ if (typeof content === "string") {
1270
+ collector.push("user", content, at, spoken);
1271
+ if (index === 0) out.userTurns += 1;
1272
+ if (index === 0) out.title ??= titleOf(content);
1273
+ continue;
1274
+ }
1275
+ if (!Array.isArray(content)) continue;
1276
+ let typed = false;
1277
+ for (const part of content.map(asRecord)) {
1278
+ if (part?.type === "text" && str2(part.text)) {
1279
+ collector.push("user", part.text, at, spoken);
1280
+ typed = true;
1281
+ if (index === 0) out.title ??= titleOf(part.text);
1282
+ } else if (part?.type === "tool_result") {
1283
+ collector.push("tool", toolResultText(part.content), at);
1284
+ }
1285
+ }
1286
+ if (typed && index === 0) out.userTurns += 1;
1287
+ } else if (record.type === "assistant") {
1288
+ const content = Array.isArray(message.content) ? message.content.map(asRecord) : [];
1289
+ for (const part of content) {
1290
+ if (part?.type === "text") collector.push("assistant", str2(part.text) ?? "", at, own);
1291
+ else if (part?.type === "tool_use") {
1292
+ out.toolCalls += 1;
1293
+ collector.push("tool", `${str2(part.name) ?? "tool"} ${stringify(part.input)}`, at);
1294
+ }
1295
+ }
1296
+ }
1297
+ }
1298
+ }
1299
+ return withWorkLinks(finish(withSource(out, source.result()), collector), references);
1300
+ }
1301
+ async function parseCodexSession(session) {
1302
+ const out = { harness: "codex", sessionId: session.sessionId, userTurns: 0, toolCalls: 0, partial: false, messages: [], conversation: [] };
1303
+ const collector = new Collector();
1304
+ const source = new SessionSourceCollector();
1305
+ const references = new TraceReferences();
1306
+ for await (const line of readLines(session.files[0])) {
1307
+ if (!line.trim()) continue;
1308
+ references.scan(line);
1309
+ let record;
1310
+ try {
1311
+ record = asRecord(JSON.parse(line));
1312
+ } catch {
1313
+ out.partial = true;
1314
+ continue;
1315
+ }
1316
+ source.push(record);
1317
+ const payload = asRecord(record?.payload);
1318
+ if (!record || !payload) continue;
1319
+ const at = isoOrUndefined(record.timestamp);
1320
+ if (at) {
1321
+ out.startedAt ??= at;
1322
+ out.endedAt = at;
1323
+ }
1324
+ if (record.type === "session_meta") {
1325
+ out.cwd ??= str2(payload.cwd);
1326
+ } else if (record.type === "turn_context") {
1327
+ out.cwd ??= str2(payload.cwd);
1328
+ } else if (record.type === "response_item") {
1329
+ if (payload.type === "message") {
1330
+ const role = payload.role === "user" ? "user" : payload.role === "assistant" ? "assistant" : null;
1331
+ if (!role) continue;
1332
+ const text = (Array.isArray(payload.content) ? payload.content : []).map((part) => str2(asRecord(part)?.text) ?? "").filter(Boolean).join("\n");
1333
+ if (role === "user" && HARNESS_PREAMBLES.some((prefix) => text.trimStart().startsWith(prefix))) continue;
1334
+ collector.push(role, text, at);
1335
+ if (role === "user" && text.trim()) {
1336
+ out.userTurns += 1;
1337
+ out.title ??= titleOf(text);
1338
+ }
1339
+ } else if (payload.type === "function_call" || payload.type === "custom_tool_call" || payload.type === "local_shell_call") {
1340
+ out.toolCalls += 1;
1341
+ collector.push("tool", `${str2(payload.name) ?? payload.type} ${stringify(payload.arguments ?? payload.input ?? payload.action)}`, at);
1342
+ } else if (payload.type === "function_call_output" || payload.type === "custom_tool_call_output") {
1343
+ const output = asRecord(payload.output);
1344
+ collector.push("tool", str2(output?.content) ?? stringify(payload.output), at);
1345
+ }
1346
+ }
1347
+ }
1348
+ return withWorkLinks(finish(withSource(out, source.result()), collector), references);
1349
+ }
1350
+ function withWorkLinks(out, references) {
1351
+ const remote = out.gitRemote ?? gitRemoteAt(out.cwd);
1352
+ return { ...out, ...remote ? { gitRemote: publicRemote(remote) } : {}, workObjects: references.objects() };
1353
+ }
1354
+ function withSource(out, meta) {
1355
+ return {
1356
+ ...out,
1357
+ gitBranch: out.gitBranch ?? meta.git?.branch,
1358
+ gitCommit: meta.git?.commit,
1359
+ gitRemote: meta.git?.remote ? publicRemote(meta.git.remote) : void 0,
1360
+ model: meta.models?.[0],
1361
+ models: meta.models,
1362
+ harnessVersion: meta.harness_version,
1363
+ client: meta.client,
1364
+ modelProvider: meta.model_provider,
1365
+ effort: meta.effort,
1366
+ usage: meta.usage
1367
+ };
1368
+ }
1369
+ function finish(out, collector) {
1370
+ let messages = collector.messages;
1371
+ const conversation = [...collector.conversation];
1372
+ let partial = out.partial || collector.partial;
1373
+ let bytes = collector.bytes;
1374
+ if (bytes > BODY_MAX_BYTES) {
1375
+ messages = messages.map((message) => message.role === "tool" && message.text.length > 256 ? { ...message, text: `${message.text.slice(0, 256)}\u2026` } : message);
1376
+ bytes = messages.reduce((sum, message) => sum + Buffer.byteLength(message.text) + 80, 0);
1377
+ partial = true;
1378
+ }
1379
+ while (bytes > BODY_MAX_BYTES && messages.length) {
1380
+ const from = Math.floor(messages.length / 2), count = Math.max(1, Math.floor(messages.length / 10));
1381
+ const dropped = messages.splice(from, count);
1382
+ conversation.splice(from, count);
1383
+ bytes -= dropped.reduce((sum, message) => sum + Buffer.byteLength(message.text) + 80, 0);
1384
+ }
1385
+ return { ...out, title: out.title ? redactTraceText(out.title, 300).text : void 0, partial, messages, conversation };
1386
+ }
1387
+ function isTrivial(session) {
1388
+ if (!session.messages.length) return true;
1389
+ const chars = session.messages.reduce((sum, message) => sum + message.text.length, 0);
1390
+ return session.toolCalls === 0 && session.messages.length <= 2 && chars < 200;
1391
+ }
1392
+ function sessionDigest(session) {
1393
+ const hash = createHash3("sha256");
1394
+ hash.update(`${session.cwd ?? ""}${session.model ?? ""}`);
1395
+ for (const message of session.messages) hash.update(`${message.role}\0${message.text}`);
1396
+ return hash.digest("hex");
1397
+ }
1398
+ function projectOf(cwd) {
1399
+ const parts = cwd.split(sep3).filter(Boolean);
1400
+ for (const marker of [".worktrees", "worktrees"]) {
1401
+ const at = parts.lastIndexOf(marker);
1402
+ if (at > 0) {
1403
+ const owner = parts[at - 1] === ".claude" ? at - 2 : at - 1;
1404
+ if (owner >= 0) return parts[owner];
1405
+ }
1406
+ }
1407
+ let dir = cwd;
1408
+ while (dir && dir !== dirname5(dir)) {
1409
+ if (existsSync3(join4(dir, ".git"))) return basename4(dir);
1410
+ dir = dirname5(dir);
1411
+ }
1412
+ return parts.at(-1);
1413
+ }
1414
+ function workspaceFile(cwd) {
1415
+ let dir = cwd;
1416
+ while (dir && dir !== dirname5(dir)) {
1417
+ const file = join4(dir, ".agentsky.json");
1418
+ if (existsSync3(file)) {
1419
+ const workspace = str2(readJson2(file, {}).workspace);
1420
+ if (workspace) return workspace;
1421
+ }
1422
+ if (existsSync3(join4(dir, ".git"))) return void 0;
1423
+ dir = dirname5(dir);
1424
+ }
1425
+ return void 0;
1426
+ }
1427
+ function gitConfigPath(root) {
1428
+ const dotGit = join4(root, ".git");
1429
+ try {
1430
+ if (statSync4(dotGit).isDirectory()) return join4(dotGit, "config");
1431
+ const pointer = readFileSync4(dotGit, "utf8").match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();
1432
+ if (!pointer) return void 0;
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");
1436
+ } catch {
1437
+ return void 0;
1438
+ }
1439
+ }
1440
+ function repoRemote(cwd) {
1441
+ let dir = cwd;
1442
+ while (dir && dir !== dirname5(dir)) {
1443
+ if (existsSync3(join4(dir, ".git"))) {
1444
+ const config = gitConfigPath(dir);
1445
+ if (!config) return void 0;
1446
+ try {
1447
+ const text = readFileSync4(config, "utf8");
1448
+ return text.match(/\[remote "origin"\][^[]*?url\s*=\s*(\S+)/)?.[1];
1449
+ } catch {
1450
+ return void 0;
1451
+ }
1452
+ }
1453
+ dir = dirname5(dir);
1454
+ }
1455
+ return void 0;
1456
+ }
1457
+ function routeSession(cwd, config) {
1458
+ if (cwd) {
1459
+ const pinned = workspaceFile(cwd);
1460
+ if (pinned) return pinned;
1461
+ const lower = `${cwd}
1462
+ ${repoRemote(cwd) ?? ""}`.toLowerCase();
1463
+ const rule = config.rules.find((candidate) => lower.includes(candidate.match.toLowerCase()));
1464
+ if (rule) return rule.workspace;
1465
+ }
1466
+ return config.fallback ?? null;
1467
+ }
1468
+ function homeLabel(path) {
1469
+ if (!path) return void 0;
1470
+ const home = homedir4();
1471
+ return path === home || path.startsWith(`${home}${sep3}`) ? `~${path.slice(home.length)}` : path;
1472
+ }
1473
+ async function libraryRequest(method, path, workspace, body, timeoutMs = 12e4) {
1474
+ const token = apiToken();
1475
+ if (!token) throw new ApiError(401, "not_logged_in", "not logged in \u2014 run `sky auth login`");
1476
+ const payload = body ? JSON.stringify(body) : void 0;
1477
+ let res;
1478
+ for (let attempt = 0; ; attempt++) {
1479
+ try {
1480
+ res = await fetch(`${apiBase()}${path}`, {
1481
+ method,
1482
+ headers: { "user-agent": USER_AGENT, authorization: `Bearer ${token}`, "x-universe": workspace, ...payload ? { "content-type": "application/json" } : {} },
1483
+ body: payload,
1484
+ signal: AbortSignal.timeout(timeoutMs)
1485
+ });
1486
+ } catch (error) {
1487
+ if (attempt >= RETRIES) throw error;
1488
+ await sleep(backoffMs(attempt));
1489
+ continue;
1490
+ }
1491
+ if (res.status === 429 && attempt < RATE_LIMIT_RETRIES) {
1492
+ const wait = Number(res.headers.get("retry-after"));
1493
+ await sleep(Number.isFinite(wait) && wait > 0 ? Math.min(wait, 65) * 1e3 : backoffMs(attempt));
1494
+ continue;
1495
+ }
1496
+ if (res.status >= 500 && res.status !== 503 && attempt < RETRIES) {
1497
+ await sleep(backoffMs(attempt));
1498
+ continue;
1499
+ }
1500
+ break;
1501
+ }
1502
+ if (!res.ok) {
1503
+ let code = "http_error";
1504
+ let message = `${res.status} ${res.statusText}`;
1505
+ try {
1506
+ const parsed = await res.json();
1507
+ code = parsed.error?.code ?? code;
1508
+ message = parsed.error?.message ?? message;
1509
+ } catch {
1510
+ }
1511
+ throw new ApiError(res.status, code, message);
1512
+ }
1513
+ return await res.json();
1514
+ }
1515
+ function uploadBody(session, sha256, device) {
1516
+ const cwd = homeLabel(session.cwd);
1517
+ return {
1518
+ sha256,
1519
+ ...session.workObjects?.length ? { work_objects: session.workObjects } : {},
1520
+ ...session.title ? { title: session.title } : {},
1521
+ ...cwd ? { cwd: cwd.slice(0, 1024) } : {},
1522
+ ...session.cwd && projectOf(session.cwd) ? { project: projectOf(session.cwd).slice(0, 200) } : {},
1523
+ ...session.gitBranch ? { git_branch: session.gitBranch.slice(0, 300) } : {},
1524
+ ...session.gitCommit ? { git_commit: session.gitCommit.slice(0, 80) } : {},
1525
+ ...session.gitRemote ? { git_remote: session.gitRemote.slice(0, 1024) } : {},
1526
+ ...session.model ? { model: session.model.slice(0, 200) } : {},
1527
+ ...session.models?.length ? { models: session.models.slice(0, 50).map((model) => model.slice(0, 200)) } : {},
1528
+ ...session.harnessVersion ? { harness_version: session.harnessVersion.slice(0, 80) } : {},
1529
+ ...session.client ? { client: session.client.slice(0, 200) } : {},
1530
+ ...session.modelProvider ? { model_provider: session.modelProvider.slice(0, 100) } : {},
1531
+ ...session.effort ? { effort: session.effort.slice(0, 100) } : {},
1532
+ ...session.usage && Object.keys(session.usage).length ? { usage: session.usage } : {},
1533
+ device: device.slice(0, 200),
1534
+ ...session.startedAt ? { started_at: session.startedAt } : {},
1535
+ ...session.endedAt ? { ended_at: session.endedAt } : {},
1536
+ user_turns: session.userTurns,
1537
+ tool_calls: session.toolCalls,
1538
+ partial: session.partial,
1539
+ messages: session.messages,
1540
+ outside_conversation: session.conversation.flatMap((inside, index) => inside ? [] : [index])
1541
+ };
1542
+ }
1543
+ function lockPath() {
1544
+ return join4(skyDir(), "trace-sync.lock");
1545
+ }
1546
+ function takeLock() {
1547
+ const path = lockPath();
1548
+ mkdirSync2(skyDir(), { recursive: true });
1549
+ try {
1550
+ mkdirSync2(path);
1551
+ } catch {
1552
+ const pid = Number(readJson2(join4(path, "pid.json"), {}).pid);
1553
+ let alive = false;
1554
+ try {
1555
+ if (pid) {
1556
+ process.kill(pid, 0);
1557
+ alive = true;
1558
+ }
1559
+ } catch {
1560
+ alive = false;
1561
+ }
1562
+ if (alive) return false;
1563
+ rmSync2(path, { recursive: true, force: true });
1564
+ try {
1565
+ mkdirSync2(path);
1566
+ } catch {
1567
+ return false;
1568
+ }
1569
+ }
1570
+ writeJson(join4(path, "pid.json"), { pid: process.pid });
1571
+ return true;
1572
+ }
1573
+ function releaseLock() {
1574
+ rmSync2(lockPath(), { recursive: true, force: true });
1575
+ }
1576
+ async function pool(items, size, fn) {
1577
+ let next = 0;
1578
+ await Promise.all(Array.from({ length: Math.min(size, items.length) }, async () => {
1579
+ while (next < items.length) await fn(items[next++]);
1580
+ }));
1581
+ }
1582
+ async function syncTraces(options = {}) {
1583
+ const config = loadSyncConfig();
1584
+ if (!config.enabled) throw new Error("trace sync is off on this machine \u2014 turn it on with `sky trace sync --enable`");
1585
+ if (!options.dryRun && !takeLock()) return null;
1586
+ try {
1587
+ return await runSync(config, options);
1588
+ } finally {
1589
+ if (!options.dryRun) releaseLock();
1590
+ }
1591
+ }
1592
+ async function verifyPendingFile(item, source) {
1593
+ const workspace = item.manifest.workspace;
1594
+ let url = `${apiBase()}/files/${encodeURIComponent(item.manifest.fileId)}/content`;
1595
+ let response = await fetch(url, { redirect: "manual", headers: { authorization: `Bearer ${apiToken()}`, "x-universe": workspace, "user-agent": USER_AGENT } });
1596
+ for (let redirects = 0; response.status >= 300 && response.status < 400 && redirects < 5; redirects++) {
1597
+ const location = response.headers.get("location");
1598
+ if (!location) throw new Error("Stored source redirect has no location.");
1599
+ url = new URL(location, url).href;
1600
+ if (!/^https?:/.test(url)) throw new Error("Stored source redirect has an invalid protocol.");
1601
+ response = await fetch(url, { redirect: "manual", headers: { "user-agent": USER_AGENT } });
1602
+ }
1603
+ if (!response.ok || !response.body) throw new Error(`Cannot verify stored source file (${response.status}).`);
1604
+ const hash = createHash3("sha256");
1605
+ let bytes = 0;
1606
+ const reader = response.body.getReader();
1607
+ try {
1608
+ while (true) {
1609
+ const part = await reader.read();
1610
+ if (part.done) break;
1611
+ hash.update(part.value);
1612
+ bytes += part.value.length;
1613
+ }
1614
+ } finally {
1615
+ reader.releaseLock();
1616
+ }
1617
+ if (bytes !== source.bytes || hash.digest("hex") !== source.sha256) throw new Error("Stored source file does not match the pending archive; retained for retry.");
1618
+ }
1619
+ async function runSync(config, options) {
1620
+ const state = readJson2(statePath2(), { sessions: {} });
1621
+ const full = options.full || !state.lastFullAt || Date.now() - Date.parse(state.lastFullAt) > FULL_SWEEP_MS;
1622
+ const device = config.device ?? hostname();
1623
+ 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: [] };
1624
+ const results = readJson2(resultsStatePath(), { read: [], saved: [] });
1625
+ const saveResults = async (local, workspace, sessionId, cwd) => {
1626
+ if (!sessionHarness(local.harness)) return;
1627
+ try {
1628
+ report.results += (await captureSessionResults({ harness: local.harness, nativeId: local.sessionId, sessionId, workspace, files: local.files, cwd: cwd?.replace(/^~(?=\/|$)/, homedir4()) }, results)).saved;
1629
+ } catch (error) {
1630
+ (results.tries ??= {})[key(local)] = (results.tries[key(local)] ?? 0) + 1;
1631
+ report.errors.push(`${key(local)} \u2192 ${workspace}: results not saved yet: ${error.message}`);
1632
+ } finally {
1633
+ writePrivateJson(resultsStatePath(), results);
1634
+ }
1635
+ };
1636
+ const key = (s) => `${s.harness}:${s.sessionId}`;
1637
+ const selected = (s) => !options.only?.length || options.only.includes(s.sessionId) || s.files.some((file) => options.only.includes(file));
1638
+ const record = (s, value) => {
1639
+ state.sessions[key(s)] = { captureVersion: SOURCE_CAPTURE_VERSION, signature: s.signature, at: (/* @__PURE__ */ new Date()).toISOString(), ...value };
1640
+ };
1641
+ const fail = (label, error) => {
1642
+ report.failed++;
1643
+ report.errors.push(`${label}: ${error.message}`);
1644
+ };
1645
+ const exclusions = loadExclusions(skyDir());
1646
+ const leftOut = (local, cwd) => {
1647
+ const hit = excludedBy(exclusions, { harness: local.harness, sessionId: local.sessionId, cwd });
1648
+ if (!hit) return false;
1649
+ report.excluded++;
1650
+ record(local, { workspace: null, status: "excluded", excludedBy: hit.by });
1651
+ return true;
1652
+ };
1653
+ try {
1654
+ report.legacySources = readdirSync2(join4(skyDir(), "trace-sources")).filter((name) => /^[a-f0-9]{64}\.jsonl$/.test(name)).length;
1655
+ } catch {
1656
+ }
1657
+ if (report.legacySources) options.onProgress?.(`${report.legacySources} unbound legacy source archives remain local; they are not uploaded or removed.`);
1658
+ const queueRoot = join4(skyDir(), "trace-pending");
1659
+ const endpoint = canonicalSourceApiBase(apiBase());
1660
+ const restored = /* @__PURE__ */ new Map();
1661
+ let blocked = false;
1662
+ const unreadable = /* @__PURE__ */ new Set();
1663
+ let scrubber;
1664
+ const collectorFailed = (error) => fail("other agents: unreadable", error);
1665
+ let discovered;
1666
+ const discover = async () => discovered ??= await discoverSessions(collectorFailed);
1667
+ const send = async (item) => {
1668
+ const { workspace } = item.manifest;
1669
+ let capturing = false;
1670
+ let { local } = item.manifest;
1671
+ const queuedCwd = typeof item.manifest.body.cwd === "string" ? item.manifest.body.cwd : void 0;
1672
+ if (leftOut(local, queuedCwd)) {
1673
+ writePrivateJson(statePath2(), state);
1674
+ removePendingSource(item);
1675
+ restored.set(key(local), local.signature);
1676
+ return;
1677
+ }
1678
+ try {
1679
+ if (item.manifest.apiBase !== endpoint) throw new Error("Pending source belongs to another API endpoint; restore that endpoint before syncing new sources.");
1680
+ let source;
1681
+ capturing = false;
1682
+ try {
1683
+ source = await recoverPendingSource(item);
1684
+ } catch (error) {
1685
+ if (!(error instanceof IncompleteSourceCaptureError)) throw error;
1686
+ capturing = true;
1687
+ const native = (await discover()).find((s) => key(s) === key(local));
1688
+ if (!native) throw error;
1689
+ const parsed = native.trace ? null : native.harness === "claude_code" ? await parseClaudeSession(native) : await parseCodexSession(native);
1690
+ const nativeCwd = native.trace?.cwd ?? parsed.cwd;
1691
+ if (routeSession(nativeCwd, config) !== workspace) throw new Error("Interrupted capture no longer has its original routing authorization; pending data retained.");
1692
+ if (native.signature !== local.signature) {
1693
+ const body = native.trace ? await collectorBody(native.trace, device, scrubber ??= (await traceCollector()).collector.scrubberFor()) : uploadBody(parsed, sessionDigest(parsed), device);
1694
+ savePendingSource(item, { local: { harness: native.harness, sessionId: native.sessionId, signature: native.signature, files: native.files }, body });
1695
+ local = item.manifest.local;
1696
+ }
1697
+ source = await captureTraceSource(native, item.directory, { workspace, apiBase: item.manifest.apiBase });
1698
+ capturing = false;
1699
+ }
1700
+ if (item.manifest.stage !== "ready") completePendingCapture(item, source);
1701
+ const statuses = await libraryRequest("POST", "/trace-library/check", workspace, {
1702
+ sessions: [{ harness: local.harness, session_id: local.sessionId, sha256: source.sha256 }]
1703
+ });
1704
+ if (statuses.sessions[0]?.status === "owned") {
1705
+ report.owned++;
1706
+ throw new Error("Another member owns this source; pending archive retained.");
1707
+ }
1708
+ if (item.manifest.fileId) await verifyPendingFile(item, source);
1709
+ else {
1710
+ const file = await uploadLargeFile(source.path, "application/x-ndjson", void 0, () => {
1711
+ }, workspace);
1712
+ savePendingSource(item, { fileId: file.id });
1713
+ }
1714
+ const { work_objects: workObjects, outside_conversation: outside, ...previewBody } = item.manifest.body;
1715
+ if (config.sessions !== false && sessionHarness(local.harness)) {
1716
+ const body = previewBody;
1717
+ const left = new Set(outside ?? []);
1718
+ const saved2 = await saveTraceSession(libraryRequest, {
1719
+ harness: local.harness,
1720
+ sessionId: local.sessionId,
1721
+ workspace,
1722
+ body: { ...body, messages: body.messages.filter((_, index) => !left.has(index)) },
1723
+ skills: loadLocalSkillState()
1724
+ });
1725
+ if (saved2.status === "saved") report.sessions++;
1726
+ if (saved2.status === "saved" || saved2.status === "elsewhere") await saveResults(local, saved2.status === "elsewhere" ? saved2.workspace : workspace, saved2.sessionId, body.cwd);
1727
+ else if (saved2.status === "refused") options.onProgress?.(`${key(local)}: kept in the trace library only (${saved2.code})`);
1728
+ if (saved2.status !== "saved" && saved2.status !== "elsewhere" && !results.read.includes(key(local))) {
1729
+ results.read.push(key(local));
1730
+ writePrivateJson(resultsStatePath(), results);
1731
+ }
1732
+ }
1733
+ const saved = await libraryRequest("PUT", `/trace-library/${local.harness}/${encodeURIComponent(local.sessionId)}`, workspace, { ...previewBody, sha256: source.sha256 });
1734
+ savePendingSource(item, { previewSaved: true, link: saved.linked_task ?? null });
1735
+ const link = item.manifest.link;
1736
+ const linkKey = createHash3("sha256").update(JSON.stringify(link ?? null)).digest("hex").slice(0, 16);
1737
+ await libraryRequest("POST", "/events", workspace, { events: [{
1738
+ idempotency_key: `trace-source:${source.sha256}:${linkKey}`,
1739
+ ...link ? { session_id: link.session_id, task_id: link.task_id } : {},
1740
+ log: "workspace",
1741
+ kind: "trace.source",
1742
+ source: { system: "local-trace-collector", kind: local.harness, version: String(SOURCE_CAPTURE_VERSION) },
1743
+ surface: "cli",
1744
+ actor: { kind: "person" },
1745
+ objects: [{ type: "local_session", id: key(local), role: "source" }, ...workObjects ?? []],
1746
+ payload: {
1747
+ harness: local.harness,
1748
+ session_id: local.sessionId,
1749
+ sha256: source.sha256,
1750
+ redacted_before_upload: true,
1751
+ records: source.records,
1752
+ source_files: source.sourceFiles,
1753
+ source_file_id: item.manifest.fileId,
1754
+ gaps: source.gaps,
1755
+ library_is_preview: true
1756
+ },
1757
+ bodies: [{ role: "transcript", media_type: "application/x-ndjson", file_id: item.manifest.fileId, complete: source.complete }]
1758
+ }] });
1759
+ record(local, { workspace, sha256: source.sha256, status: source.complete ? "stored" : "stored_with_gaps" });
1760
+ writePrivateJson(statePath2(), state);
1761
+ removePendingSource(item);
1762
+ restored.set(key(local), local.signature);
1763
+ report.uploaded++;
1764
+ report.byWorkspace[workspace] = (report.byWorkspace[workspace] ?? 0) + 1;
1765
+ } catch (error) {
1766
+ if (capturing) unreadable.add(key(local));
1767
+ else blocked = true;
1768
+ fail(`${key(local)} \u2192 ${workspace}`, error);
1769
+ }
1770
+ };
1771
+ if (!options.dryRun) {
1772
+ let existing;
1773
+ try {
1774
+ existing = listPendingSources(queueRoot);
1775
+ } catch (error) {
1776
+ fail("pending source queue", error);
1777
+ return report;
1778
+ }
1779
+ report.scanned = existing.length;
1780
+ report.changed = existing.length;
1781
+ for (let start = 0; start < existing.length; start += UPLOAD_CONCURRENCY) {
1782
+ await pool(existing.slice(start, start + UPLOAD_CONCURRENCY), UPLOAD_CONCURRENCY, send);
1783
+ if (blocked) return report;
1784
+ }
1785
+ }
1786
+ const direct = options.only?.length ? options.only.map(claudeSessionAt) : [];
1787
+ const sessions = (direct.length && direct.every(Boolean) ? direct : await discover()).filter(selected);
1788
+ report.scanned = Math.max(report.scanned, sessions.length);
1789
+ const lifted = (s) => state.sessions[key(s)]?.status === "excluded" && !stillExcluded(exclusions, state.sessions[key(s)]?.excludedBy ?? "");
1790
+ 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) => {
1791
+ try {
1792
+ return Date.now() - statSync4(file).mtimeMs < RESULTS_BACKFILL_MS;
1793
+ } catch {
1794
+ return false;
1795
+ }
1796
+ });
1797
+ let pending = sessions.filter((s) => !unreadable.has(key(s)) && restored.get(key(s)) !== s.signature && (full || lifted(s) || state.sessions[key(s)]?.captureVersion !== SOURCE_CAPTURE_VERSION || state.sessions[key(s)]?.signature !== s.signature || awaitingResults(s)));
1798
+ if (options.limit) pending = pending.slice(0, options.limit);
1799
+ report.changed += pending.length;
1800
+ const prepare = async (local) => {
1801
+ if (local.trace) {
1802
+ if (leftOut(local, local.trace.cwd)) return null;
1803
+ const workspace2 = routeSession(local.trace.cwd, config);
1804
+ if (!workspace2) {
1805
+ report.local++;
1806
+ record(local, { workspace: null, status: "local" });
1807
+ return null;
1808
+ }
1809
+ scrubber ??= (await traceCollector()).collector.scrubberFor();
1810
+ return { workspace: workspace2, body: await collectorBody(local.trace, device, scrubber) };
1811
+ }
1812
+ const parsed = local.harness === "claude_code" ? await parseClaudeSession(local) : await parseCodexSession(local);
1813
+ if (leftOut(local, parsed.cwd)) return null;
1814
+ const workspace = routeSession(parsed.cwd, config);
1815
+ if (!workspace) {
1816
+ report.local++;
1817
+ record(local, { workspace: null, status: "local" });
1818
+ return null;
1819
+ }
1820
+ return { workspace, body: uploadBody(parsed, sessionDigest(parsed), device) };
1821
+ };
1822
+ for (let start = 0; start < pending.length; start += UPLOAD_CONCURRENCY) {
1823
+ const ready = [];
1824
+ await pool(pending.slice(start, start + UPLOAD_CONCURRENCY), UPLOAD_CONCURRENCY, async (local) => {
1825
+ try {
1826
+ const prepared = await prepare(local);
1827
+ if (!prepared) return;
1828
+ if (options.dryRun) {
1829
+ const directory = mkdtempSync(join4(skyDir(), "trace-dry-run-"));
1830
+ try {
1831
+ const source2 = await captureTraceSource(local, directory, { workspace: prepared.workspace, apiBase: endpoint });
1832
+ const checked = await libraryRequest("POST", "/trace-library/check", prepared.workspace, { sessions: [{ harness: local.harness, session_id: local.sessionId, sha256: source2.sha256 }] });
1833
+ if (checked.sessions[0]?.status === "owned") {
1834
+ report.owned++;
1835
+ return;
1836
+ }
1837
+ report.uploaded++;
1838
+ report.byWorkspace[prepared.workspace] = (report.byWorkspace[prepared.workspace] ?? 0) + 1;
1839
+ } finally {
1840
+ rmSync2(directory, { recursive: true, force: true });
1841
+ }
1842
+ return;
1843
+ }
1844
+ const item = beginPendingSource(queueRoot, {
1845
+ apiBase: endpoint,
1846
+ workspace: prepared.workspace,
1847
+ local: { harness: local.harness, sessionId: local.sessionId, signature: local.signature, files: local.files },
1848
+ body: prepared.body
1849
+ });
1850
+ const source = await captureTraceSource(local, item.directory, { workspace: prepared.workspace, apiBase: item.manifest.apiBase });
1851
+ completePendingCapture(item, source);
1852
+ ready.push(item);
1853
+ } catch (error) {
1854
+ fail(`${key(local)}: source capture failed`, error);
1855
+ }
1856
+ });
1857
+ await pool(ready, UPLOAD_CONCURRENCY, send);
1858
+ if (blocked) break;
1859
+ options.onProgress?.(`${Math.min(start + UPLOAD_CONCURRENCY, pending.length)}/${pending.length} checked, ${report.uploaded} uploaded so far`);
1860
+ }
1861
+ if (!options.dryRun) {
1862
+ if (full && !options.only?.length && !options.limit && report.failed === 0) state.lastFullAt = (/* @__PURE__ */ new Date()).toISOString();
1863
+ writePrivateJson(statePath2(), state);
1864
+ }
1865
+ return report;
1866
+ }
1867
+ function hookSessionRef(payload) {
1868
+ try {
1869
+ const value = asRecord(JSON.parse(payload));
1870
+ return str2(value?.transcript_path) ?? str2(value?.session_id) ?? str2(value?.["thread-id"]) ?? str2(value?.thread_id);
1871
+ } catch {
1872
+ return void 0;
1873
+ }
1874
+ }
1875
+ var LAUNCHD_LABEL = "dev.agentsky.trace-sync";
1876
+ function launchdPlistPath(home = homedir4()) {
1877
+ return join4(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
1878
+ }
1879
+ function launchdPlist(command, logPath) {
1880
+ const escape = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1881
+ return `<?xml version="1.0" encoding="UTF-8"?>
1882
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1883
+ <plist version="1.0">
1884
+ <dict>
1885
+ <key>Label</key><string>${LAUNCHD_LABEL}</string>
1886
+ <key>ProgramArguments</key>
1887
+ <array>
1888
+ ${command.map((part) => ` <string>${escape(part)}</string>`).join("\n")}
1889
+ </array>
1890
+ <key>StartInterval</key><integer>900</integer>
1891
+ <key>RunAtLoad</key><true/>
1892
+ <key>ProcessType</key><string>Background</string>
1893
+ <key>StandardOutPath</key><string>${escape(logPath)}</string>
1894
+ <key>StandardErrorPath</key><string>${escape(logPath)}</string>
1895
+ </dict>
1896
+ </plist>
1897
+ `;
1898
+ }
1899
+ function installLaunchd(command, logPath) {
1900
+ if (process.platform !== "darwin") throw new Error("the schedule installer covers macOS; on Linux add `*/15 * * * * sky trace sync --quiet` to your crontab");
1901
+ const plist = launchdPlistPath();
1902
+ mkdirSync2(dirname5(plist), { recursive: true });
1903
+ writeFileSync2(plist, launchdPlist(command, logPath));
1904
+ return plist;
1905
+ }
1906
+ var SYNC_HOOK_COMMAND = "sky trace sync --hook";
1907
+ function installSyncHooks(home = homedir4(), codexHome = process.env.CODEX_HOME || join4(home, ".codex")) {
1908
+ const lines = [];
1909
+ const claudeSettings = join4(home, ".claude", "settings.json");
1910
+ installClaudeHooks(claudeSettings, SYNC_HOOK_COMMAND, { Stop: [{ hooks: [{ type: "command", command: SYNC_HOOK_COMMAND, timeout: 10 }] }] });
1911
+ lines.push(`Claude Code: syncs at the end of every turn (${claudeSettings}).`);
1912
+ const codexConfig = join4(codexHome, "config.toml");
1913
+ const text = existsSync3(codexConfig) ? readFileSync4(codexConfig, "utf8") : "";
1914
+ const topLevel = text.split(/^\s*\[/m, 1)[0] ?? "";
1915
+ const notify = /^\s*notify\s*=.*$/m.exec(topLevel)?.[0];
1916
+ 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.`);
1917
+ else if (notify) lines.push(`Codex: already syncs at the end of every turn (${codexConfig}).`);
1918
+ else {
1919
+ mkdirSync2(dirname5(codexConfig), { recursive: true });
1920
+ writeFileSync2(codexConfig, `notify = ["sky", "trace", "sync", "--hook"]
1921
+ ${text}`);
1922
+ lines.push(`Codex: syncs at the end of every turn (${codexConfig}).`);
1923
+ }
1924
+ return lines;
1925
+ }
1926
+ function syncDir() {
1927
+ return skyDir();
1928
+ }
1929
+
1930
+ export {
1931
+ importReadAllowed,
1932
+ importPathAllowed,
1933
+ repositoryRoot,
1934
+ sharedInstructionPaths,
1935
+ loadedSkills,
1936
+ workspaceState,
1937
+ skillFiles,
1938
+ codexThreadName,
1939
+ SINGLE_REQUEST_MAX_BYTES,
1940
+ transfer,
1941
+ uploadLargeFile,
1942
+ syncConfigPath,
1943
+ lastUploads,
1944
+ loadSyncConfig,
1945
+ saveSyncConfig,
1946
+ collectorHarness,
1947
+ sourceFolders,
1948
+ supportedAgents,
1949
+ importExport,
1950
+ discoverSessions,
1951
+ collectorBody,
1952
+ parseClaudeSession,
1953
+ parseCodexSession,
1954
+ isTrivial,
1955
+ sessionDigest,
1956
+ projectOf,
1957
+ repoRemote,
1958
+ routeSession,
1959
+ libraryRequest,
1960
+ syncTraces,
1961
+ hookSessionRef,
1962
+ LAUNCHD_LABEL,
1963
+ launchdPlistPath,
1964
+ launchdPlist,
1965
+ installLaunchd,
1966
+ SYNC_HOOK_COMMAND,
1967
+ installSyncHooks,
1968
+ syncDir
1969
+ };