@agentsky/sky 3.41.0 → 3.43.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,1559 @@
1
+ import {
2
+ importPathAllowed,
3
+ uploadLargeFile
4
+ } from "./chunk-AB7SUDX4.js";
5
+ import {
6
+ installClaudeHooks
7
+ } from "./chunk-4MVM65ET.js";
8
+ import {
9
+ IncompleteSourceCaptureError,
10
+ SOURCE_CAPTURE_VERSION,
11
+ beginPendingSource,
12
+ canonicalSourceApiBase,
13
+ captureTraceSource,
14
+ completePendingCapture,
15
+ excludedBy,
16
+ listPendingSources,
17
+ loadExclusions,
18
+ recoverPendingSource,
19
+ removePendingSource,
20
+ savePendingSource,
21
+ stillExcluded,
22
+ writePrivateJson
23
+ } from "./chunk-UJ7IXSJX.js";
24
+ import {
25
+ SessionSourceCollector,
26
+ publicRemote,
27
+ redactTraceText
28
+ } from "./chunk-BIZJ4VZL.js";
29
+ import {
30
+ ApiError
31
+ } from "./chunk-44XF4EGE.js";
32
+ import {
33
+ loadLocalSkillState,
34
+ revisionAt
35
+ } from "./chunk-J3KIEZXM.js";
36
+ import {
37
+ USER_AGENT
38
+ } from "./chunk-4A4PDUT5.js";
39
+ import {
40
+ apiBase,
41
+ apiToken
42
+ } from "./chunk-XHZJG3QT.js";
43
+ import "./chunk-MLKGABMK.js";
44
+
45
+ // 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";
48
+ 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";
51
+ import { fileURLToPath, pathToFileURL } from "url";
52
+ import { createGunzip } from "zlib";
53
+
54
+ // src/trace-references.ts
55
+ import { execFileSync } from "child_process";
56
+ import { existsSync } from "fs";
57
+ import { homedir } from "os";
58
+ import { dirname } from "path";
59
+ var PULL_URL = /github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/([1-9][0-9]{0,8})/g;
60
+ var GMAIL_ID = /(?:message_?id|thread_?id)\\*"?\s*[:=]\s*\\*"?([0-9a-f]{16})\b/gi;
61
+ var GMAIL_PATH = /(?:\/messages\/|\/threads\/|mail\.google\.com\/[^\s"\\]*[#/])([0-9a-f]{16})\b/g;
62
+ var OPENS_PULL = /"(?:command|cmd|input|arguments)\\*"\s*:.*\bgh\s+pr\s+create\b/;
63
+ var RESULT_WINDOW = 8;
64
+ var MAX_PULLS = 80;
65
+ var MAX_GMAIL = 100;
66
+ var TraceReferences = class {
67
+ pulls = /* @__PURE__ */ new Map();
68
+ gmail = /* @__PURE__ */ new Set();
69
+ opening = 0;
70
+ scan(line) {
71
+ const awaiting = this.opening > 0;
72
+ if (awaiting) this.opening--;
73
+ let credited = false;
74
+ for (const match of line.matchAll(PULL_URL)) {
75
+ const id = `${match[1]}/${match[2]}#${match[3]}`.toLowerCase();
76
+ if (id.startsWith("owner/repo#")) continue;
77
+ if (awaiting && !credited) {
78
+ this.pulls.set(id, "authored");
79
+ credited = true;
80
+ this.opening = 0;
81
+ } else if (!this.pulls.has(id)) this.pulls.set(id, "referenced");
82
+ }
83
+ if (OPENS_PULL.test(line)) this.opening = RESULT_WINDOW;
84
+ if (/gmail|mail\.google\.com/i.test(line)) {
85
+ for (const match of line.matchAll(GMAIL_ID)) this.gmail.add(match[1].toLowerCase());
86
+ for (const match of line.matchAll(GMAIL_PATH)) this.gmail.add(match[1].toLowerCase());
87
+ }
88
+ }
89
+ objects() {
90
+ const pulls = [...this.pulls].sort((a, b) => Number(b[1] === "authored") - Number(a[1] === "authored")).slice(0, MAX_PULLS);
91
+ return [
92
+ ...pulls.map(([id, role]) => ({ type: "pr", id, role })),
93
+ ...[...this.gmail].slice(0, MAX_GMAIL).map((id) => ({ type: "gmail_message", id, role: "referenced" }))
94
+ ];
95
+ }
96
+ };
97
+ var remotes = /* @__PURE__ */ new Map();
98
+ function gitRemoteAt(cwd) {
99
+ if (!cwd) return void 0;
100
+ if (remotes.has(cwd)) return remotes.get(cwd);
101
+ let remote;
102
+ const home = homedir();
103
+ for (let folder = cwd; folder !== home && folder !== dirname(folder); folder = dirname(folder)) {
104
+ if (!existsSync(folder)) continue;
105
+ try {
106
+ remote = execFileSync("git", ["-C", folder, "remote", "get-url", "origin"], { encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"] }).trim() || void 0;
107
+ } catch {
108
+ remote = void 0;
109
+ }
110
+ break;
111
+ }
112
+ remotes.set(cwd, remote);
113
+ return remote;
114
+ }
115
+
116
+ // src/session-results.ts
117
+ import { createHash } from "crypto";
118
+ import { readFileSync, statSync } from "fs";
119
+ import { homedir as homedir2 } from "os";
120
+ import { basename, dirname as dirname2, extname, isAbsolute, join, normalize, resolve, sep } from "path";
121
+ var MAX_RESULT_BYTES = 15 * 1024 * 1024;
122
+ var RESULT_TYPES = {
123
+ ".mp4": "video/mp4",
124
+ ".mov": "video/quicktime",
125
+ ".webm": "video/webm",
126
+ ".m4v": "video/x-m4v",
127
+ ".mp3": "audio/mpeg",
128
+ ".wav": "audio/wav",
129
+ ".m4a": "audio/mp4",
130
+ ".aac": "audio/aac",
131
+ ".ogg": "audio/ogg",
132
+ ".flac": "audio/flac",
133
+ ".png": "image/png",
134
+ ".jpg": "image/jpeg",
135
+ ".jpeg": "image/jpeg",
136
+ ".gif": "image/gif",
137
+ ".webp": "image/webp",
138
+ ".svg": "image/svg+xml",
139
+ ".pdf": "application/pdf",
140
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
141
+ ".doc": "application/msword",
142
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
143
+ ".xls": "application/vnd.ms-excel",
144
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
145
+ ".ppt": "application/vnd.ms-powerpoint",
146
+ ".csv": "text/csv",
147
+ ".tsv": "text/tab-separated-values",
148
+ ".html": "text/html",
149
+ ".htm": "text/html",
150
+ ".md": "text/markdown",
151
+ ".markdown": "text/markdown",
152
+ ".txt": "text/plain",
153
+ ".json": "application/json"
154
+ };
155
+ 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" };
156
+ var PUBLISHING_TOOLS = /* @__PURE__ */ new Set(["Artifact"]);
157
+ var SCRATCH_ROOTS = ["/tmp/", "/private/tmp/", "/var/folders/", "/private/var/folders/"];
158
+ var REBUILT = /* @__PURE__ */ new Set(["node_modules", ".git", ".venv", "venv", "__pycache__", ".next", ".nuxt", ".turbo", ".cache", "dist", "build", "out", "target", "DerivedData", "Library", ".Trash"]);
159
+ var PATH_LIKE = /(?:~\/|\.{1,2}\/|\/)?(?:[^\s'"`()<>|;&*?,:=]+\/)*[^\s'"`()<>|;&*?,:=/]+\.[A-Za-z0-9]{1,8}(?![A-Za-z0-9])/g;
160
+ var ATTACHED = /^Attached files:\n((?:- .+(?:\n|$))+)/m;
161
+ var LOCAL_REFERENCE = /(\s(?:src|href)\s*=\s*)(["'])([^"'<>]+)\2/gi;
162
+ var CODEX_CONTEXT = /^\s*(?:<environment_context>|<user_instructions>|<turn_aborted>|# AGENTS\.md instructions)/;
163
+ var obj = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
164
+ var str = (value) => typeof value === "string" ? value : "";
165
+ function typeOf(name, any) {
166
+ const ext = extname(name).toLowerCase();
167
+ return RESULT_TYPES[ext] ?? (any ? OTHER_TYPES[ext] ?? "application/octet-stream" : null);
168
+ }
169
+ function pictureOf(block) {
170
+ const source = obj(block.source);
171
+ if (block.type === "image" && source?.type === "base64" && typeof source.data === "string") return { mediaType: str(source.media_type) || "image/png", data: source.data };
172
+ const inline = block.type === "input_image" ? /^data:(image\/[a-z0-9.+-]+);base64,(.+)$/i.exec(str(block.image_url)) : null;
173
+ return inline ? { mediaType: inline[1], data: inline[2] } : null;
174
+ }
175
+ function turnsOf(records, cwd = "") {
176
+ const turns = [];
177
+ let context = cwd;
178
+ const start = (at, texts, pictures) => turns.push({ since: Date.parse(str(at)) || 0, texts, pictures, said: [], tools: [] });
179
+ for (const raw of records) {
180
+ const record = obj(raw);
181
+ if (!record) continue;
182
+ const payload = obj(record.payload);
183
+ if (record.type === "turn_context" || record.type === "session_meta") context = str(payload?.cwd) || context;
184
+ const here = str(record.cwd) || context;
185
+ const content = obj(record.message)?.content;
186
+ if (record.type === "user") {
187
+ const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content.map(obj).filter(Boolean) : [];
188
+ if (blocks.some((block) => block.type === "tool_result") || record.isMeta === true) continue;
189
+ const texts = blocks.filter((block) => block.type === "text").map((block) => str(block.text));
190
+ if (!texts.some((text) => text.trim()) && !blocks.some((block) => block.type === "image")) continue;
191
+ start(record.timestamp, texts, blocks.map(pictureOf).filter(Boolean));
192
+ continue;
193
+ }
194
+ if (record.type === "assistant" && Array.isArray(content)) {
195
+ const turn = turns.at(-1);
196
+ for (const block of content.map(obj)) {
197
+ if (!turn || !block) continue;
198
+ if (block.type === "text") turn.said.push(str(block.text));
199
+ if (block.type === "tool_use") turn.tools.push({ name: str(block.name), input: block.input, cwd: here });
200
+ }
201
+ continue;
202
+ }
203
+ if (record.type !== "response_item" || !payload) continue;
204
+ if (payload.type === "message") {
205
+ const blocks = Array.isArray(payload.content) ? payload.content.map(obj).filter(Boolean) : [];
206
+ const texts = blocks.filter((block) => block.type === "input_text" || block.type === "output_text" || block.type === "text").map((block) => str(block.text));
207
+ if (payload.role === "user") {
208
+ if (texts.every((text) => !text.trim() || CODEX_CONTEXT.test(text)) && !blocks.some((block) => block.type === "input_image")) continue;
209
+ start(record.timestamp, texts.filter((text) => !CODEX_CONTEXT.test(text)), blocks.map(pictureOf).filter(Boolean));
210
+ } else if (payload.role === "assistant") turns.at(-1)?.said.push(...texts);
211
+ continue;
212
+ }
213
+ if (payload.type === "function_call" || payload.type === "custom_tool_call" || payload.type === "local_shell_call") {
214
+ let input = payload.arguments ?? payload.input ?? payload.action ?? "";
215
+ if (typeof input === "string") {
216
+ try {
217
+ input = JSON.parse(input);
218
+ } catch {
219
+ }
220
+ }
221
+ turns.at(-1)?.tools.push({ name: str(payload.name), input, cwd: str(obj(input)?.workdir) || here });
222
+ }
223
+ }
224
+ return turns;
225
+ }
226
+ function strings(value, into = []) {
227
+ 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);
230
+ return into;
231
+ }
232
+ function resolved(candidate, cwd, home) {
233
+ const text = candidate.replace(/^file:\/\//, "");
234
+ if (text.startsWith("~/")) return join(home, text.slice(2));
235
+ if (isAbsolute(text)) return normalize(text);
236
+ return cwd ? resolve(cwd, text) : null;
237
+ }
238
+ function credential(file) {
239
+ return !importPathAllowed(file);
240
+ }
241
+ function kept(file, home) {
242
+ const inHome = file.startsWith(`${home}/`);
243
+ if (!inHome && SCRATCH_ROOTS.some((root) => file.startsWith(root))) return false;
244
+ 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));
247
+ }
248
+ function inWebProject(file, home, stat) {
249
+ for (let dir = dirname2(file); dir.startsWith(`${home}/`); dir = dirname2(dir)) {
250
+ try {
251
+ if (stat(join(dir, "package.json")).isFile()) return true;
252
+ } catch {
253
+ }
254
+ }
255
+ return false;
256
+ }
257
+ function publishedPaths(tool) {
258
+ if (!PUBLISHING_TOOLS.has(tool.name)) return [];
259
+ const input = obj(tool.input) ?? {};
260
+ const files = obj(input.files) ? Object.values(input.files) : [];
261
+ 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
+ }
263
+ function sessionResults(records, options = {}) {
264
+ const home = options.home ?? homedir2();
265
+ const stat = options.stat ?? statSync;
266
+ const turns = turnsOf(records, options.cwd ?? "");
267
+ const found = [];
268
+ for (const turn of options.all ? turns : turns.slice(-1)) {
269
+ const said = turn.said.join("\n");
270
+ if (!said.trim()) continue;
271
+ const seen = /* @__PURE__ */ new Set();
272
+ const add = (file, origin, mediaType, fresh) => {
273
+ if (seen.has(file)) return;
274
+ seen.add(file);
275
+ let info;
276
+ try {
277
+ info = stat(file);
278
+ } catch {
279
+ return;
280
+ }
281
+ 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 });
283
+ };
284
+ turn.pictures.forEach((picture, index) => {
285
+ const data = Buffer.from(picture.data, "base64");
286
+ if (!data.length || data.length > MAX_RESULT_BYTES) return;
287
+ const ext = picture.mediaType.split("/")[1]?.replace("jpeg", "jpg").replace(/[^a-z0-9]/gi, "") || "png";
288
+ 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 });
289
+ });
290
+ for (const line of (ATTACHED.exec(turn.texts.join("\n"))?.[1] ?? "").split("\n")) {
291
+ const file = line.replace(/^- /, "").trim();
292
+ if (isAbsolute(file) && !credential(normalize(file))) add(normalize(file), "sent", typeOf(file, true), false);
293
+ }
294
+ for (const tool of turn.tools) for (const raw of publishedPaths(tool)) {
295
+ const file = resolved(raw, tool.cwd, home);
296
+ if (file && !credential(file)) add(file, "published", typeOf(file, true), false);
297
+ }
298
+ const texts = [...turn.tools.flatMap((tool) => strings(tool.input)), ...turn.said];
299
+ for (const text of texts) {
300
+ for (const match of text.matchAll(PATH_LIKE)) {
301
+ const tool = turn.tools.find((entry) => strings(entry.input).includes(text));
302
+ const file = resolved(match[0], tool?.cwd ?? options.cwd ?? "", home);
303
+ if (!file || seen.has(file)) continue;
304
+ const name = basename(file);
305
+ const mediaType = typeOf(name, false);
306
+ if (!mediaType || !said.includes(name) || !kept(file, home)) continue;
307
+ if (mediaType === "text/html" && inWebProject(file, home, stat)) continue;
308
+ add(file, "delivered", mediaType, true);
309
+ }
310
+ }
311
+ }
312
+ return found;
313
+ }
314
+ function pageWithImages(bytes, file, home = homedir2(), explicit = false) {
315
+ const html = bytes.toString("utf8");
316
+ const dir = dirname2(file);
317
+ const images = /* @__PURE__ */ new Map();
318
+ let total = bytes.length;
319
+ for (const match of html.matchAll(LOCAL_REFERENCE)) {
320
+ const reference = match[3].trim();
321
+ if (images.has(reference) || /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\/)/i.test(reference)) continue;
322
+ let target;
323
+ try {
324
+ target = resolve(dir, decodeURI(reference.split(/[?#]/, 1)[0]));
325
+ } catch {
326
+ continue;
327
+ }
328
+ const mediaType = typeOf(target, false);
329
+ if (!mediaType?.startsWith("image/") || !(explicit ? target.startsWith(`${dir}${sep}`) : kept(target, home))) continue;
330
+ let image;
331
+ try {
332
+ image = readFileSync(target);
333
+ } catch {
334
+ continue;
335
+ }
336
+ const uri = `data:${mediaType};base64,${image.toString("base64")}`;
337
+ total += uri.length - reference.length;
338
+ if (total > MAX_RESULT_BYTES) return bytes;
339
+ images.set(reference, uri);
340
+ }
341
+ if (!images.size) return bytes;
342
+ 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
+ }
344
+ function resultRequestId(...parts) {
345
+ const hex = createHash("sha256").update(JSON.stringify(parts)).digest("hex");
346
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
347
+ }
348
+ var RateLimited = class extends Error {
349
+ };
350
+ async function call(fetcher, method, path, workspace, body, multipart2) {
351
+ const token = apiToken();
352
+ if (!token) throw new Error("not logged in \u2014 run `sky auth login`");
353
+ const response = await fetcher(`${apiBase()}${path}`, {
354
+ method,
355
+ headers: { authorization: `Bearer ${token}`, "x-universe": workspace, ...multipart2 ? { "content-type": multipart2.type } : body ? { "content-type": "application/json" } : {} },
356
+ body: multipart2 ? new Uint8Array(multipart2.body) : body ? JSON.stringify(body) : void 0,
357
+ signal: AbortSignal.timeout(12e4)
358
+ });
359
+ if (response.status === 429) throw new RateLimited("rate limited");
360
+ const answer = await response.json().catch(() => null);
361
+ if (!response.ok) throw new Error(str(obj(answer?.error)?.message) || `${method} ${path} failed (${response.status})`);
362
+ return answer;
363
+ }
364
+ function multipart(fields) {
365
+ const boundary = `----sky${createHash("sha256").update(fields.requestId).digest("hex").slice(0, 24)}`;
366
+ const filename = fields.name.replace(/[\r\n]/g, " ").replace(/"/g, "%22");
367
+ const field = (key, value) => Buffer.from(`--${boundary}\r
368
+ Content-Disposition: form-data; name="${key}"\r
369
+ \r
370
+ ${value}\r
371
+ `, "utf8");
372
+ return { type: `multipart/form-data; boundary=${boundary}`, body: Buffer.concat([
373
+ Buffer.from(`--${boundary}\r
374
+ Content-Disposition: form-data; name="file"; filename="${filename}"\r
375
+ Content-Type: ${fields.mediaType}\r
376
+ \r
377
+ `, "utf8"),
378
+ fields.bytes,
379
+ Buffer.from("\r\n", "utf8"),
380
+ field("requestId", fields.requestId),
381
+ field("sessionId", fields.sessionId),
382
+ Buffer.from(`--${boundary}--\r
383
+ `, "utf8")
384
+ ]) };
385
+ }
386
+ function readRecords(files) {
387
+ const records = [];
388
+ for (const file of files) {
389
+ if (file.endsWith(".gz")) continue;
390
+ for (const line of readFileSync(file, "utf8").split("\n")) {
391
+ if (!line.trim()) continue;
392
+ try {
393
+ records.push(JSON.parse(line));
394
+ } catch {
395
+ }
396
+ }
397
+ }
398
+ return records;
399
+ }
400
+ async function captureSessionResults(input, state, options = {}) {
401
+ const fetcher = options.fetcher ?? fetch;
402
+ const home = options.home ?? homedir2();
403
+ const key = `${input.harness}:${input.nativeId}`;
404
+ const saved = new Set(state.saved);
405
+ let count = 0;
406
+ let limited = false;
407
+ 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")];
409
+ const id = JSON.stringify(version);
410
+ if (saved.has(id)) continue;
411
+ try {
412
+ const read = result.data ?? readFileSync(result.path);
413
+ if (read.length !== result.size) continue;
414
+ const bytes = result.path && result.mediaType === "text/html" ? pageWithImages(read, result.path, home, result.origin !== "delivered") : read;
415
+ await call(fetcher, "POST", "/library/artifacts", input.workspace, void 0, multipart({ name: result.name, mediaType: result.mediaType, bytes, requestId: resultRequestId(...version), sessionId: input.sessionId }));
416
+ saved.add(id);
417
+ state.saved.push(id);
418
+ count++;
419
+ } catch (error) {
420
+ if (error instanceof RateLimited) {
421
+ limited = true;
422
+ break;
423
+ }
424
+ }
425
+ }
426
+ if (!limited && !state.read.includes(key)) state.read.push(key);
427
+ if (state.saved.length > 2e4) state.saved.splice(0, state.saved.length - 2e4);
428
+ if (state.read.length > 5e3) state.read.splice(0, state.read.length - 5e3);
429
+ return { saved: count };
430
+ }
431
+
432
+ // src/trace-session.ts
433
+ var SESSION_HARNESSES = ["claude_code", "codex"];
434
+ var UPLOADED_MESSAGE_PREFIX = "trace:";
435
+ var SESSION_BACKFILL_DAYS = 30;
436
+ var BATCH_MESSAGES = 200;
437
+ var BATCH_BYTES = 3 * 1024 * 1024;
438
+ var MESSAGE_BYTES = 384 * 1024;
439
+ var HARNESS_BLOCKS = /<(system-reminder|local-command-stdout|local-command-stderr|command-message|command-args|task-notification)>[\s\S]*?<\/\1>/g;
440
+ var SKILL_FILE = /(?:^|[/\s'"=])skills\/([a-z0-9][a-z0-9-]*)\/SKILL\.md/g;
441
+ var WRITING_TOOL = /write|edit|create|delete|patch|apply/i;
442
+ var WRITES_SKILL_FILE = /(?:>|\btee\b|\bsed\s+-i|\brm\b|\bmv\b|\bcp\b|\btouch\b)[^|;&]*SKILL\.md/;
443
+ var TOOL_CALL = /^([A-Za-z_][\w.:-]*) ([{[][\s\S]*)$/;
444
+ function skillNamesRead(text) {
445
+ const call2 = TOOL_CALL.exec(text);
446
+ if (!call2) return [];
447
+ const tool = call2[1];
448
+ const args = call2[2];
449
+ if (tool === "Skill") {
450
+ try {
451
+ const parsed = JSON.parse(args);
452
+ return [parsed.skill, parsed.name].filter((name) => typeof name === "string").map((name) => name.split(":").at(-1));
453
+ } catch {
454
+ return [];
455
+ }
456
+ }
457
+ if (WRITING_TOOL.test(tool) || WRITES_SKILL_FILE.test(args)) return [];
458
+ return [...args.matchAll(SKILL_FILE)].map((match) => match[1]);
459
+ }
460
+ function skillReadsIn(rows, messages, state) {
461
+ const kept2 = new Set(messages.map((message) => message.id));
462
+ const reads = /* @__PURE__ */ new Map();
463
+ let current = null;
464
+ let waiting = [];
465
+ const settle = (messageId) => {
466
+ for (const read of waiting) {
467
+ const revision = revisionAt(state, read.name, read.at);
468
+ if (revision && kept2.has(messageId) && !reads.has(revision)) reads.set(revision, { revision_id: revision, message_id: messageId });
469
+ }
470
+ waiting = [];
471
+ };
472
+ rows.forEach((row, index) => {
473
+ 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 } : {} })));
476
+ if (current?.role === "agent") settle(current.id);
477
+ return;
478
+ }
479
+ const role = row.role === "user" ? "user" : "agent";
480
+ const text = role === "user" ? row.text.replace(HARNESS_BLOCKS, "").trim() : row.text;
481
+ if (!text) return;
482
+ if (!current || current.role !== role) current = { id: `${UPLOADED_MESSAGE_PREFIX}${index}`, role };
483
+ if (role === "agent") settle(current.id);
484
+ });
485
+ return [...reads.values()];
486
+ }
487
+ function sessionHarness(harness) {
488
+ return SESSION_HARNESSES.includes(harness);
489
+ }
490
+ var bytesOf = (value) => Buffer.byteLength(JSON.stringify(value));
491
+ function transcriptMessages(rows, startedAt) {
492
+ const messages = [];
493
+ let at = startedAt && Number.isFinite(Date.parse(startedAt)) ? new Date(startedAt).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString();
494
+ let current = null;
495
+ rows.forEach((row, index) => {
496
+ if (row.at && Number.isFinite(Date.parse(row.at))) at = new Date(row.at).toISOString();
497
+ if (row.role === "tool") return;
498
+ const role = row.role === "user" ? "user" : "agent";
499
+ const text = role === "user" ? row.text.replace(HARNESS_BLOCKS, "").trim() : row.text;
500
+ if (!text) return;
501
+ if (!current || current.role !== role) {
502
+ current = { id: `${UPLOADED_MESSAGE_PREFIX}${index}`, role, created_at: at, parts: [], bytes: 0 };
503
+ messages.push(current);
504
+ }
505
+ const part = { type: "text", index: current.parts.length, text };
506
+ const size = bytesOf(part);
507
+ if (current.bytes + size > MESSAGE_BYTES) return;
508
+ current.parts.push(part);
509
+ current.bytes += size;
510
+ });
511
+ return messages.filter((message) => message.parts.length).map(({ id, role, created_at, parts }) => ({ id, role, created_at, parts }));
512
+ }
513
+ function messageBatches(messages) {
514
+ const batches = [];
515
+ let batch = [];
516
+ let bytes = 0;
517
+ for (const message of messages) {
518
+ const size = bytesOf(message);
519
+ if (batch.length && (batch.length >= BATCH_MESSAGES || bytes + size > BATCH_BYTES)) {
520
+ batches.push(batch);
521
+ batch = [];
522
+ bytes = 0;
523
+ }
524
+ batch.push(message);
525
+ bytes += size;
526
+ }
527
+ if (batch.length) batches.push(batch);
528
+ return batches;
529
+ }
530
+ var refusal = (error) => error instanceof ApiError && error.status !== 429 && (error.status >= 400 && error.status < 500 || error.status === 503);
531
+ async function saveTraceSession(request, input, now = Date.now()) {
532
+ const { harness, sessionId, workspace, body } = input;
533
+ const last = Date.parse(body.ended_at ?? body.started_at ?? "");
534
+ if (Number.isFinite(last) && last < now - SESSION_BACKFILL_DAYS * 864e5) return { status: "older" };
535
+ try {
536
+ const opened = await request("POST", "/threads/local", workspace, {
537
+ harness,
538
+ sourceSessionId: sessionId,
539
+ origin: "terminal",
540
+ ...body.model ? { llm: body.model } : {},
541
+ ...body.title ? { title: body.title.slice(0, 120) } : {},
542
+ ...body.cwd ? { folder: body.cwd } : {},
543
+ machine: body.device.slice(0, 120)
544
+ });
545
+ if (opened.workspace) return { status: "elsewhere", sessionId: opened.sessionId, workspace: opened.workspace };
546
+ let stored = 0;
547
+ const transcript = transcriptMessages(body.messages, body.started_at);
548
+ const reads = input.skills ? skillReadsIn(body.messages, transcript, input.skills).slice(0, 200) : [];
549
+ const batches = messageBatches(transcript);
550
+ for (const [index, messages] of batches.entries()) {
551
+ const last2 = index === batches.length - 1;
552
+ const answer = await request("PUT", `/sessions/${encodeURIComponent(opened.sessionId)}/mirror`, workspace, {
553
+ messages,
554
+ ...index === 0 && body.title ? { title: body.title.slice(0, 120) } : {},
555
+ ...last2 && reads.length ? { skills_read: reads } : {}
556
+ });
557
+ stored += answer.stored;
558
+ }
559
+ return { status: "saved", sessionId: opened.sessionId, stored };
560
+ } catch (error) {
561
+ if (refusal(error)) return { status: "refused", code: error.code };
562
+ throw error;
563
+ }
564
+ }
565
+
566
+ // src/trace-library.ts
567
+ var MESSAGE_MAX_BYTES = 8 * 1024;
568
+ var TOOL_MAX_BYTES = 2 * 1024;
569
+ var MESSAGES_MAX = 2e4;
570
+ var BODY_MAX_BYTES = 7 * 1024 * 1024;
571
+ var UPLOAD_CONCURRENCY = 4;
572
+ var FULL_SWEEP_MS = 7 * 24 * 60 * 60 * 1e3;
573
+ var RESULTS_BACKFILL_MS = SESSION_BACKFILL_DAYS * 24 * 60 * 60 * 1e3;
574
+ var RESULTS_TRIES = 3;
575
+ var RETRIES = 3;
576
+ var RATE_LIMIT_RETRIES = 30;
577
+ var HARNESS_PREAMBLES = ["<environment_context>", "<user_instructions>", "<permissions instructions>", "# AGENTS.md instructions", "<INSTRUCTIONS>", "<external_codex_apps_open_page>"];
578
+ 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));
580
+ var backoffMs = (attempt) => Math.min(3e4, 1e3 * 2 ** attempt);
581
+ function skyDir() {
582
+ return process.env.SKY_CONFIG_DIR ?? join2(homedir3(), ".config", "sky");
583
+ }
584
+ function syncConfigPath() {
585
+ return join2(skyDir(), "trace-sync.json");
586
+ }
587
+ function resultsStatePath() {
588
+ return join2(skyDir(), "session-results.json");
589
+ }
590
+ function statePath() {
591
+ return join2(skyDir(), "trace-sync-state.json");
592
+ }
593
+ function readJson(path, fallback) {
594
+ try {
595
+ return JSON.parse(readFileSync2(path, "utf8"));
596
+ } catch {
597
+ return fallback;
598
+ }
599
+ }
600
+ function writeJson(path, value) {
601
+ mkdirSync(dirname3(path), { recursive: true });
602
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
603
+ `, { mode: 384 });
604
+ }
605
+ function loadSyncConfig() {
606
+ return readJson(syncConfigPath(), { enabled: false, rules: [] });
607
+ }
608
+ function saveSyncConfig(config) {
609
+ writeJson(syncConfigPath(), config);
610
+ }
611
+ function claudeRoot() {
612
+ return join2(process.env.CLAUDE_CONFIG_DIR ?? join2(homedir3(), ".claude"), "projects");
613
+ }
614
+ function codexRoot() {
615
+ return process.env.CODEX_HOME ?? join2(homedir3(), ".codex");
616
+ }
617
+ var SKY_PARSED = /* @__PURE__ */ new Set(["claude-code", "codex"]);
618
+ var COLLECTOR_HARNESS = { "claude-code": "claude_code", codex: "codex" };
619
+ var collectorModules;
620
+ async function traceCollector() {
621
+ const dir = join2(dirname3(fileURLToPath(import.meta.url)), "..", "vendor", "trace-collect");
622
+ collectorModules ??= Promise.all([
623
+ import(pathToFileURL(join2(dir, "collect.mjs")).href),
624
+ import(pathToFileURL(join2(dir, "sinks", "agentsky.mjs")).href)
625
+ ]).then(([collector, sink]) => ({ collector, sink }));
626
+ return collectorModules;
627
+ }
628
+ function collectorHarness(harness) {
629
+ return COLLECTOR_HARNESS[harness] ?? harness.replace(/[^a-z0-9_-]/g, "_").slice(0, 40);
630
+ }
631
+ async function sourceFolders() {
632
+ const { collector } = await traceCollector();
633
+ 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];
635
+ }
636
+ async function supportedAgents() {
637
+ const { collector } = await traceCollector();
638
+ return (await collector.describeSources()).map(({ id, name, kind, found }) => ({ id, name, kind, found: found.length > 0 }));
639
+ }
640
+ async function importExport(input) {
641
+ const { collector } = await traceCollector();
642
+ const result = await collector.importFile(input);
643
+ if (result.error) throw new Error(result.error);
644
+ return { agent: result.name ?? result.id ?? "export", sessions: result.total ?? 0 };
645
+ }
646
+ function signatureOf(files) {
647
+ const parts = [];
648
+ for (const file of files) {
649
+ try {
650
+ const stat = statSync2(file);
651
+ parts.push(`${file}:${stat.size}:${Math.floor(stat.mtimeMs)}`);
652
+ } catch {
653
+ return null;
654
+ }
655
+ }
656
+ return parts.join("|");
657
+ }
658
+ function claudeSessions() {
659
+ const root = claudeRoot();
660
+ const found = [];
661
+ let projects;
662
+ try {
663
+ projects = readdirSync(root);
664
+ } catch {
665
+ return found;
666
+ }
667
+ for (const project of projects) {
668
+ const dir = join2(root, project);
669
+ let entries;
670
+ try {
671
+ entries = readdirSync(dir);
672
+ } catch {
673
+ continue;
674
+ }
675
+ for (const entry of entries) {
676
+ if (!entry.endsWith(".jsonl")) continue;
677
+ const sessionId = entry.slice(0, -".jsonl".length);
678
+ const files = [join2(dir, entry)];
679
+ const subagents = join2(dir, sessionId, "subagents");
680
+ try {
681
+ files.push(...readdirSync(subagents).filter((name) => name.endsWith(".jsonl")).sort().map((name) => join2(subagents, name)));
682
+ } catch {
683
+ }
684
+ const signature = signatureOf(files);
685
+ if (signature) found.push({ harness: "claude_code", sessionId, files, signature });
686
+ }
687
+ }
688
+ return found;
689
+ }
690
+ async function* readLines(file) {
691
+ const raw = createReadStream(file);
692
+ const input = file.endsWith(".gz") ? raw.pipe(createGunzip()) : raw;
693
+ const reader = createInterface({ input, crlfDelay: Infinity });
694
+ try {
695
+ for await (const line of reader) yield line;
696
+ } finally {
697
+ reader.close();
698
+ raw.destroy();
699
+ }
700
+ }
701
+ async function firstLine(file) {
702
+ for await (const line of readLines(file)) return line.length > 1024 * 1024 ? "" : line;
703
+ return "";
704
+ }
705
+ function codexIdCachePath() {
706
+ return join2(skyDir(), "trace-sync-codex-ids.json");
707
+ }
708
+ async function codexSessions() {
709
+ const byId = /* @__PURE__ */ new Map();
710
+ const cached = readJson(codexIdCachePath(), {});
711
+ const seen = {};
712
+ const walk = async (dir) => {
713
+ let entries;
714
+ try {
715
+ entries = readdirSync(dir, { withFileTypes: true });
716
+ } catch {
717
+ return;
718
+ }
719
+ for (const entry of entries) {
720
+ const full = join2(dir, entry.name);
721
+ if (entry.isDirectory()) {
722
+ await walk(full);
723
+ continue;
724
+ }
725
+ if (!entry.name.startsWith("rollout-") || !/\.jsonl(\.gz)?$/.test(entry.name)) continue;
726
+ const signature = signatureOf([full]);
727
+ if (!signature) continue;
728
+ let id = cached[full]?.signature === signature ? cached[full].id : void 0;
729
+ if (!id) {
730
+ try {
731
+ const meta = JSON.parse(await firstLine(full));
732
+ if (meta?.type === "session_meta" && typeof meta.payload?.id === "string") id = meta.payload.id;
733
+ } catch {
734
+ continue;
735
+ }
736
+ }
737
+ if (!id) continue;
738
+ seen[full] = { signature, id };
739
+ const mtime = statSync2(full).mtimeMs;
740
+ const known = byId.get(id);
741
+ if (!known || mtime > known.mtime) byId.set(id, { harness: "codex", sessionId: id, files: [full], signature, mtime });
742
+ }
743
+ };
744
+ await walk(join2(codexRoot(), "sessions"));
745
+ await walk(join2(codexRoot(), "archived_sessions"));
746
+ try {
747
+ writeJson(codexIdCachePath(), seen);
748
+ } catch {
749
+ }
750
+ return [...byId.values()].map(({ mtime: _mtime, ...session }) => session);
751
+ }
752
+ function claudeSessionAt(path) {
753
+ 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");
756
+ const files = [path];
757
+ const subagents = join2(dirname3(path), sessionId, "subagents");
758
+ try {
759
+ files.push(...readdirSync(subagents).filter((name) => name.endsWith(".jsonl")).sort().map((name) => join2(subagents, name)));
760
+ } catch {
761
+ }
762
+ const signature = signatureOf(files);
763
+ return signature ? { harness: "claude_code", sessionId, files, signature } : null;
764
+ }
765
+ async function collectorSessions() {
766
+ const { collector } = await traceCollector();
767
+ const report = await collector.collect();
768
+ const failed = report.filter((entry) => entry.error);
769
+ if (failed.length) throw new Error(failed.map((entry) => `${entry.id}: ${entry.error}`).join("; "));
770
+ const harness = (await collector.loadSources()).map((source) => source.id).filter((id) => !SKY_PARSED.has(id));
771
+ const found = /* @__PURE__ */ new Map();
772
+ for await (const { file, trace, id } of collector.sessions({ harness, children: true })) {
773
+ const signature = signatureOf([file]);
774
+ if (!signature) continue;
775
+ const session = { harness: collectorHarness(trace.harness), sessionId: String(id).slice(0, 200), files: [file], signature, trace };
776
+ found.set(`${session.harness}:${session.sessionId}`, session);
777
+ }
778
+ return [...found.values()];
779
+ }
780
+ async function discoverSessions(onCollectorError) {
781
+ let others = [];
782
+ try {
783
+ others = await collectorSessions();
784
+ } catch (error) {
785
+ if (!onCollectorError) throw error;
786
+ onCollectorError(error);
787
+ }
788
+ return [...claudeSessions(), ...await codexSessions(), ...others];
789
+ }
790
+ function asRecord(value) {
791
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
792
+ }
793
+ function str2(value) {
794
+ return typeof value === "string" && value.length ? value : void 0;
795
+ }
796
+ function toolResultText(content) {
797
+ if (typeof content === "string") return content;
798
+ if (Array.isArray(content)) return content.map((part) => str2(asRecord(part)?.text) ?? "").filter(Boolean).join("\n");
799
+ return "";
800
+ }
801
+ function stringify(value) {
802
+ if (typeof value === "string") return value;
803
+ try {
804
+ return JSON.stringify(value);
805
+ } catch {
806
+ return "";
807
+ }
808
+ }
809
+ var Collector = class {
810
+ messages = [];
811
+ conversation = [];
812
+ partial = false;
813
+ bytes = 0;
814
+ push(role, text, at, inConversation = true) {
815
+ const trimmed = text.replace(/\u0000/g, "").trim();
816
+ if (!trimmed) return;
817
+ if (this.messages.length >= MESSAGES_MAX) {
818
+ this.partial = true;
819
+ return;
820
+ }
821
+ const safe = redactTraceText(trimmed, role === "tool" ? TOOL_MAX_BYTES : MESSAGE_MAX_BYTES);
822
+ if (safe.truncated) this.partial = true;
823
+ this.bytes += Buffer.byteLength(safe.text) + 80;
824
+ this.messages.push({ role, text: safe.text, ...at ? { at } : {} });
825
+ this.conversation.push(inConversation);
826
+ }
827
+ };
828
+ function isoOrUndefined(value) {
829
+ const text = str2(value);
830
+ if (!text) return void 0;
831
+ const time = Date.parse(text);
832
+ return Number.isFinite(time) ? new Date(time).toISOString() : void 0;
833
+ }
834
+ async function collectorBody(trace, device, scrubber) {
835
+ const { collector, sink } = await traceCollector();
836
+ const scrubbed = (scrubber ?? collector.scrubberFor()).scrub(trace);
837
+ return sink.toLibrary({ ...scrubbed, cwd: trace.cwd, stats: trace.stats }, device);
838
+ }
839
+ async function parseClaudeSession(session) {
840
+ const out = { harness: "claude_code", sessionId: session.sessionId, userTurns: 0, toolCalls: 0, partial: false, messages: [], conversation: [] };
841
+ const collector = new Collector();
842
+ const source = new SessionSourceCollector();
843
+ const references = new TraceReferences();
844
+ for (const [index, file] of session.files.entries()) {
845
+ for await (const line of readLines(file)) {
846
+ if (!line.trim()) continue;
847
+ references.scan(line);
848
+ let record;
849
+ try {
850
+ record = asRecord(JSON.parse(line));
851
+ } catch {
852
+ out.partial = true;
853
+ continue;
854
+ }
855
+ if (!record) continue;
856
+ source.push(index === 0 ? record : { ...record, isSidechain: true });
857
+ const at = isoOrUndefined(record.timestamp);
858
+ if (index === 0) {
859
+ out.cwd ??= str2(record.cwd);
860
+ out.gitBranch ??= str2(record.gitBranch);
861
+ if (at) {
862
+ out.startedAt ??= at;
863
+ out.endedAt = at;
864
+ }
865
+ }
866
+ const message = asRecord(record.message);
867
+ if (!message || record.isMeta === true) continue;
868
+ const own = index === 0 && record.isSidechain !== true && record.parent_tool_use_id == null;
869
+ if (record.type === "user") {
870
+ const spoken = own && asRecord(record.origin)?.kind !== "task-notification" && record.promptSource !== "system" && typeof record.wakeupSource !== "string";
871
+ const content = message.content;
872
+ if (typeof content === "string") {
873
+ collector.push("user", content, at, spoken);
874
+ if (index === 0) out.userTurns += 1;
875
+ if (index === 0) out.title ??= titleOf(content);
876
+ continue;
877
+ }
878
+ if (!Array.isArray(content)) continue;
879
+ let typed = false;
880
+ for (const part of content.map(asRecord)) {
881
+ if (part?.type === "text" && str2(part.text)) {
882
+ collector.push("user", part.text, at, spoken);
883
+ typed = true;
884
+ if (index === 0) out.title ??= titleOf(part.text);
885
+ } else if (part?.type === "tool_result") {
886
+ collector.push("tool", toolResultText(part.content), at);
887
+ }
888
+ }
889
+ if (typed && index === 0) out.userTurns += 1;
890
+ } else if (record.type === "assistant") {
891
+ const content = Array.isArray(message.content) ? message.content.map(asRecord) : [];
892
+ for (const part of content) {
893
+ if (part?.type === "text") collector.push("assistant", str2(part.text) ?? "", at, own);
894
+ else if (part?.type === "tool_use") {
895
+ out.toolCalls += 1;
896
+ collector.push("tool", `${str2(part.name) ?? "tool"} ${stringify(part.input)}`, at);
897
+ }
898
+ }
899
+ }
900
+ }
901
+ }
902
+ return withWorkLinks(finish(withSource(out, source.result()), collector), references);
903
+ }
904
+ async function parseCodexSession(session) {
905
+ const out = { harness: "codex", sessionId: session.sessionId, userTurns: 0, toolCalls: 0, partial: false, messages: [], conversation: [] };
906
+ const collector = new Collector();
907
+ const source = new SessionSourceCollector();
908
+ const references = new TraceReferences();
909
+ for await (const line of readLines(session.files[0])) {
910
+ if (!line.trim()) continue;
911
+ references.scan(line);
912
+ let record;
913
+ try {
914
+ record = asRecord(JSON.parse(line));
915
+ } catch {
916
+ out.partial = true;
917
+ continue;
918
+ }
919
+ source.push(record);
920
+ const payload = asRecord(record?.payload);
921
+ if (!record || !payload) continue;
922
+ const at = isoOrUndefined(record.timestamp);
923
+ if (at) {
924
+ out.startedAt ??= at;
925
+ out.endedAt = at;
926
+ }
927
+ if (record.type === "session_meta") {
928
+ out.cwd ??= str2(payload.cwd);
929
+ } else if (record.type === "turn_context") {
930
+ out.cwd ??= str2(payload.cwd);
931
+ } else if (record.type === "response_item") {
932
+ if (payload.type === "message") {
933
+ const role = payload.role === "user" ? "user" : payload.role === "assistant" ? "assistant" : null;
934
+ if (!role) continue;
935
+ const text = (Array.isArray(payload.content) ? payload.content : []).map((part) => str2(asRecord(part)?.text) ?? "").filter(Boolean).join("\n");
936
+ if (role === "user" && HARNESS_PREAMBLES.some((prefix) => text.trimStart().startsWith(prefix))) continue;
937
+ collector.push(role, text, at);
938
+ if (role === "user" && text.trim()) {
939
+ out.userTurns += 1;
940
+ out.title ??= titleOf(text);
941
+ }
942
+ } else if (payload.type === "function_call" || payload.type === "custom_tool_call" || payload.type === "local_shell_call") {
943
+ out.toolCalls += 1;
944
+ collector.push("tool", `${str2(payload.name) ?? payload.type} ${stringify(payload.arguments ?? payload.input ?? payload.action)}`, at);
945
+ } else if (payload.type === "function_call_output" || payload.type === "custom_tool_call_output") {
946
+ const output = asRecord(payload.output);
947
+ collector.push("tool", str2(output?.content) ?? stringify(payload.output), at);
948
+ }
949
+ }
950
+ }
951
+ return withWorkLinks(finish(withSource(out, source.result()), collector), references);
952
+ }
953
+ function withWorkLinks(out, references) {
954
+ const remote = out.gitRemote ?? gitRemoteAt(out.cwd);
955
+ return { ...out, ...remote ? { gitRemote: publicRemote(remote) } : {}, workObjects: references.objects() };
956
+ }
957
+ function withSource(out, meta) {
958
+ return {
959
+ ...out,
960
+ gitBranch: out.gitBranch ?? meta.git?.branch,
961
+ gitCommit: meta.git?.commit,
962
+ gitRemote: meta.git?.remote ? publicRemote(meta.git.remote) : void 0,
963
+ model: meta.models?.[0],
964
+ models: meta.models,
965
+ harnessVersion: meta.harness_version,
966
+ client: meta.client,
967
+ modelProvider: meta.model_provider,
968
+ effort: meta.effort,
969
+ usage: meta.usage
970
+ };
971
+ }
972
+ function finish(out, collector) {
973
+ let messages = collector.messages;
974
+ const conversation = [...collector.conversation];
975
+ let partial = out.partial || collector.partial;
976
+ let bytes = collector.bytes;
977
+ if (bytes > BODY_MAX_BYTES) {
978
+ messages = messages.map((message) => message.role === "tool" && message.text.length > 256 ? { ...message, text: `${message.text.slice(0, 256)}\u2026` } : message);
979
+ bytes = messages.reduce((sum, message) => sum + Buffer.byteLength(message.text) + 80, 0);
980
+ partial = true;
981
+ }
982
+ while (bytes > BODY_MAX_BYTES && messages.length) {
983
+ const from = Math.floor(messages.length / 2), count = Math.max(1, Math.floor(messages.length / 10));
984
+ const dropped = messages.splice(from, count);
985
+ conversation.splice(from, count);
986
+ bytes -= dropped.reduce((sum, message) => sum + Buffer.byteLength(message.text) + 80, 0);
987
+ }
988
+ return { ...out, title: out.title ? redactTraceText(out.title, 300).text : void 0, partial, messages, conversation };
989
+ }
990
+ function isTrivial(session) {
991
+ if (!session.messages.length) return true;
992
+ const chars = session.messages.reduce((sum, message) => sum + message.text.length, 0);
993
+ return session.toolCalls === 0 && session.messages.length <= 2 && chars < 200;
994
+ }
995
+ function sessionDigest(session) {
996
+ const hash = createHash2("sha256");
997
+ hash.update(`${session.cwd ?? ""}${session.model ?? ""}`);
998
+ for (const message of session.messages) hash.update(`${message.role}\0${message.text}`);
999
+ return hash.digest("hex");
1000
+ }
1001
+ function projectOf(cwd) {
1002
+ const parts = cwd.split(sep2).filter(Boolean);
1003
+ for (const marker of [".worktrees", "worktrees"]) {
1004
+ const at = parts.lastIndexOf(marker);
1005
+ if (at > 0) {
1006
+ const owner = parts[at - 1] === ".claude" ? at - 2 : at - 1;
1007
+ if (owner >= 0) return parts[owner];
1008
+ }
1009
+ }
1010
+ let dir = cwd;
1011
+ while (dir && dir !== dirname3(dir)) {
1012
+ if (existsSync2(join2(dir, ".git"))) return basename2(dir);
1013
+ dir = dirname3(dir);
1014
+ }
1015
+ return parts.at(-1);
1016
+ }
1017
+ function workspaceFile(cwd) {
1018
+ 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);
1023
+ if (workspace) return workspace;
1024
+ }
1025
+ if (existsSync2(join2(dir, ".git"))) return void 0;
1026
+ dir = dirname3(dir);
1027
+ }
1028
+ return void 0;
1029
+ }
1030
+ function gitConfigPath(root) {
1031
+ const dotGit = join2(root, ".git");
1032
+ try {
1033
+ if (statSync2(dotGit).isDirectory()) return join2(dotGit, "config");
1034
+ const pointer = readFileSync2(dotGit, "utf8").match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();
1035
+ 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");
1039
+ } catch {
1040
+ return void 0;
1041
+ }
1042
+ }
1043
+ function repoRemote(cwd) {
1044
+ let dir = cwd;
1045
+ while (dir && dir !== dirname3(dir)) {
1046
+ if (existsSync2(join2(dir, ".git"))) {
1047
+ const config = gitConfigPath(dir);
1048
+ if (!config) return void 0;
1049
+ try {
1050
+ const text = readFileSync2(config, "utf8");
1051
+ return text.match(/\[remote "origin"\][^[]*?url\s*=\s*(\S+)/)?.[1];
1052
+ } catch {
1053
+ return void 0;
1054
+ }
1055
+ }
1056
+ dir = dirname3(dir);
1057
+ }
1058
+ return void 0;
1059
+ }
1060
+ function routeSession(cwd, config) {
1061
+ if (cwd) {
1062
+ const pinned = workspaceFile(cwd);
1063
+ if (pinned) return pinned;
1064
+ const lower = `${cwd}
1065
+ ${repoRemote(cwd) ?? ""}`.toLowerCase();
1066
+ const rule = config.rules.find((candidate) => lower.includes(candidate.match.toLowerCase()));
1067
+ if (rule) return rule.workspace;
1068
+ }
1069
+ return config.fallback ?? null;
1070
+ }
1071
+ function homeLabel(path) {
1072
+ if (!path) return void 0;
1073
+ const home = homedir3();
1074
+ return path === home || path.startsWith(`${home}${sep2}`) ? `~${path.slice(home.length)}` : path;
1075
+ }
1076
+ async function libraryRequest(method, path, workspace, body, timeoutMs = 12e4) {
1077
+ const token = apiToken();
1078
+ if (!token) throw new ApiError(401, "not_logged_in", "not logged in \u2014 run `sky auth login`");
1079
+ const payload = body ? JSON.stringify(body) : void 0;
1080
+ let res;
1081
+ for (let attempt = 0; ; attempt++) {
1082
+ try {
1083
+ res = await fetch(`${apiBase()}${path}`, {
1084
+ method,
1085
+ headers: { "user-agent": USER_AGENT, authorization: `Bearer ${token}`, "x-universe": workspace, ...payload ? { "content-type": "application/json" } : {} },
1086
+ body: payload,
1087
+ signal: AbortSignal.timeout(timeoutMs)
1088
+ });
1089
+ } catch (error) {
1090
+ if (attempt >= RETRIES) throw error;
1091
+ await sleep(backoffMs(attempt));
1092
+ continue;
1093
+ }
1094
+ if (res.status === 429 && attempt < RATE_LIMIT_RETRIES) {
1095
+ const wait = Number(res.headers.get("retry-after"));
1096
+ await sleep(Number.isFinite(wait) && wait > 0 ? Math.min(wait, 65) * 1e3 : backoffMs(attempt));
1097
+ continue;
1098
+ }
1099
+ if (res.status >= 500 && res.status !== 503 && attempt < RETRIES) {
1100
+ await sleep(backoffMs(attempt));
1101
+ continue;
1102
+ }
1103
+ break;
1104
+ }
1105
+ if (!res.ok) {
1106
+ let code = "http_error";
1107
+ let message = `${res.status} ${res.statusText}`;
1108
+ try {
1109
+ const parsed = await res.json();
1110
+ code = parsed.error?.code ?? code;
1111
+ message = parsed.error?.message ?? message;
1112
+ } catch {
1113
+ }
1114
+ throw new ApiError(res.status, code, message);
1115
+ }
1116
+ return await res.json();
1117
+ }
1118
+ function uploadBody(session, sha256, device) {
1119
+ const cwd = homeLabel(session.cwd);
1120
+ return {
1121
+ sha256,
1122
+ ...session.workObjects?.length ? { work_objects: session.workObjects } : {},
1123
+ ...session.title ? { title: session.title } : {},
1124
+ ...cwd ? { cwd: cwd.slice(0, 1024) } : {},
1125
+ ...session.cwd && projectOf(session.cwd) ? { project: projectOf(session.cwd).slice(0, 200) } : {},
1126
+ ...session.gitBranch ? { git_branch: session.gitBranch.slice(0, 300) } : {},
1127
+ ...session.gitCommit ? { git_commit: session.gitCommit.slice(0, 80) } : {},
1128
+ ...session.gitRemote ? { git_remote: session.gitRemote.slice(0, 1024) } : {},
1129
+ ...session.model ? { model: session.model.slice(0, 200) } : {},
1130
+ ...session.models?.length ? { models: session.models.slice(0, 50).map((model) => model.slice(0, 200)) } : {},
1131
+ ...session.harnessVersion ? { harness_version: session.harnessVersion.slice(0, 80) } : {},
1132
+ ...session.client ? { client: session.client.slice(0, 200) } : {},
1133
+ ...session.modelProvider ? { model_provider: session.modelProvider.slice(0, 100) } : {},
1134
+ ...session.effort ? { effort: session.effort.slice(0, 100) } : {},
1135
+ ...session.usage && Object.keys(session.usage).length ? { usage: session.usage } : {},
1136
+ device: device.slice(0, 200),
1137
+ ...session.startedAt ? { started_at: session.startedAt } : {},
1138
+ ...session.endedAt ? { ended_at: session.endedAt } : {},
1139
+ user_turns: session.userTurns,
1140
+ tool_calls: session.toolCalls,
1141
+ partial: session.partial,
1142
+ messages: session.messages,
1143
+ outside_conversation: session.conversation.flatMap((inside, index) => inside ? [] : [index])
1144
+ };
1145
+ }
1146
+ function lockPath() {
1147
+ return join2(skyDir(), "trace-sync.lock");
1148
+ }
1149
+ function takeLock() {
1150
+ const path = lockPath();
1151
+ mkdirSync(skyDir(), { recursive: true });
1152
+ try {
1153
+ mkdirSync(path);
1154
+ } catch {
1155
+ const pid = Number(readJson(join2(path, "pid.json"), {}).pid);
1156
+ let alive = false;
1157
+ try {
1158
+ if (pid) {
1159
+ process.kill(pid, 0);
1160
+ alive = true;
1161
+ }
1162
+ } catch {
1163
+ alive = false;
1164
+ }
1165
+ if (alive) return false;
1166
+ rmSync(path, { recursive: true, force: true });
1167
+ try {
1168
+ mkdirSync(path);
1169
+ } catch {
1170
+ return false;
1171
+ }
1172
+ }
1173
+ writeJson(join2(path, "pid.json"), { pid: process.pid });
1174
+ return true;
1175
+ }
1176
+ function releaseLock() {
1177
+ rmSync(lockPath(), { recursive: true, force: true });
1178
+ }
1179
+ async function pool(items, size, fn) {
1180
+ let next = 0;
1181
+ await Promise.all(Array.from({ length: Math.min(size, items.length) }, async () => {
1182
+ while (next < items.length) await fn(items[next++]);
1183
+ }));
1184
+ }
1185
+ async function syncTraces(options = {}) {
1186
+ const config = loadSyncConfig();
1187
+ if (!config.enabled) throw new Error("trace sync is off on this machine \u2014 turn it on with `sky trace sync --enable`");
1188
+ if (!options.dryRun && !takeLock()) return null;
1189
+ try {
1190
+ return await runSync(config, options);
1191
+ } finally {
1192
+ if (!options.dryRun) releaseLock();
1193
+ }
1194
+ }
1195
+ async function verifyPendingFile(item, source) {
1196
+ const workspace = item.manifest.workspace;
1197
+ let url = `${apiBase()}/files/${encodeURIComponent(item.manifest.fileId)}/content`;
1198
+ let response = await fetch(url, { redirect: "manual", headers: { authorization: `Bearer ${apiToken()}`, "x-universe": workspace, "user-agent": USER_AGENT } });
1199
+ for (let redirects = 0; response.status >= 300 && response.status < 400 && redirects < 5; redirects++) {
1200
+ const location = response.headers.get("location");
1201
+ if (!location) throw new Error("Stored source redirect has no location.");
1202
+ url = new URL(location, url).href;
1203
+ if (!/^https?:/.test(url)) throw new Error("Stored source redirect has an invalid protocol.");
1204
+ response = await fetch(url, { redirect: "manual", headers: { "user-agent": USER_AGENT } });
1205
+ }
1206
+ if (!response.ok || !response.body) throw new Error(`Cannot verify stored source file (${response.status}).`);
1207
+ const hash = createHash2("sha256");
1208
+ let bytes = 0;
1209
+ const reader = response.body.getReader();
1210
+ try {
1211
+ while (true) {
1212
+ const part = await reader.read();
1213
+ if (part.done) break;
1214
+ hash.update(part.value);
1215
+ bytes += part.value.length;
1216
+ }
1217
+ } finally {
1218
+ reader.releaseLock();
1219
+ }
1220
+ 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
+ }
1222
+ async function runSync(config, options) {
1223
+ const state = readJson(statePath(), { sessions: {} });
1224
+ const full = options.full || !state.lastFullAt || Date.now() - Date.parse(state.lastFullAt) > FULL_SWEEP_MS;
1225
+ 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: [] });
1228
+ const saveResults = async (local, workspace, sessionId, cwd) => {
1229
+ if (!sessionHarness(local.harness)) return;
1230
+ try {
1231
+ report.results += (await captureSessionResults({ harness: local.harness, nativeId: local.sessionId, sessionId, workspace, files: local.files, cwd: cwd?.replace(/^~(?=\/|$)/, homedir3()) }, results)).saved;
1232
+ } catch (error) {
1233
+ (results.tries ??= {})[key(local)] = (results.tries[key(local)] ?? 0) + 1;
1234
+ report.errors.push(`${key(local)} \u2192 ${workspace}: results not saved yet: ${error.message}`);
1235
+ } finally {
1236
+ writePrivateJson(resultsStatePath(), results);
1237
+ }
1238
+ };
1239
+ const key = (s) => `${s.harness}:${s.sessionId}`;
1240
+ const selected = (s) => !options.only?.length || options.only.includes(s.sessionId) || s.files.some((file) => options.only.includes(file));
1241
+ const record = (s, value) => {
1242
+ state.sessions[key(s)] = { captureVersion: SOURCE_CAPTURE_VERSION, signature: s.signature, at: (/* @__PURE__ */ new Date()).toISOString(), ...value };
1243
+ };
1244
+ const fail = (label, error) => {
1245
+ report.failed++;
1246
+ report.errors.push(`${label}: ${error.message}`);
1247
+ };
1248
+ const exclusions = loadExclusions(skyDir());
1249
+ const leftOut = (local, cwd) => {
1250
+ const hit = excludedBy(exclusions, { harness: local.harness, sessionId: local.sessionId, cwd });
1251
+ if (!hit) return false;
1252
+ report.excluded++;
1253
+ record(local, { workspace: null, status: "excluded", excludedBy: hit.by });
1254
+ return true;
1255
+ };
1256
+ try {
1257
+ report.legacySources = readdirSync(join2(skyDir(), "trace-sources")).filter((name) => /^[a-f0-9]{64}\.jsonl$/.test(name)).length;
1258
+ } catch {
1259
+ }
1260
+ 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");
1262
+ const endpoint = canonicalSourceApiBase(apiBase());
1263
+ const restored = /* @__PURE__ */ new Map();
1264
+ let blocked = false;
1265
+ const unreadable = /* @__PURE__ */ new Set();
1266
+ let scrubber;
1267
+ const collectorFailed = (error) => fail("other agents: unreadable", error);
1268
+ let discovered;
1269
+ const discover = async () => discovered ??= await discoverSessions(collectorFailed);
1270
+ const send = async (item) => {
1271
+ const { workspace } = item.manifest;
1272
+ let capturing = false;
1273
+ let { local } = item.manifest;
1274
+ const queuedCwd = typeof item.manifest.body.cwd === "string" ? item.manifest.body.cwd : void 0;
1275
+ if (leftOut(local, queuedCwd)) {
1276
+ writePrivateJson(statePath(), state);
1277
+ removePendingSource(item);
1278
+ restored.set(key(local), local.signature);
1279
+ return;
1280
+ }
1281
+ try {
1282
+ if (item.manifest.apiBase !== endpoint) throw new Error("Pending source belongs to another API endpoint; restore that endpoint before syncing new sources.");
1283
+ let source;
1284
+ capturing = false;
1285
+ try {
1286
+ source = await recoverPendingSource(item);
1287
+ } catch (error) {
1288
+ if (!(error instanceof IncompleteSourceCaptureError)) throw error;
1289
+ capturing = true;
1290
+ const native = (await discover()).find((s) => key(s) === key(local));
1291
+ if (!native) throw error;
1292
+ const parsed = native.trace ? null : native.harness === "claude_code" ? await parseClaudeSession(native) : await parseCodexSession(native);
1293
+ const nativeCwd = native.trace?.cwd ?? parsed.cwd;
1294
+ if (routeSession(nativeCwd, config) !== workspace) throw new Error("Interrupted capture no longer has its original routing authorization; pending data retained.");
1295
+ if (native.signature !== local.signature) {
1296
+ const body = native.trace ? await collectorBody(native.trace, device, scrubber ??= (await traceCollector()).collector.scrubberFor()) : uploadBody(parsed, sessionDigest(parsed), device);
1297
+ savePendingSource(item, { local: { harness: native.harness, sessionId: native.sessionId, signature: native.signature, files: native.files }, body });
1298
+ local = item.manifest.local;
1299
+ }
1300
+ source = await captureTraceSource(native, item.directory, { workspace, apiBase: item.manifest.apiBase });
1301
+ capturing = false;
1302
+ }
1303
+ if (item.manifest.stage !== "ready") completePendingCapture(item, source);
1304
+ const statuses = await libraryRequest("POST", "/trace-library/check", workspace, {
1305
+ sessions: [{ harness: local.harness, session_id: local.sessionId, sha256: source.sha256 }]
1306
+ });
1307
+ if (statuses.sessions[0]?.status === "owned") {
1308
+ report.owned++;
1309
+ throw new Error("Another member owns this source; pending archive retained.");
1310
+ }
1311
+ if (item.manifest.fileId) await verifyPendingFile(item, source);
1312
+ else {
1313
+ const file = await uploadLargeFile(source.path, "application/x-ndjson", void 0, () => {
1314
+ }, workspace);
1315
+ savePendingSource(item, { fileId: file.id });
1316
+ }
1317
+ const { work_objects: workObjects, outside_conversation: outside, ...previewBody } = item.manifest.body;
1318
+ if (config.sessions !== false && sessionHarness(local.harness)) {
1319
+ const body = previewBody;
1320
+ const left = new Set(outside ?? []);
1321
+ const saved2 = await saveTraceSession(libraryRequest, {
1322
+ harness: local.harness,
1323
+ sessionId: local.sessionId,
1324
+ workspace,
1325
+ body: { ...body, messages: body.messages.filter((_, index) => !left.has(index)) },
1326
+ skills: loadLocalSkillState()
1327
+ });
1328
+ if (saved2.status === "saved") report.sessions++;
1329
+ if (saved2.status === "saved" || saved2.status === "elsewhere") await saveResults(local, saved2.status === "elsewhere" ? saved2.workspace : workspace, saved2.sessionId, body.cwd);
1330
+ else if (saved2.status === "refused") options.onProgress?.(`${key(local)}: kept in the trace library only (${saved2.code})`);
1331
+ if (saved2.status !== "saved" && saved2.status !== "elsewhere" && !results.read.includes(key(local))) {
1332
+ results.read.push(key(local));
1333
+ writePrivateJson(resultsStatePath(), results);
1334
+ }
1335
+ }
1336
+ const saved = await libraryRequest("PUT", `/trace-library/${local.harness}/${encodeURIComponent(local.sessionId)}`, workspace, { ...previewBody, sha256: source.sha256 });
1337
+ savePendingSource(item, { previewSaved: true, link: saved.linked_task ?? null });
1338
+ const link = item.manifest.link;
1339
+ const linkKey = createHash2("sha256").update(JSON.stringify(link ?? null)).digest("hex").slice(0, 16);
1340
+ await libraryRequest("POST", "/events", workspace, { events: [{
1341
+ idempotency_key: `trace-source:${source.sha256}:${linkKey}`,
1342
+ ...link ? { session_id: link.session_id, task_id: link.task_id } : {},
1343
+ log: "workspace",
1344
+ kind: "trace.source",
1345
+ source: { system: "local-trace-collector", kind: local.harness, version: String(SOURCE_CAPTURE_VERSION) },
1346
+ surface: "cli",
1347
+ actor: { kind: "person" },
1348
+ objects: [{ type: "local_session", id: key(local), role: "source" }, ...workObjects ?? []],
1349
+ payload: {
1350
+ harness: local.harness,
1351
+ session_id: local.sessionId,
1352
+ sha256: source.sha256,
1353
+ redacted_before_upload: true,
1354
+ records: source.records,
1355
+ source_files: source.sourceFiles,
1356
+ source_file_id: item.manifest.fileId,
1357
+ gaps: source.gaps,
1358
+ library_is_preview: true
1359
+ },
1360
+ bodies: [{ role: "transcript", media_type: "application/x-ndjson", file_id: item.manifest.fileId, complete: source.complete }]
1361
+ }] });
1362
+ record(local, { workspace, sha256: source.sha256, status: source.complete ? "stored" : "stored_with_gaps" });
1363
+ writePrivateJson(statePath(), state);
1364
+ removePendingSource(item);
1365
+ restored.set(key(local), local.signature);
1366
+ report.uploaded++;
1367
+ report.byWorkspace[workspace] = (report.byWorkspace[workspace] ?? 0) + 1;
1368
+ } catch (error) {
1369
+ if (capturing) unreadable.add(key(local));
1370
+ else blocked = true;
1371
+ fail(`${key(local)} \u2192 ${workspace}`, error);
1372
+ }
1373
+ };
1374
+ if (!options.dryRun) {
1375
+ let existing;
1376
+ try {
1377
+ existing = listPendingSources(queueRoot);
1378
+ } catch (error) {
1379
+ fail("pending source queue", error);
1380
+ return report;
1381
+ }
1382
+ report.scanned = existing.length;
1383
+ report.changed = existing.length;
1384
+ for (let start = 0; start < existing.length; start += UPLOAD_CONCURRENCY) {
1385
+ await pool(existing.slice(start, start + UPLOAD_CONCURRENCY), UPLOAD_CONCURRENCY, send);
1386
+ if (blocked) return report;
1387
+ }
1388
+ }
1389
+ const direct = options.only?.length ? options.only.map(claudeSessionAt) : [];
1390
+ const sessions = (direct.length && direct.every(Boolean) ? direct : await discover()).filter(selected);
1391
+ report.scanned = Math.max(report.scanned, sessions.length);
1392
+ const lifted = (s) => state.sessions[key(s)]?.status === "excluded" && !stillExcluded(exclusions, state.sessions[key(s)]?.excludedBy ?? "");
1393
+ 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
+ try {
1395
+ return Date.now() - statSync2(file).mtimeMs < RESULTS_BACKFILL_MS;
1396
+ } catch {
1397
+ return false;
1398
+ }
1399
+ });
1400
+ 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)));
1401
+ if (options.limit) pending = pending.slice(0, options.limit);
1402
+ report.changed += pending.length;
1403
+ const prepare = async (local) => {
1404
+ if (local.trace) {
1405
+ if (leftOut(local, local.trace.cwd)) return null;
1406
+ const workspace2 = routeSession(local.trace.cwd, config);
1407
+ if (!workspace2) {
1408
+ report.local++;
1409
+ record(local, { workspace: null, status: "local" });
1410
+ return null;
1411
+ }
1412
+ scrubber ??= (await traceCollector()).collector.scrubberFor();
1413
+ return { workspace: workspace2, body: await collectorBody(local.trace, device, scrubber) };
1414
+ }
1415
+ const parsed = local.harness === "claude_code" ? await parseClaudeSession(local) : await parseCodexSession(local);
1416
+ if (leftOut(local, parsed.cwd)) return null;
1417
+ const workspace = routeSession(parsed.cwd, config);
1418
+ if (!workspace) {
1419
+ report.local++;
1420
+ record(local, { workspace: null, status: "local" });
1421
+ return null;
1422
+ }
1423
+ return { workspace, body: uploadBody(parsed, sessionDigest(parsed), device) };
1424
+ };
1425
+ for (let start = 0; start < pending.length; start += UPLOAD_CONCURRENCY) {
1426
+ const ready = [];
1427
+ await pool(pending.slice(start, start + UPLOAD_CONCURRENCY), UPLOAD_CONCURRENCY, async (local) => {
1428
+ try {
1429
+ const prepared = await prepare(local);
1430
+ if (!prepared) return;
1431
+ if (options.dryRun) {
1432
+ const directory = mkdtempSync(join2(skyDir(), "trace-dry-run-"));
1433
+ try {
1434
+ 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 }] });
1436
+ if (checked.sessions[0]?.status === "owned") {
1437
+ report.owned++;
1438
+ return;
1439
+ }
1440
+ report.uploaded++;
1441
+ report.byWorkspace[prepared.workspace] = (report.byWorkspace[prepared.workspace] ?? 0) + 1;
1442
+ } finally {
1443
+ rmSync(directory, { recursive: true, force: true });
1444
+ }
1445
+ return;
1446
+ }
1447
+ const item = beginPendingSource(queueRoot, {
1448
+ apiBase: endpoint,
1449
+ workspace: prepared.workspace,
1450
+ local: { harness: local.harness, sessionId: local.sessionId, signature: local.signature, files: local.files },
1451
+ body: prepared.body
1452
+ });
1453
+ const source = await captureTraceSource(local, item.directory, { workspace: prepared.workspace, apiBase: item.manifest.apiBase });
1454
+ completePendingCapture(item, source);
1455
+ ready.push(item);
1456
+ } catch (error) {
1457
+ fail(`${key(local)}: source capture failed`, error);
1458
+ }
1459
+ });
1460
+ await pool(ready, UPLOAD_CONCURRENCY, send);
1461
+ if (blocked) break;
1462
+ options.onProgress?.(`${Math.min(start + UPLOAD_CONCURRENCY, pending.length)}/${pending.length} checked, ${report.uploaded} uploaded so far`);
1463
+ }
1464
+ if (!options.dryRun) {
1465
+ if (full && !options.only?.length && !options.limit && report.failed === 0) state.lastFullAt = (/* @__PURE__ */ new Date()).toISOString();
1466
+ writePrivateJson(statePath(), state);
1467
+ }
1468
+ return report;
1469
+ }
1470
+ function hookSessionRef(payload) {
1471
+ try {
1472
+ const value = asRecord(JSON.parse(payload));
1473
+ return str2(value?.transcript_path) ?? str2(value?.session_id) ?? str2(value?.["thread-id"]) ?? str2(value?.thread_id);
1474
+ } catch {
1475
+ return void 0;
1476
+ }
1477
+ }
1478
+ var LAUNCHD_LABEL = "dev.agentsky.trace-sync";
1479
+ function launchdPlistPath(home = homedir3()) {
1480
+ return join2(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
1481
+ }
1482
+ function launchdPlist(command, logPath) {
1483
+ const escape = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1484
+ return `<?xml version="1.0" encoding="UTF-8"?>
1485
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1486
+ <plist version="1.0">
1487
+ <dict>
1488
+ <key>Label</key><string>${LAUNCHD_LABEL}</string>
1489
+ <key>ProgramArguments</key>
1490
+ <array>
1491
+ ${command.map((part) => ` <string>${escape(part)}</string>`).join("\n")}
1492
+ </array>
1493
+ <key>StartInterval</key><integer>900</integer>
1494
+ <key>RunAtLoad</key><true/>
1495
+ <key>ProcessType</key><string>Background</string>
1496
+ <key>StandardOutPath</key><string>${escape(logPath)}</string>
1497
+ <key>StandardErrorPath</key><string>${escape(logPath)}</string>
1498
+ </dict>
1499
+ </plist>
1500
+ `;
1501
+ }
1502
+ function installLaunchd(command, logPath) {
1503
+ if (process.platform !== "darwin") throw new Error("the schedule installer covers macOS; on Linux add `*/15 * * * * sky trace sync --quiet` to your crontab");
1504
+ const plist = launchdPlistPath();
1505
+ mkdirSync(dirname3(plist), { recursive: true });
1506
+ writeFileSync(plist, launchdPlist(command, logPath));
1507
+ return plist;
1508
+ }
1509
+ var SYNC_HOOK_COMMAND = "sky trace sync --hook";
1510
+ function installSyncHooks(home = homedir3(), codexHome = process.env.CODEX_HOME || join2(home, ".codex")) {
1511
+ const lines = [];
1512
+ const claudeSettings = join2(home, ".claude", "settings.json");
1513
+ installClaudeHooks(claudeSettings, SYNC_HOOK_COMMAND, { Stop: [{ hooks: [{ type: "command", command: SYNC_HOOK_COMMAND, timeout: 10 }] }] });
1514
+ 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") : "";
1517
+ const topLevel = text.split(/^\s*\[/m, 1)[0] ?? "";
1518
+ const notify = /^\s*notify\s*=.*$/m.exec(topLevel)?.[0];
1519
+ 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
+ else if (notify) lines.push(`Codex: already syncs at the end of every turn (${codexConfig}).`);
1521
+ else {
1522
+ mkdirSync(dirname3(codexConfig), { recursive: true });
1523
+ writeFileSync(codexConfig, `notify = ["sky", "trace", "sync", "--hook"]
1524
+ ${text}`);
1525
+ lines.push(`Codex: syncs at the end of every turn (${codexConfig}).`);
1526
+ }
1527
+ return lines;
1528
+ }
1529
+ function syncDir() {
1530
+ return skyDir();
1531
+ }
1532
+ export {
1533
+ LAUNCHD_LABEL,
1534
+ SYNC_HOOK_COMMAND,
1535
+ collectorBody,
1536
+ collectorHarness,
1537
+ discoverSessions,
1538
+ hookSessionRef,
1539
+ importExport,
1540
+ installLaunchd,
1541
+ installSyncHooks,
1542
+ isTrivial,
1543
+ launchdPlist,
1544
+ launchdPlistPath,
1545
+ libraryRequest,
1546
+ loadSyncConfig,
1547
+ parseClaudeSession,
1548
+ parseCodexSession,
1549
+ projectOf,
1550
+ repoRemote,
1551
+ routeSession,
1552
+ saveSyncConfig,
1553
+ sessionDigest,
1554
+ sourceFolders,
1555
+ supportedAgents,
1556
+ syncConfigPath,
1557
+ syncDir,
1558
+ syncTraces
1559
+ };