agent-neckbeard 1.1.29 → 1.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +25 -27
  3. package/dist/archil.d.ts +73 -0
  4. package/dist/archil.js +673 -0
  5. package/dist/build.cjs +129 -5315
  6. package/dist/build.d.cts +9 -5
  7. package/dist/build.d.ts +9 -5
  8. package/dist/build.js +4 -6
  9. package/dist/{chunk-BPXEIXPM.js → chunk-FHNQ5DNA.js} +3264 -564
  10. package/dist/{chunk-FSBTLBB5.js → chunk-I5GIWADK.js} +29 -7
  11. package/dist/chunk-I5NULOJP.js +129 -0
  12. package/dist/chunk-PKUGXECR.js +13 -0
  13. package/dist/chunk-QA4L7ZI2.js +72 -0
  14. package/dist/{chunk-KG6SJM74.js → chunk-VHBDBB3N.js} +8 -5
  15. package/dist/cli.cjs +124 -5309
  16. package/dist/cli.js +7 -8
  17. package/dist/define-gdmBe9RA.d.ts +227 -0
  18. package/dist/durable.d.ts +53 -0
  19. package/dist/durable.js +92 -0
  20. package/dist/index.cjs +720 -988
  21. package/dist/index.d.cts +139 -87
  22. package/dist/index.d.ts +139 -87
  23. package/dist/index.js +12 -11
  24. package/dist/inside.d.ts +15 -0
  25. package/dist/inside.js +530 -0
  26. package/dist/{invoke-client-P2CPBYTF.js → invoke-client-QB2NTZ3L.js} +1 -2
  27. package/dist/pi-watch-legacy.d.ts +4503 -0
  28. package/dist/serve.cjs +9 -439
  29. package/dist/serve.d.cts +14 -1
  30. package/dist/serve.d.ts +14 -1
  31. package/dist/serve.js +3 -5
  32. package/docs/AGENT.md +81 -77
  33. package/docs/DAYTONA.md +2 -0
  34. package/docs/DOCKER.md +0 -1
  35. package/docs/E2B.md +1 -1
  36. package/docs/LEGACY.md +1 -8
  37. package/docs/MODAL.md +1 -1
  38. package/package.json +57 -23
  39. package/types/pi-watch.d.cts +68 -0
  40. package/dist/chunk-33IXN6MM.js +0 -21
  41. package/dist/chunk-6P5I7ZCH.js +0 -2552
  42. package/dist/chunk-YFG4EKZM.js +0 -508
  43. package/dist/sandbox-capabilities-CFjnZ_kB.d.cts +0 -77
  44. package/dist/sandbox-capabilities-CFjnZ_kB.d.ts +0 -77
  45. package/dist/serve-Du2NCz9_.d.cts +0 -111
  46. package/dist/serve-Du2NCz9_.d.ts +0 -111
  47. package/dist/supervisor.cjs +0 -5731
  48. package/dist/supervisor.d.cts +0 -482
  49. package/dist/supervisor.d.ts +0 -482
  50. package/dist/supervisor.js +0 -3187
  51. package/docs/SUPERVISOR.md +0 -258
package/dist/archil.js ADDED
@@ -0,0 +1,673 @@
1
+ import {
2
+ settleOperation,
3
+ untilAborted
4
+ } from "./chunk-QA4L7ZI2.js";
5
+
6
+ // src/archil.ts
7
+ import { withoutAbortSignal as withoutAbortSignal2 } from "@earendil-works/chord/context";
8
+ import { LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
9
+
10
+ // src/archil-env.ts
11
+ import { AsyncLocalStorage } from "async_hooks";
12
+ import { randomUUID } from "crypto";
13
+ import { mkdtemp, rm, writeFile } from "fs/promises";
14
+ import { tmpdir } from "os";
15
+ import { join } from "path";
16
+ import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
17
+ import { posix as path } from "path";
18
+ import {
19
+ err,
20
+ ExecutionError,
21
+ FileError,
22
+ getOrThrow,
23
+ ok
24
+ } from "@earendil-works/pi-durable/env";
25
+ import { withoutAbortSignal } from "@earendil-works/chord/context";
26
+
27
+ // src/shell.ts
28
+ function shellQuote(value) {
29
+ return `'${value.replace(/'/g, `'\\''`)}'`;
30
+ }
31
+
32
+ // src/archil-env.ts
33
+ var workspace = "/mnt/archil/workspace";
34
+ var skills = "/app/.agents/skills";
35
+ function inside(base, file) {
36
+ return file === base || file.startsWith(base + "/");
37
+ }
38
+ var operationSignal = new AsyncLocalStorage();
39
+ var fileAborted = () => new FileError("aborted", "Aborted");
40
+ async function fileResult(ctx, operation) {
41
+ const signal = ctx.abortSignal;
42
+ try {
43
+ return ok(await settleOperation(() => operationSignal.run(signal, operation), {
44
+ abort: signal && { signal, createError: fileAborted }
45
+ }));
46
+ } catch (error) {
47
+ if (signal?.aborted) return err(fileAborted());
48
+ if (error instanceof FileError) return err(error);
49
+ const code = error instanceof Error && "status" in error && error.status === 404 ? "not_found" : "unknown";
50
+ return err(new FileError(code, error instanceof Error ? error.message : String(error)));
51
+ }
52
+ }
53
+ async function createArchilExecutionEnv(options, context) {
54
+ return (await openArchilEnv(options, context)).executionEnv;
55
+ }
56
+ async function openArchilEnv({ disk: volume, imageId, client, network, env }, context) {
57
+ const opening = (request) => untilAborted(request, context?.abortSignal);
58
+ const executor = client ?? await opening(() => import("disk"));
59
+ const proceed = () => {
60
+ if (operationSignal.getStore()?.aborted) throw fileAborted();
61
+ };
62
+ const disk = new Proxy(volume, {
63
+ get(target, name) {
64
+ const method = Reflect.get(target, name);
65
+ if (typeof method !== "function") return method;
66
+ return (...args) => {
67
+ proceed();
68
+ return method.apply(target, args);
69
+ };
70
+ }
71
+ });
72
+ if (!await opening(() => disk.objectExists("workspace/"))) await opening(() => disk.putObject("workspace/", ""));
73
+ const absolute = (file) => path.resolve(workspace, file);
74
+ const key = (file) => {
75
+ const full = absolute(file);
76
+ if (!inside(workspace, full)) throw new FileError("permission_denied", "Outside workspace", file);
77
+ return path.relative("/mnt/archil", full);
78
+ };
79
+ const run = async (command, policy = network) => {
80
+ proceed();
81
+ return executor.exec({
82
+ ...policy && { network: policy },
83
+ command,
84
+ imageId,
85
+ disks: { workspace: { disk: volume, subdirectory: "workspace", conditional: true } }
86
+ });
87
+ };
88
+ const checked = async (command) => {
89
+ const result = await run(command);
90
+ if (result.exitCode !== 0) throw new FileError("unknown", result.stderr || "Archil command failed");
91
+ return result.stdout;
92
+ };
93
+ const canonical = async (file) => {
94
+ const full = absolute(file);
95
+ if (!inside(skills, full)) {
96
+ key(full);
97
+ for (let parent = full; parent !== workspace; parent = path.dirname(parent)) {
98
+ try {
99
+ if (await disk.headObject(key(parent))) return full;
100
+ } catch (error) {
101
+ if (!(error instanceof Error && "status" in error && error.status === 501)) throw error;
102
+ const resolved2 = (await checked(`realpath -zm -- ${shellQuote(full)}`)).slice(0, -1);
103
+ key(resolved2);
104
+ return resolved2;
105
+ }
106
+ }
107
+ return full;
108
+ }
109
+ const resolved = (await checked(`realpath -zm -- ${shellQuote(full)}`)).slice(0, -1);
110
+ if (!inside(skills, resolved)) throw new FileError("permission_denied", "Outside image skills", file);
111
+ return resolved;
112
+ };
113
+ const read = async (file) => {
114
+ const full = absolute(file);
115
+ if (inside(skills, full)) {
116
+ const result = await run(`size=$(LC_ALL=C stat -Lc %s -- ${shellQuote(full)}) || exit 1
117
+ test "$size" -le 3145728 && base64 -w0 -- ${shellQuote(full)}`);
118
+ if (result.exitCode !== 0) {
119
+ const code = result.stderr.trimEnd().endsWith(": No such file or directory") ? "not_found" : "unknown";
120
+ throw new FileError(code, result.stderr || "Cannot read image skill file", full);
121
+ }
122
+ return Buffer.from(result.stdout, "base64");
123
+ }
124
+ try {
125
+ return await disk.getObject(key(file));
126
+ } catch (error) {
127
+ if (!(error instanceof Error && "status" in error && (error.status === 404 || error.status === 501))) throw error;
128
+ const resolved = await canonical(full);
129
+ if (resolved === full) throw error;
130
+ return disk.getObject(key(resolved));
131
+ }
132
+ };
133
+ const objectInfo = async (file) => {
134
+ const full = absolute(file);
135
+ if (!inside(skills, full)) key(file);
136
+ if (inside(workspace, full) && full !== workspace) {
137
+ try {
138
+ const object = await disk.headObject(key(file));
139
+ if (object) return { name: path.basename(full), path: full, kind: "file", size: object.size, mtimeMs: object.lastModified?.getTime() ?? 0 };
140
+ } catch (error) {
141
+ if (!(error instanceof Error && "status" in error && error.status === 501)) throw error;
142
+ }
143
+ }
144
+ };
145
+ const mountedInfo = async (file) => {
146
+ const full = absolute(file);
147
+ const { stdout, exitCode } = await run(`LC_ALL=C stat --printf='%F\\n%s\\n%Y' -- ${shellQuote(full)}`);
148
+ if (exitCode !== 0) throw new FileError("not_found", "Path not found", full);
149
+ const [kind, size, time] = stdout.split("\n");
150
+ return {
151
+ name: path.basename(full),
152
+ path: full,
153
+ kind: kind === "directory" ? "directory" : kind === "symbolic link" ? "symlink" : "file",
154
+ size: Number(size),
155
+ mtimeMs: Number(time) * 1e3
156
+ };
157
+ };
158
+ const info = async (file) => await objectInfo(file) ?? mountedInfo(file);
159
+ const tempPaths = /* @__PURE__ */ new Set();
160
+ const watchers = /* @__PURE__ */ new Set();
161
+ const executionEnv = {
162
+ id: "archil:" + disk.id,
163
+ cwd: workspace,
164
+ absolutePath: async (file) => ok(absolute(file)),
165
+ joinPath: async (parts) => ok(path.join(...parts)),
166
+ canonicalPath: (file, ctx) => fileResult(ctx, () => canonical(file)),
167
+ fileInfo: (file, ctx) => fileResult(ctx, () => info(file)),
168
+ exists: (file, ctx) => fileResult(ctx, async () => {
169
+ const found = await executionEnv.fileInfo(file, ctx);
170
+ if (!found.ok && found.error.code === "not_found") return false;
171
+ getOrThrow(found);
172
+ return true;
173
+ }),
174
+ readBinaryFile: (file, ctx) => fileResult(ctx, () => read(file)),
175
+ readTextFile: (file, ctx) => fileResult(ctx, async () => new TextDecoder().decode(await read(file))),
176
+ readTextLines: (file, options, ctx) => fileResult(ctx, async () => getOrThrow(await executionEnv.readTextFile(file, ctx)).split("\n").slice(0, options?.maxLines)),
177
+ openTextLineReader: (file, ctx) => fileResult(ctx, async () => {
178
+ const text = getOrThrow(await executionEnv.readTextFile(file, ctx));
179
+ let offset = 0;
180
+ return {
181
+ readLine: (context2) => fileResult(context2, () => {
182
+ if (offset >= text.length) return void 0;
183
+ const end = text.indexOf("\n", offset);
184
+ const line = text.slice(offset, end < 0 ? void 0 : end);
185
+ offset = end < 0 ? text.length : end + 1;
186
+ return { text: line, terminated: end >= 0 };
187
+ }),
188
+ close: async () => {
189
+ offset = text.length;
190
+ }
191
+ };
192
+ }),
193
+ openBinaryReader: (file, options, ctx) => fileResult(ctx, async () => {
194
+ const direct = await objectInfo(file);
195
+ const metadata = direct ?? await mountedInfo(file);
196
+ if (metadata.kind === "directory") throw new FileError("is_directory", "Expected a file", file);
197
+ if (metadata.kind === "symlink" && options?.noFollow) throw new FileError("invalid", "Symbolic link", file);
198
+ const target = direct ? file : (await checked(`realpath -zm -- ${shellQuote(absolute(file))}`)).slice(0, -1);
199
+ if (inside(skills, absolute(file)) && !inside(skills, target)) throw new FileError("permission_denied", "Outside image skills", file);
200
+ if (inside(workspace, absolute(file))) key(target);
201
+ const dir = await mkdtemp(join(tmpdir(), "neckbeard-read-"));
202
+ const snapshot = join(dir, "file");
203
+ let reader;
204
+ try {
205
+ try {
206
+ if (inside(skills, absolute(target))) {
207
+ await writeFile(snapshot, await read(target), { mode: 384 });
208
+ } else {
209
+ const { url } = await disk.share(key(target), { expiresIn: 60 });
210
+ const response = await fetch(url, { signal: ctx.abortSignal });
211
+ if (!response.ok || !response.body) throw new FileError("unknown", `Archil download failed (${response.status})`, file);
212
+ await writeFile(snapshot, response.body, { mode: 384, signal: ctx.abortSignal });
213
+ }
214
+ proceed();
215
+ reader = getOrThrow(await new NodeExecutionEnv({ cwd: dir }).openBinaryReader(snapshot, void 0, ctx));
216
+ } finally {
217
+ await rm(dir, { recursive: true, force: true });
218
+ }
219
+ proceed();
220
+ } catch (error) {
221
+ await reader?.close(withoutAbortSignal(ctx));
222
+ throw error;
223
+ }
224
+ const opened = reader;
225
+ return {
226
+ read: opened.read.bind(opened),
227
+ scanLines: opened.scanLines.bind(opened),
228
+ close: opened.close.bind(opened),
229
+ info: (context2) => fileResult(context2, async () => ({
230
+ ...getOrThrow(await opened.info(context2)),
231
+ path: absolute(file),
232
+ name: path.basename(file),
233
+ mtimeMs: metadata.mtimeMs
234
+ }))
235
+ };
236
+ }),
237
+ writeFile: (file, content, ctx) => fileResult(ctx, async () => {
238
+ key(file);
239
+ const target = await canonical(file);
240
+ const object = key(target);
241
+ if (!await disk.objectExists(object)) {
242
+ await disk.putObject(object, content);
243
+ return;
244
+ }
245
+ const attrs = await checked(`stat -c '%a %u %g' -- ${shellQuote(target)}`);
246
+ const [mode, uid, gid] = attrs.trim().split(" ");
247
+ await disk.putObject(object, content, { mode: parseInt(mode, 8), uid: Number(uid), gid: Number(gid) });
248
+ }),
249
+ appendFile: (file, content, ctx) => fileResult(ctx, async () => {
250
+ await disk.appendObject(key(file), content);
251
+ }),
252
+ flushFile: (file, ctx) => fileResult(ctx, async () => {
253
+ await info(file);
254
+ }),
255
+ truncateFile: (file, size, ctx) => mutate(["truncate", "-s", String(size), "--"], [file], ctx),
256
+ renameFile: (from, to, ctx) => mutate(["mv", "-T", "--"], [from, to], ctx),
257
+ createDir: (file, options, ctx) => mutate(options?.recursive ? ["mkdir", "-p", "--"] : ["mkdir", "--"], [file], ctx),
258
+ remove: (file, options, ctx) => mutate(["rm", ...options?.recursive ? ["-r"] : [], ...options?.force ? ["-f"] : [], "--"], [file], ctx),
259
+ createTempDir: (prefix, ctx) => temp(prefix, "", true, ctx),
260
+ createTempFile: (options, ctx) => temp(options?.prefix, options?.suffix ?? "", false, ctx),
261
+ cleanup: async (ctx) => {
262
+ for (const stop of watchers) stop();
263
+ for (const file of tempPaths) {
264
+ getOrThrow(await executionEnv.remove(file, { recursive: true, force: true }, ctx));
265
+ tempPaths.delete(file);
266
+ }
267
+ },
268
+ listDir: (file, ctx) => fileResult(ctx, async () => {
269
+ const directory = await info(file);
270
+ if (directory.kind !== "directory") throw new FileError("not_directory", "Expected directory", file);
271
+ const raw = await checked(`find ${shellQuote(directory.path)} -mindepth 1 -maxdepth 1 -printf '%f\\0%y\\0%s\\0%T@\\0'`);
272
+ const values = raw.split("\0");
273
+ const entries = [];
274
+ for (let i = 0; i + 3 < values.length; i += 4) {
275
+ const [name, kind, size, time] = values.slice(i, i + 4);
276
+ entries.push({
277
+ name,
278
+ path: path.join(directory.path, name),
279
+ kind: kind === "d" ? "directory" : kind === "l" ? "symlink" : "file",
280
+ size: Number(size),
281
+ mtimeMs: Number(time) * 1e3
282
+ });
283
+ }
284
+ return entries;
285
+ }),
286
+ openDirReader: (file, ctx) => fileResult(ctx, async () => {
287
+ const directory = await info(file);
288
+ if (directory.kind !== "directory") throw new FileError("not_directory", "Expected directory", file);
289
+ let closed = false;
290
+ let entries;
291
+ return {
292
+ next: (limit, context2) => fileResult(context2, async () => {
293
+ if (closed || !Number.isSafeInteger(limit) || limit < 1) throw new FileError("invalid", "Invalid directory read");
294
+ entries ??= getOrThrow(await executionEnv.listDir(file, context2));
295
+ return { entries: entries.splice(0, limit), done: entries.length === 0 };
296
+ }),
297
+ close: async () => {
298
+ closed = true;
299
+ }
300
+ };
301
+ }),
302
+ watch: (targets, onChange, ctx) => fileResult(ctx, () => watch(targets, onChange)),
303
+ exec: (command, options, ctx) => execute(command, options, ctx)
304
+ };
305
+ function mutate(args, files, ctx) {
306
+ return fileResult(ctx, async () => {
307
+ for (const file of files) key(file);
308
+ await checked([...args, ...files.map(absolute)].map(shellQuote).join(" "));
309
+ });
310
+ }
311
+ function temp(prefix = "tmp-", suffix, directory, ctx) {
312
+ return fileResult(ctx, async () => {
313
+ if ([prefix, suffix].some((part) => part.includes("/"))) throw new FileError("invalid", "Invalid temporary name");
314
+ const file = path.join(workspace, prefix + randomUUID() + suffix);
315
+ tempPaths.add(file);
316
+ if (directory) getOrThrow(await executionEnv.createDir(file, void 0, ctx));
317
+ else getOrThrow(await executionEnv.writeFile(file, "", ctx));
318
+ return file;
319
+ });
320
+ }
321
+ async function watch(targets, onChange) {
322
+ const snapshots = async () => Promise.all(targets.map(async (target) => {
323
+ key(target.path);
324
+ const exclude = [...target.exclude?.names ?? [], ...target.exclude?.hidden ? [".*"] : []];
325
+ const prune = exclude.length ? "\\( " + exclude.map((name) => "-name " + shellQuote(name)).join(" -o ") + " \\) -prune -o " : "";
326
+ const { stdout, exitCode } = await run(`find -H ${shellQuote(absolute(target.path))} ${target.recursive ? "" : "-maxdepth 1"} ${prune} -printf '%p\\0%T@\\0%s\\0'`);
327
+ return String(exitCode) + stdout;
328
+ }));
329
+ let previous = await snapshots();
330
+ proceed();
331
+ let stopped = false;
332
+ let timer;
333
+ const poll = async () => {
334
+ try {
335
+ const next = await snapshots();
336
+ if (stopped) return;
337
+ const paths = targets.filter((_, i) => previous[i] !== next[i]).map((target) => absolute(target.path));
338
+ if (paths.length) onChange({ kind: "paths", paths });
339
+ previous = next;
340
+ timer = setTimeout(poll, 200);
341
+ } catch (error) {
342
+ if (!stopped) onChange({ kind: "failed", error: new FileError("unknown", String(error)) });
343
+ }
344
+ };
345
+ timer = operationSignal.exit(() => setTimeout(poll, 200));
346
+ const stop = () => {
347
+ stopped = true;
348
+ clearTimeout(timer);
349
+ watchers.delete(stop);
350
+ };
351
+ watchers.add(stop);
352
+ return { mode: "polling", stop: async () => stop() };
353
+ }
354
+ async function execute(command, options, ctx, policy) {
355
+ const aborted = () => new ExecutionError("aborted", "Command wait aborted");
356
+ if (ctx.abortSignal?.aborted) return err(aborted());
357
+ if (typeof command !== "string" && !command.length) return err(new ExecutionError("spawn_error", "Empty argv"));
358
+ try {
359
+ const cwd = absolute(options?.cwd ?? workspace);
360
+ key(cwd);
361
+ const args = typeof command === "string" ? ["bash", "-c", command] : command;
362
+ const deadline = options?.timeout === void 0 ? void 0 : Date.now() + options.timeout * 1e3;
363
+ const bounded = (operation) => settleOperation(operation, {
364
+ abort: ctx.abortSignal && { signal: ctx.abortSignal, createError: aborted },
365
+ timeout: deadline === void 0 ? void 0 : {
366
+ timeoutMs: Math.max(0, deadline - Date.now()),
367
+ createError: () => new ExecutionError("timeout", "Command wait timed out")
368
+ }
369
+ });
370
+ const launch = policy && await bounded(() => policy(ctx));
371
+ if (ctx.abortSignal?.aborted) return err(aborted());
372
+ const vars = Object.entries({ ...options?.env, ...env, ...launch?.env, NECKBEARD_CWD: workspace }).map(([k, v]) => k + "=" + v);
373
+ let script = `cd ${shellQuote(cwd)} && env ${options?.inheritEnv === false ? "-i " : ""}-- ${[...vars, ...args].map(shellQuote).join(" ")}`;
374
+ const spill = options?.spill;
375
+ const spillPath = path.join(workspace, ".pi-output-" + randomUUID() + ".log");
376
+ const window = options?.window;
377
+ if (window && ![window.maxBytes, window.maxLines].every((n) => Number.isSafeInteger(n) && n > 0)) {
378
+ throw new ExecutionError("unknown", "Invalid output window");
379
+ }
380
+ if (spill || window) {
381
+ if (spill && ![spill.afterBytes, spill.afterLines].every((n) => Number.isSafeInteger(n) && n >= 0)) {
382
+ throw new ExecutionError("unknown", "Invalid spill thresholds");
383
+ }
384
+ script = [
385
+ "out=$(mktemp) || exit 1",
386
+ `( ${script} ) >"$out" 2>&1; status=$?`,
387
+ 'bytes=$(wc -c < "$out")',
388
+ `lines=$(awk 'END { print NR + 0 }' "$out")`,
389
+ spill && `if [ "$bytes" -gt ${spill.afterBytes} ] || [ "$lines" -gt ${spill.afterLines} ]; then cat "$out" > ${shellQuote(spillPath)} || exit 1; fi`,
390
+ window && `emit() {
391
+ tail -c ${Math.min(window.maxBytes + 4, 4 * 1024 * 1024 - 128)} "$1" | tail -n ${window.maxLines + 2} > "$out.tail"
392
+ skip=$(( $(wc -c < "$1") - $(wc -c < "$out.tail") ))
393
+ extra=0
394
+ if [ "$skip" -gt 0 ]; then
395
+ for byte in $(od -An -N3 -tu1 "$out.tail"); do
396
+ [ "$byte" -ge 128 ] && [ "$byte" -lt 192 ] || break
397
+ extra=$((extra + 1))
398
+ done
399
+ skip=$((skip + extra))
400
+ fi
401
+ lines=$(head -c "$skip" "$1" | wc -l)
402
+ last=$(head -c "$skip" "$1" | tail -c 1 | od -An -tu1)
403
+ printf '%s %s %s\\n' "$skip" "$lines" "$(( \${last:-0} == 10 ))"
404
+ tail -c "+$((extra + 1))" "$out.tail"
405
+ }`,
406
+ window ? 'emit "$out"' : 'cat "$out"',
407
+ 'exit "$status"'
408
+ ].filter(Boolean).join("\n");
409
+ }
410
+ const result = await bounded(() => run(script, launch?.network));
411
+ if (ctx.abortSignal?.aborted) return err(aborted());
412
+ for (const stream of ["stdout", "stderr"]) {
413
+ let text = result[stream];
414
+ let skipped;
415
+ if (!text) continue;
416
+ if (window && stream === "stdout") {
417
+ const header = /^(\d+) (\d+) ([01])\n/.exec(text);
418
+ if (!header) throw new ExecutionError("unknown", "Missing Archil output window");
419
+ if (Number(header[1])) skipped = { bytes: Number(header[1]), newlines: Number(header[2]), endsWithNewline: header[3] === "1" };
420
+ text = text.slice(header[0].length);
421
+ }
422
+ if ((stream === "stderr" || spill || window) && typeof command !== "string" && result.exitCode === 127 && text.startsWith("env:")) {
423
+ throw new ExecutionError("spawn_error", text);
424
+ }
425
+ if (text || skipped) options?.onOutput?.(text, ctx, { stream, skipped });
426
+ }
427
+ if (spill && await bounded(() => disk.objectExists(key(spillPath)))) {
428
+ tempPaths.add(spillPath);
429
+ return ok({ exitCode: result.exitCode, spillPath });
430
+ }
431
+ return ok({ exitCode: result.exitCode });
432
+ } catch (error) {
433
+ return err(error instanceof ExecutionError ? error : new ExecutionError("unknown", String(error)));
434
+ }
435
+ }
436
+ return {
437
+ executionEnv,
438
+ withBash(policy) {
439
+ return { ...executionEnv, exec: (command, options, ctx) => execute(command, options, ctx, policy) };
440
+ }
441
+ };
442
+ }
443
+
444
+ // src/archil-storage.ts
445
+ import { createHash } from "crypto";
446
+ import { MemoryStorage } from "@earendil-works/pi-durable/storage/memory";
447
+ var tape = "session-storage/commits.jsonl";
448
+ var ArchilSessionNotFound = class extends Error {
449
+ };
450
+ var ArchilSessionAlreadyExists = class extends Error {
451
+ };
452
+ var ArchilStorage = class _ArchilStorage extends MemoryStorage {
453
+ constructor(disk) {
454
+ super();
455
+ this.disk = disk;
456
+ }
457
+ pending = Promise.resolve();
458
+ static async open(disk, operation, context) {
459
+ const storage = new _ArchilStorage(disk);
460
+ const read = (request) => untilAborted(request, context?.abortSignal);
461
+ const exists = await read(() => disk.objectExists(tape));
462
+ if (operation === "open" && !exists) throw new ArchilSessionNotFound("No session commit log on this disk.");
463
+ if (operation === "start" && exists) throw new ArchilSessionAlreadyExists("This disk already contains a session commit log.");
464
+ if (exists) {
465
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(await read(() => disk.getObject(tape)));
466
+ if (text && !text.endsWith("\n")) throw new Error("Incomplete Archil commit log");
467
+ for (const line of text.split("\n").slice(0, -1)) {
468
+ let record = JSON.parse(line);
469
+ if (record.blob !== void 0) {
470
+ if (typeof record.blob !== "string" || !/^[a-f0-9]{64}$/.test(record.blob)) throw new Error("Invalid Archil commit reference");
471
+ const body = await read(() => disk.getObject("session-storage/" + record.blob));
472
+ if (createHash("sha256").update(body).digest("hex") !== record.blob) throw new Error("Corrupt Archil commit");
473
+ record = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
474
+ }
475
+ const { seq, writes } = record;
476
+ if (!Number.isSafeInteger(seq) || !Array.isArray(writes)) throw new Error("Invalid Archil commit");
477
+ storage.prepareCommit(writes, seq).apply();
478
+ }
479
+ }
480
+ return new Proxy(storage, {
481
+ get(target, name) {
482
+ const method = Reflect.get(target, name);
483
+ if (typeof method !== "function") return method;
484
+ if (name === "commit" || name === "close") return method.bind(target);
485
+ return (...args) => {
486
+ const context2 = args.at(-1);
487
+ const signal = typeof context2 === "object" && context2 !== null ? Reflect.get(context2, "abortSignal") : void 0;
488
+ return untilAborted(() => target.pending.then(() => method.apply(target, args)), signal instanceof AbortSignal ? signal : void 0);
489
+ };
490
+ }
491
+ });
492
+ }
493
+ commit(...[batches, receive, context]) {
494
+ const operation = this.pending.then(async () => {
495
+ await super.commit([], receive, context);
496
+ const seqs = [];
497
+ let chunk = "";
498
+ let size = 0;
499
+ let refused;
500
+ try {
501
+ for (const writes of batches) {
502
+ let prepared;
503
+ try {
504
+ prepared = this.prepareCommit(writes);
505
+ } catch (error) {
506
+ refused = error;
507
+ break;
508
+ }
509
+ let line = JSON.stringify({ seq: prepared.seq, writes: prepared.writes }) + "\n";
510
+ let bytes = Buffer.byteLength(line);
511
+ if (bytes > 1024 * 1024) {
512
+ const blob = createHash("sha256").update(line).digest("hex");
513
+ await this.disk.putObject("session-storage/" + blob, line);
514
+ line = JSON.stringify({ blob }) + "\n";
515
+ bytes = Buffer.byteLength(line);
516
+ }
517
+ if (size + bytes > 1024 * 1024) {
518
+ await this.disk.appendObject(tape, chunk);
519
+ chunk = "";
520
+ size = 0;
521
+ }
522
+ chunk += line;
523
+ size += bytes;
524
+ seqs.push(prepared.apply());
525
+ }
526
+ if (chunk) await this.disk.appendObject(tape, chunk);
527
+ } catch (error) {
528
+ await super.close(context);
529
+ throw error;
530
+ }
531
+ seqs.forEach((seq, index) => receive(index, seq));
532
+ return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused };
533
+ });
534
+ this.pending = operation.then(() => {
535
+ }, () => {
536
+ });
537
+ return operation;
538
+ }
539
+ async close(...args) {
540
+ await this.pending;
541
+ await super.close(...args);
542
+ }
543
+ };
544
+
545
+ // src/archil-image.ts
546
+ import { execFileSync } from "child_process";
547
+
548
+ // src/image-tag.ts
549
+ var IMAGE_TAG_ENV_VARS = [
550
+ "NECKBEARD_IMAGE_TAG",
551
+ "GITHUB_SHA",
552
+ "CI_COMMIT_SHA",
553
+ "BITBUCKET_COMMIT",
554
+ "CODEBUILD_RESOLVED_SOURCE_VERSION",
555
+ "BUILDKITE_COMMIT",
556
+ "CIRCLE_SHA1",
557
+ "CF_PAGES_COMMIT_SHA",
558
+ "HEROKU_BUILD_COMMIT",
559
+ "HEROKU_SLUG_COMMIT",
560
+ "RAILWAY_GIT_COMMIT_SHA",
561
+ "RENDER_GIT_COMMIT",
562
+ "VERCEL_GIT_COMMIT_SHA",
563
+ "SOURCE_VERSION",
564
+ "GIT_COMMIT"
565
+ ];
566
+ function resolveImageTag(env = process.env) {
567
+ for (const name of IMAGE_TAG_ENV_VARS) {
568
+ const value = env[name]?.trim();
569
+ if (value && value !== name) return value;
570
+ }
571
+ return void 0;
572
+ }
573
+
574
+ // src/archil-image.ts
575
+ function archilToolsImage(definition, tag) {
576
+ if (!tag || !/^[0-9a-f]{40}$/.test(tag) || !definition.registry) {
577
+ throw new Error("Archil tools images require a registry and one full commit SHA tag.");
578
+ }
579
+ return definition.registry.replace(/\/+$/, "") + "/" + definition.name + "-tools:" + tag;
580
+ }
581
+ async function getArchilToolsImageId(definition, options = {}) {
582
+ const tag = options.tag ?? resolveImageTag() ?? execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
583
+ const ref = archilToolsImage(definition, tag);
584
+ const slash = ref.indexOf("/");
585
+ const host = ref.slice(0, slash);
586
+ const repo = ref.slice(slash + 1, ref.lastIndexOf(":"));
587
+ const origin = new URL("https://" + host);
588
+ if (origin.host !== host || !repo || !/^[a-z0-9._/-]+$/.test(repo)) throw new Error("Invalid tools image registry or repository");
589
+ const username = process.env.REGISTRY_USERNAME;
590
+ const password = process.env.REGISTRY_TOKEN;
591
+ if (Boolean(username) !== Boolean(password)) throw new Error("Supply both REGISTRY_USERNAME and REGISTRY_TOKEN.");
592
+ const registryAuth = username && password ? { username, password } : void 0;
593
+ const basic = registryAuth && "Basic " + Buffer.from(username + ":" + password).toString("base64");
594
+ const manifest = new URL("/v2/" + repo + "/manifests/" + tag, origin);
595
+ const accept = [
596
+ "application/vnd.oci.image.index.v1+json",
597
+ "application/vnd.oci.image.manifest.v1+json",
598
+ "application/vnd.docker.distribution.manifest.list.v2+json",
599
+ "application/vnd.docker.distribution.manifest.v2+json"
600
+ ].join(", ");
601
+ const head = (auth) => fetch(manifest, {
602
+ method: "HEAD",
603
+ redirect: "error",
604
+ headers: { Accept: accept, ...auth && { Authorization: auth } }
605
+ });
606
+ let response = await head();
607
+ if (response.status === 401) {
608
+ const challenge = response.headers.get("www-authenticate") ?? "";
609
+ const realm = /^Bearer\s+realm="([^"]+)"/i.exec(challenge)?.[1];
610
+ if (realm) {
611
+ const tokenUrl = new URL(realm);
612
+ if (tokenUrl.origin !== origin.origin) throw new Error("Registry token realm must share the registry origin");
613
+ const service = /service="([^"]+)"/i.exec(challenge)?.[1];
614
+ if (service) tokenUrl.searchParams.set("service", service);
615
+ tokenUrl.searchParams.set("scope", "repository:" + repo + ":pull");
616
+ const auth = await fetch(tokenUrl, { redirect: "error", headers: basic ? { Authorization: basic } : {} });
617
+ if (!auth.ok) throw new Error("Registry pull token request failed (HTTP " + auth.status + ")");
618
+ const data = await auth.json();
619
+ const token = data.token ?? data.access_token;
620
+ if (typeof token !== "string" || !token) throw new Error("Registry returned no pull token");
621
+ response = await head("Bearer " + token);
622
+ } else if (basic && /^Basic\s/i.test(challenge)) response = await head(basic);
623
+ }
624
+ if (!response.ok) {
625
+ const credentials = registryAuth ? "" : " Private images require REGISTRY_USERNAME and REGISTRY_TOKEN.";
626
+ throw new Error("Registry manifest lookup failed (HTTP " + response.status + ")." + credentials);
627
+ }
628
+ const digest = response.headers.get("docker-content-digest");
629
+ if (!digest || !/^sha256:[0-9a-f]{64}$/.test(digest)) throw new Error("Registry returned no valid manifest digest");
630
+ const images = options.images ?? new (await import("disk")).Archil().images;
631
+ const image = await images.build({ source: host + "/" + repo + "@" + digest, ...registryAuth && { registryAuth } });
632
+ return image.imageId;
633
+ }
634
+
635
+ // src/archil.ts
636
+ async function archilStorage(disk, context, options = {}) {
637
+ const { create } = options;
638
+ if (create !== void 0 && typeof create !== "boolean") throw new Error("create must be true, false or omitted.");
639
+ const storage = await ArchilStorage.open(disk, create === void 0 ? void 0 : create ? "start" : "open", context);
640
+ if (create === false && !await storage.conversation(ROOT_CONVERSATION_ID, context)) {
641
+ await storage.close(withoutAbortSignal2(context));
642
+ throw new ArchilSessionNotFound("The session log on this disk has no root conversation.");
643
+ }
644
+ return storage;
645
+ }
646
+ function archilExecution(options) {
647
+ return async ({ sessionId, storage }, context) => {
648
+ if (!options.imageId?.trim()) throw new Error("Archil execution requires a tools image ID.");
649
+ const adapter = await openArchilEnv(options, context);
650
+ const { dispatch } = options;
651
+ return {
652
+ executionEnv: adapter.executionEnv,
653
+ resolve: dispatch && (async (target, ctx) => {
654
+ const live = await target.read.snapshot(LiveDoc, target.conversationId, ctx);
655
+ const submissionId = live?.run?.inputs[0];
656
+ if (submissionId === void 0) return adapter.executionEnv;
657
+ const submission = await storage.submission(submissionId, ctx);
658
+ if (!submission) throw new Error("Missing submission for the active Pi run.");
659
+ const identity = Object.freeze({ sessionId, submissionId, requestId: submission.requestId, cwd: adapter.executionEnv.cwd });
660
+ return adapter.withBash((commandContext) => dispatch(identity, commandContext));
661
+ })
662
+ };
663
+ };
664
+ }
665
+ export {
666
+ ArchilSessionAlreadyExists,
667
+ ArchilSessionNotFound,
668
+ ArchilStorage,
669
+ archilExecution,
670
+ archilStorage,
671
+ createArchilExecutionEnv,
672
+ getArchilToolsImageId
673
+ };