local-commander-agent-linux-arm64 0.3.46 → 0.3.47

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.
package/runtime/agent.mjs CHANGED
@@ -2138,7 +2138,7 @@ var require_extension = __commonJS({
2138
2138
  if (dest[name2] === void 0) dest[name2] = [elem];
2139
2139
  else dest[name2].push(elem);
2140
2140
  }
2141
- function parse3(header) {
2141
+ function parse4(header) {
2142
2142
  const offers = /* @__PURE__ */ Object.create(null);
2143
2143
  let params = /* @__PURE__ */ Object.create(null);
2144
2144
  let mustUnescape = false;
@@ -2278,7 +2278,7 @@ var require_extension = __commonJS({
2278
2278
  }).join(", ");
2279
2279
  }).join(", ");
2280
2280
  }
2281
- module.exports = { format, parse: parse3 };
2281
+ module.exports = { format, parse: parse4 };
2282
2282
  }
2283
2283
  });
2284
2284
 
@@ -2289,9 +2289,9 @@ var require_websocket = __commonJS({
2289
2289
  var EventEmitter = __require("events");
2290
2290
  var https2 = __require("https");
2291
2291
  var http2 = __require("http");
2292
- var net2 = __require("net");
2292
+ var net3 = __require("net");
2293
2293
  var tls2 = __require("tls");
2294
- var { randomBytes: randomBytes10, createHash: createHash21 } = __require("crypto");
2294
+ var { randomBytes: randomBytes11, createHash: createHash21 } = __require("crypto");
2295
2295
  var { Duplex, Readable } = __require("stream");
2296
2296
  var { URL: URL2 } = __require("url");
2297
2297
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -2312,7 +2312,7 @@ var require_websocket = __commonJS({
2312
2312
  var {
2313
2313
  EventTarget: { addEventListener, removeEventListener }
2314
2314
  } = require_event_target();
2315
- var { format, parse: parse3 } = require_extension();
2315
+ var { format, parse: parse4 } = require_extension();
2316
2316
  var { toBuffer } = require_buffer_util();
2317
2317
  var kAborted = /* @__PURE__ */ Symbol("kAborted");
2318
2318
  var protocolVersions = [8, 13];
@@ -2842,7 +2842,7 @@ var require_websocket = __commonJS({
2842
2842
  }
2843
2843
  }
2844
2844
  const defaultPort = isSecure ? 443 : 80;
2845
- const key = randomBytes10(16).toString("base64");
2845
+ const key = randomBytes11(16).toString("base64");
2846
2846
  const request = isSecure ? https2.request : http2.request;
2847
2847
  const protocolSet = /* @__PURE__ */ new Set();
2848
2848
  let perMessageDeflate;
@@ -3002,7 +3002,7 @@ var require_websocket = __commonJS({
3002
3002
  }
3003
3003
  let extensions;
3004
3004
  try {
3005
- extensions = parse3(secWebSocketExtensions);
3005
+ extensions = parse4(secWebSocketExtensions);
3006
3006
  } catch (err) {
3007
3007
  const message2 = "Invalid Sec-WebSocket-Extensions header";
3008
3008
  abortHandshake(websocket, socket, message2);
@@ -3046,12 +3046,12 @@ var require_websocket = __commonJS({
3046
3046
  }
3047
3047
  function netConnect2(options) {
3048
3048
  options.path = options.socketPath;
3049
- return net2.connect(options);
3049
+ return net3.connect(options);
3050
3050
  }
3051
3051
  function tlsConnect(options) {
3052
3052
  options.path = void 0;
3053
3053
  if (!options.servername && options.servername !== "") {
3054
- options.servername = net2.isIP(options.host) ? "" : options.host;
3054
+ options.servername = net3.isIP(options.host) ? "" : options.host;
3055
3055
  }
3056
3056
  return tls2.connect(options);
3057
3057
  }
@@ -3294,7 +3294,7 @@ var require_subprotocol = __commonJS({
3294
3294
  "node_modules/ws/lib/subprotocol.js"(exports, module) {
3295
3295
  "use strict";
3296
3296
  var { tokenChars } = require_validation();
3297
- function parse3(header) {
3297
+ function parse4(header) {
3298
3298
  const protocols = /* @__PURE__ */ new Set();
3299
3299
  let start = -1;
3300
3300
  let end = -1;
@@ -3330,7 +3330,7 @@ var require_subprotocol = __commonJS({
3330
3330
  protocols.add(protocol2);
3331
3331
  return protocols;
3332
3332
  }
3333
- module.exports = { parse: parse3 };
3333
+ module.exports = { parse: parse4 };
3334
3334
  }
3335
3335
  });
3336
3336
 
@@ -5583,18 +5583,18 @@ var validateAsync = async (schema, value, _ctx) => {
5583
5583
  return result2.issues.length === 0;
5584
5584
  };
5585
5585
  var _encode = (_Err) => {
5586
- const parse3 = _parse(_Err);
5586
+ const parse4 = _parse(_Err);
5587
5587
  const fn = (schema, value, _ctx, _params) => {
5588
5588
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
5589
- return parse3(schema, value, ctx, finalizeParams(fn, _params));
5589
+ return parse4(schema, value, ctx, finalizeParams(fn, _params));
5590
5590
  };
5591
5591
  return fn;
5592
5592
  };
5593
5593
  var encode = /* @__PURE__ */ _encode($ZodRealError);
5594
5594
  var _decode = (_Err) => {
5595
- const parse3 = _parse(_Err);
5595
+ const parse4 = _parse(_Err);
5596
5596
  const fn = (schema, value, _ctx, _params) => {
5597
- return parse3(schema, value, _ctx, finalizeParams(fn, _params));
5597
+ return parse4(schema, value, _ctx, finalizeParams(fn, _params));
5598
5598
  };
5599
5599
  return fn;
5600
5600
  };
@@ -26479,10 +26479,12 @@ var ServerFrameSchema = external_exports.discriminatedUnion("type", [
26479
26479
  external_exports.object({ type: external_exports.literal("workspace_ack"), version: external_exports.literal(1), requestId: uuid11, workspaceGrantId: uuid11, accepted: external_exports.boolean(), code: external_exports.string().max(64).optional() }).strict(),
26480
26480
  external_exports.object({ type: external_exports.literal("revoke"), version: external_exports.literal(1), reason: external_exports.enum(["device_revoked", "account_revoked", "server_shutdown", "connection_replaced"]) }).strict()
26481
26481
  ]);
26482
+ var WORKSPACE_ACCESS_MODE_CAPABILITY = "workspaceAccessModeV1";
26483
+ var WorkspaceAccessModeSchema = external_exports.enum(["full", "scoped"]);
26482
26484
  var ClientFrameSchema = external_exports.discriminatedUnion("type", [
26483
26485
  external_exports.object({ type: external_exports.literal("ready"), version: external_exports.literal(1), safeSlots: external_exports.number().int().min(1).max(128), platform: external_exports.literal("win32"), agentVersion: external_exports.string().regex(/^[A-Za-z0-9._+-]{1,64}$/), supervisor: external_exports.boolean() }).strict(),
26484
26486
  external_exports.object({ type: external_exports.literal("heartbeat"), version: external_exports.literal(1), connectionEpoch: epoch2 }).strict(),
26485
- external_exports.object({ type: external_exports.literal("workspace_grant"), version: external_exports.literal(1), requestId: uuid11, workspaceGrantId: uuid11, rootHash: hash3, displayName: external_exports.string().min(1).max(120), policyVersion: external_exports.number().int().min(1).max(2147483647) }).strict(),
26487
+ external_exports.object({ type: external_exports.literal("workspace_grant"), version: external_exports.literal(1), requestId: uuid11, workspaceGrantId: uuid11, rootHash: hash3, displayName: external_exports.string().min(1).max(120), policyVersion: external_exports.number().int().min(1).max(2147483647), accessMode: WorkspaceAccessModeSchema.optional() }).strict(),
26486
26488
  external_exports.object({ type: external_exports.literal("workspace_revoke"), version: external_exports.literal(1), requestId: uuid11, workspaceGrantId: uuid11 }).strict(),
26487
26489
  external_exports.object({ type: external_exports.literal("prepared"), version: external_exports.literal(1), binding: ExecutionBindingSchema }).strict(),
26488
26490
  external_exports.object({ type: external_exports.literal("accepted"), version: external_exports.literal(1), binding: ExecutionBindingSchema }).strict(),
@@ -27043,9 +27045,9 @@ var NativeJournal = class _NativeJournal {
27043
27045
  if (!validPid(pid)) throw failure2("JOURNAL_INPUT_INVALID");
27044
27046
  if (e.state !== "running" || !e.supervisors) throw failure2("JOURNAL_STATE_INVALID");
27045
27047
  if (containment !== void 0) {
27046
- const linux = validLinuxContainment(containment), darwin = !linux && validDarwinContainment(containment);
27047
- if (!linux && !darwin || !e.supervisors.includes(pid) || e.linuxSupervisors?.some((s) => s.pid === pid) || e.darwinSupervisors?.some((s) => s.pid === pid)) throw failure2("JOURNAL_INPUT_INVALID");
27048
- if (linux) (e.linuxSupervisors ??= []).push({ pid, containment: clone2(containment) });
27048
+ const linux2 = validLinuxContainment(containment), darwin = !linux2 && validDarwinContainment(containment);
27049
+ if (!linux2 && !darwin || !e.supervisors.includes(pid) || e.linuxSupervisors?.some((s) => s.pid === pid) || e.darwinSupervisors?.some((s) => s.pid === pid)) throw failure2("JOURNAL_INPUT_INVALID");
27050
+ if (linux2) (e.linuxSupervisors ??= []).push({ pid, containment: clone2(containment) });
27049
27051
  else (e.darwinSupervisors ??= []).push({ pid, containment: clone2(containment) });
27050
27052
  } else {
27051
27053
  if (e.supervisors.length >= MAX_SUPERVISORS) throw failure2("JOURNAL_SUPERVISOR_LIMIT");
@@ -28918,8 +28920,8 @@ var HostMemory = class {
28918
28920
  };
28919
28921
 
28920
28922
  // agent/src/tools.ts
28921
- import { constants as constants7 } from "node:fs";
28922
- import { lstat as lstat7, open as open6, readdir as readdir4, realpath as realpath7, rename as rename4, rm as rm6 } from "node:fs/promises";
28923
+ import { constants as constants8 } from "node:fs";
28924
+ import { lstat as lstat8, open as open6, readdir as readdir5, realpath as realpath7, rename as rename4, rm as rm6 } from "node:fs/promises";
28923
28925
  import path18 from "node:path";
28924
28926
  import { createHash as createHash14, randomUUID as randomUUID7 } from "node:crypto";
28925
28927
 
@@ -29366,22 +29368,1025 @@ async function runSupervised(helper, request, options = {}) {
29366
29368
 
29367
29369
  // agent/src/screen-capture.ts
29368
29370
  import { execFile as execFile4 } from "node:child_process";
29369
- import { mkdtemp, readFile as readFile6, rm as rm5 } from "node:fs/promises";
29371
+ import { randomBytes as randomBytes6 } from "node:crypto";
29372
+ import { constants as constants7 } from "node:fs";
29373
+ import { access as access3, lstat as lstat7, mkdtemp, readFile as readFile6, readdir as readdir4, rm as rm5, unlink as unlink2 } from "node:fs/promises";
29370
29374
  import os4 from "node:os";
29371
29375
  import path17 from "node:path";
29376
+
29377
+ // agent/src/dbus-portal.ts
29378
+ import net from "node:net";
29379
+ function sessionBusSocket(address) {
29380
+ for (const entry of (address ?? "").split(";")) {
29381
+ if (!entry.startsWith("unix:")) continue;
29382
+ for (const part of entry.slice(5).split(",")) {
29383
+ const at = part.indexOf("="), key = part.slice(0, at), value = decodeURIComponent(part.slice(at + 1));
29384
+ if (at > 0 && value && key === "path") return value;
29385
+ if (at > 0 && value && key === "abstract") return "\0" + value;
29386
+ }
29387
+ }
29388
+ return null;
29389
+ }
29390
+ var Writer = class {
29391
+ bytes = [];
29392
+ align(n) {
29393
+ while (this.bytes.length % n) this.bytes.push(0);
29394
+ }
29395
+ byte(v) {
29396
+ this.bytes.push(v & 255);
29397
+ }
29398
+ u32(v) {
29399
+ this.align(4);
29400
+ this.bytes.push(v & 255, v >>> 8 & 255, v >>> 16 & 255, v >>> 24 & 255);
29401
+ }
29402
+ str(v) {
29403
+ const b = Buffer.from(v, "utf8");
29404
+ this.u32(b.length);
29405
+ this.bytes.push(...b, 0);
29406
+ }
29407
+ sig(v) {
29408
+ this.byte(v.length);
29409
+ this.bytes.push(...Buffer.from(v, "ascii"), 0);
29410
+ }
29411
+ /** Basic value or variant: `s`, `o`, `g`, `u`, `b`, `v` ([signature, value]). */
29412
+ put(type, value) {
29413
+ if (type === "s" || type === "o") this.str(String(value));
29414
+ else if (type === "g") this.sig(String(value));
29415
+ else if (type === "u") this.u32(Number(value));
29416
+ else if (type === "b") this.u32(value ? 1 : 0);
29417
+ else if (type === "v") {
29418
+ const [inner, v] = value;
29419
+ this.sig(inner);
29420
+ this.put(inner, v);
29421
+ } else throw Error("type " + type);
29422
+ }
29423
+ /** a{sv} */
29424
+ dict(entries) {
29425
+ this.u32(0);
29426
+ const lengthAt = this.bytes.length - 4;
29427
+ this.align(8);
29428
+ const start = this.bytes.length;
29429
+ for (const [key, value] of entries) {
29430
+ this.align(8);
29431
+ this.str(key);
29432
+ this.put("v", value);
29433
+ }
29434
+ const length = this.bytes.length - start;
29435
+ this.bytes.splice(lengthAt, 4, length & 255, length >>> 8 & 255, length >>> 16 & 255, length >>> 24 & 255);
29436
+ }
29437
+ };
29438
+ var Reader = class {
29439
+ constructor(data, at, le) {
29440
+ this.data = data;
29441
+ this.at = at;
29442
+ this.le = le;
29443
+ }
29444
+ data;
29445
+ at;
29446
+ le;
29447
+ align(n) {
29448
+ this.at = Math.ceil(this.at / n) * n;
29449
+ }
29450
+ u32() {
29451
+ this.align(4);
29452
+ const v = this.le ? this.data.readUInt32LE(this.at) : this.data.readUInt32BE(this.at);
29453
+ this.at += 4;
29454
+ return v;
29455
+ }
29456
+ /** Reads one complete type from `sig` starting at `i`; returns the value and the index after the type. */
29457
+ read(sig2, i) {
29458
+ const c = sig2[i];
29459
+ const fixed = { y: 1, n: 2, q: 2, b: 4, i: 4, u: 4, h: 4, x: 8, t: 8, d: 8 };
29460
+ if (c in fixed) {
29461
+ const size = fixed[c];
29462
+ this.align(size);
29463
+ const v = size === 1 ? this.data[this.at] : size === 2 ? this.le ? this.data.readUInt16LE(this.at) : this.data.readUInt16BE(this.at) : size === 4 ? this.le ? this.data.readUInt32LE(this.at) : this.data.readUInt32BE(this.at) : null;
29464
+ this.at += size;
29465
+ return [c === "b" ? v === 1 : v, i + 1];
29466
+ }
29467
+ if (c === "s" || c === "o") {
29468
+ const n = this.u32(), v = this.data.toString("utf8", this.at, this.at + n);
29469
+ this.at += n + 1;
29470
+ return [v, i + 1];
29471
+ }
29472
+ if (c === "g") {
29473
+ const n = this.data[this.at], v = this.data.toString("ascii", this.at + 1, this.at + 1 + n);
29474
+ this.at += n + 2;
29475
+ return [v, i + 1];
29476
+ }
29477
+ if (c === "v") {
29478
+ const [inner] = this.read("g", 0);
29479
+ return [this.read(inner, 0)[0], i + 1];
29480
+ }
29481
+ if (c === "(" || c === "{") {
29482
+ this.align(8);
29483
+ const close = c === "(" ? ")" : "}", values = [];
29484
+ let j = i + 1;
29485
+ while (sig2[j] !== close) {
29486
+ const [v, next] = this.read(sig2, j);
29487
+ values.push(v);
29488
+ j = next;
29489
+ }
29490
+ return [values, j + 1];
29491
+ }
29492
+ if (c === "a") {
29493
+ const n = this.u32(), element = sig2[i + 1];
29494
+ this.align("xtd({".includes(element) ? 8 : element === "n" || element === "q" ? 2 : element === "y" || element === "g" || element === "v" ? 1 : 4);
29495
+ const end = this.at + n, values = [];
29496
+ let next = skip(sig2, i + 1);
29497
+ while (this.at < end) {
29498
+ const [v, j] = this.read(sig2, i + 1);
29499
+ values.push(v);
29500
+ next = j;
29501
+ }
29502
+ return [values, next];
29503
+ }
29504
+ throw Error("signature " + sig2);
29505
+ }
29506
+ };
29507
+ function skip(sig2, i) {
29508
+ const c = sig2[i];
29509
+ if (c === "a") return skip(sig2, i + 1);
29510
+ if (c === "(" || c === "{") {
29511
+ let j = i + 1;
29512
+ while (sig2[j] !== (c === "(" ? ")" : "}")) j = skip(sig2, j);
29513
+ return j + 1;
29514
+ }
29515
+ return i + 1;
29516
+ }
29517
+ function parse3(data) {
29518
+ const le = data[0] === 108, r = new Reader(data, 4, le), bodyLength = r.u32(), serial = r.u32();
29519
+ const [fields] = r.read("a(yv)", 0);
29520
+ const message2 = { type: data[1], serial, signature: "", body: [] };
29521
+ for (const [code, value] of fields) {
29522
+ if (code === 1) message2.path = String(value);
29523
+ else if (code === 2) message2.interface = String(value);
29524
+ else if (code === 3) message2.member = String(value);
29525
+ else if (code === 4) message2.errorName = String(value);
29526
+ else if (code === 5) message2.replySerial = Number(value);
29527
+ else if (code === 8) message2.signature = String(value);
29528
+ }
29529
+ r.align(8);
29530
+ const end = r.at + bodyLength;
29531
+ for (let i = 0; i < message2.signature.length && r.at < end; ) {
29532
+ const [v, next] = r.read(message2.signature, i);
29533
+ message2.body.push(v);
29534
+ i = next;
29535
+ }
29536
+ return message2;
29537
+ }
29538
+ function frameLength(data) {
29539
+ if (data.length < 16) return 0;
29540
+ const le = data[0] === 108, u = (at) => le ? data.readUInt32LE(at) : data.readUInt32BE(at);
29541
+ const length = Math.ceil((16 + u(12)) / 8) * 8 + u(4);
29542
+ return data.length >= length ? length : 0;
29543
+ }
29544
+ async function portalScreenshot(socket, uid, token, signal) {
29545
+ const connection = net.createConnection({ path: socket });
29546
+ try {
29547
+ return await new Promise((resolve, reject) => {
29548
+ let serial = 0, buffer = Buffer.alloc(0), authenticated = false, requestPath = "";
29549
+ const pending = /* @__PURE__ */ new Map();
29550
+ const fail7 = (error62) => reject(error62 instanceof Error ? error62 : Error(String(error62)));
29551
+ const abort = () => fail7(Error("ABORTED"));
29552
+ if (signal.aborted) return abort();
29553
+ signal.addEventListener("abort", abort, { once: true });
29554
+ connection.on("error", fail7);
29555
+ connection.on("close", () => fail7(Error("CLOSED")));
29556
+ const call = (destination, path30, iface, member, signature = "", body = () => {
29557
+ }) => new Promise((done, failed) => {
29558
+ const payload2 = new Writer();
29559
+ body(payload2);
29560
+ const header = new Writer(), fields = [[1, "o", path30], [2, "s", iface], [3, "s", member], [6, "s", destination]];
29561
+ if (signature) fields.push([8, "g", signature]);
29562
+ header.byte(108);
29563
+ header.byte(1);
29564
+ header.byte(0);
29565
+ header.byte(1);
29566
+ header.u32(payload2.bytes.length);
29567
+ header.u32(++serial);
29568
+ header.u32(0);
29569
+ const lengthAt = header.bytes.length - 4;
29570
+ header.align(8);
29571
+ const start = header.bytes.length;
29572
+ for (const [code, type, value] of fields) {
29573
+ header.align(8);
29574
+ header.byte(code);
29575
+ header.sig(type);
29576
+ header.put(type, value);
29577
+ }
29578
+ const length = header.bytes.length - start;
29579
+ header.bytes.splice(lengthAt, 4, length & 255, length >>> 8 & 255, length >>> 16 & 255, length >>> 24 & 255);
29580
+ header.align(8);
29581
+ pending.set(serial, (reply) => reply.type === 3 ? failed(Error(reply.errorName ?? "DBUS_ERROR")) : done(reply));
29582
+ connection.write(Buffer.from([...header.bytes, ...payload2.bytes]));
29583
+ });
29584
+ const bus = (member, signature, body) => call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", member, signature, body);
29585
+ connection.on("data", (chunk) => {
29586
+ try {
29587
+ receive(chunk);
29588
+ } catch (error62) {
29589
+ fail7(error62);
29590
+ }
29591
+ });
29592
+ const receive = (chunk) => {
29593
+ buffer = Buffer.concat([buffer, chunk]);
29594
+ if (buffer.length > 1048576) return fail7(Error("OVERSIZED"));
29595
+ if (!authenticated) {
29596
+ const end = buffer.indexOf("\r\n");
29597
+ if (end < 0) return;
29598
+ const line = buffer.toString("ascii", 0, end);
29599
+ buffer = buffer.subarray(end + 2);
29600
+ if (!line.startsWith("OK ")) return fail7(Error("AUTH"));
29601
+ authenticated = true;
29602
+ connection.write("BEGIN\r\n");
29603
+ void (async () => {
29604
+ const unique = String((await bus("Hello")).body[0]);
29605
+ requestPath = "/org/freedesktop/portal/desktop/request/" + unique.slice(1).replace(/\./g, "_") + "/" + token;
29606
+ await bus("AddMatch", "s", (w) => w.put("s", "type='signal',interface='org.freedesktop.portal.Request',member='Response',path='" + requestPath + "'"));
29607
+ const handle = await call(
29608
+ "org.freedesktop.portal.Desktop",
29609
+ "/org/freedesktop/portal/desktop",
29610
+ "org.freedesktop.portal.Screenshot",
29611
+ "Screenshot",
29612
+ "sa{sv}",
29613
+ (w) => {
29614
+ w.put("s", "");
29615
+ w.dict([["handle_token", ["s", token]], ["interactive", ["b", false]]]);
29616
+ }
29617
+ );
29618
+ if (handle.body[0] !== requestPath) {
29619
+ requestPath = String(handle.body[0]);
29620
+ await bus("AddMatch", "s", (w) => w.put("s", "type='signal',interface='org.freedesktop.portal.Request',member='Response',path='" + requestPath + "'"));
29621
+ }
29622
+ })().catch(fail7);
29623
+ }
29624
+ for (let length = frameLength(buffer); authenticated && length; length = frameLength(buffer)) {
29625
+ const message2 = parse3(buffer.subarray(0, length));
29626
+ buffer = buffer.subarray(length);
29627
+ if ((message2.type === 2 || message2.type === 3) && message2.replySerial !== void 0) {
29628
+ pending.get(message2.replySerial)?.(message2);
29629
+ pending.delete(message2.replySerial);
29630
+ } else if (message2.type === 4 && message2.member === "Response" && message2.path === requestPath && message2.signature === "ua{sv}") {
29631
+ const results2 = message2.body[1], uri = results2.find(([key]) => key === "uri")?.[1];
29632
+ resolve({ code: Number(message2.body[0]), uri: typeof uri === "string" ? uri : void 0 });
29633
+ }
29634
+ }
29635
+ };
29636
+ connection.on("connect", () => connection.write("\0AUTH EXTERNAL " + Buffer.from(String(uid), "ascii").toString("hex") + "\r\n"));
29637
+ });
29638
+ } finally {
29639
+ connection.destroy();
29640
+ }
29641
+ }
29642
+
29643
+ // agent/src/screen-image.ts
29644
+ import { inflateSync } from "node:zlib";
29645
+ var MAX_EDGE = 16384;
29646
+ var MAX_PIXELS = 67108864;
29647
+ function sizeOk(width, height) {
29648
+ return Number.isSafeInteger(width) && Number.isSafeInteger(height) && width > 0 && height > 0 && width <= MAX_EDGE && height <= MAX_EDGE && width * height <= MAX_PIXELS;
29649
+ }
29650
+ function decodePng(data) {
29651
+ if (data.length < 33 || data.readUInt32BE(0) !== 2303741511 || data.readUInt32BE(4) !== 218765834) return null;
29652
+ let width = 0, height = 0, channels = 0;
29653
+ const idat = [];
29654
+ for (let at = 8; at + 12 <= data.length; ) {
29655
+ const length = data.readUInt32BE(at), type = data.toString("latin1", at + 4, at + 8), body = at + 8;
29656
+ if (body + length + 4 > data.length) return null;
29657
+ if (type === "IHDR") {
29658
+ if (length !== 13) return null;
29659
+ width = data.readUInt32BE(body);
29660
+ height = data.readUInt32BE(body + 4);
29661
+ const depth = data[body + 8], color = data[body + 9], interlace = data[body + 12];
29662
+ channels = color === 0 ? 1 : color === 2 ? 3 : color === 4 ? 2 : color === 6 ? 4 : 0;
29663
+ if (depth !== 8 || !channels || interlace !== 0 || data[body + 10] !== 0 || data[body + 11] !== 0 || !sizeOk(width, height)) return null;
29664
+ } else if (type === "IDAT") idat.push(data.subarray(body, body + length));
29665
+ else if (type === "IEND") break;
29666
+ at = body + length + 4;
29667
+ }
29668
+ if (!channels || !idat.length) return null;
29669
+ const stride = width * channels, expected = (stride + 1) * height;
29670
+ let raw;
29671
+ try {
29672
+ raw = inflateSync(Buffer.concat(idat), { maxOutputLength: expected });
29673
+ } catch {
29674
+ return null;
29675
+ }
29676
+ if (raw.length !== expected) return null;
29677
+ const rgb = Buffer.alloc(width * height * 3);
29678
+ let previous = Buffer.alloc(stride), current2 = Buffer.alloc(stride);
29679
+ for (let y = 0; y < height; y++) {
29680
+ const filter = raw[y * (stride + 1)], line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
29681
+ for (let x = 0; x < stride; x++) {
29682
+ const a = x >= channels ? current2[x - channels] : 0, b = previous[x], c = x >= channels ? previous[x - channels] : 0;
29683
+ let value = line[x];
29684
+ if (filter === 1) value += a;
29685
+ else if (filter === 2) value += b;
29686
+ else if (filter === 3) value += a + b >> 1;
29687
+ else if (filter === 4) {
29688
+ const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
29689
+ value += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
29690
+ } else if (filter !== 0) return null;
29691
+ current2[x] = value & 255;
29692
+ }
29693
+ for (let x = 0, o = y * width * 3; x < width; x++, o += 3) {
29694
+ const i = x * channels;
29695
+ if (channels <= 2) rgb[o] = rgb[o + 1] = rgb[o + 2] = current2[i];
29696
+ else {
29697
+ rgb[o] = current2[i];
29698
+ rgb[o + 1] = current2[i + 1];
29699
+ rgb[o + 2] = current2[i + 2];
29700
+ }
29701
+ }
29702
+ [previous, current2] = [current2, previous];
29703
+ }
29704
+ return { width, height, rgb };
29705
+ }
29706
+ function decodeXwd(data) {
29707
+ if (data.length < 100) return null;
29708
+ const field = (index) => data.readUInt32BE(index * 4);
29709
+ const headerSize = field(0), version2 = field(1), format = field(2), width = field(4), height = field(5), byteOrder = field(7);
29710
+ const bitsPerPixel = field(11), bytesPerLine = field(12), visualClass = field(13), masks = [field(14), field(15), field(16)], colors = field(19);
29711
+ if (version2 !== 7 || format !== 2 || headerSize < 100 || ![4, 5].includes(visualClass) || ![24, 32].includes(bitsPerPixel) || !sizeOk(width, height) || colors > 65536) return null;
29712
+ const pixelBytes = bitsPerPixel / 8, start = headerSize + colors * 12;
29713
+ if (bytesPerLine < width * pixelBytes || start + bytesPerLine * height > data.length || masks.some((mask) => !mask)) return null;
29714
+ const shifts = masks.map((mask) => {
29715
+ let shift = 0;
29716
+ while (!(mask >>> shift & 1)) shift++;
29717
+ return shift;
29718
+ });
29719
+ const scales = masks.map((mask, i) => 255 / (mask >>> shifts[i]));
29720
+ const rgb = Buffer.alloc(width * height * 3);
29721
+ for (let y = 0; y < height; y++) for (let x = 0, at = start + y * bytesPerLine, o = y * width * 3; x < width; x++, at += pixelBytes, o += 3) {
29722
+ const pixel = pixelBytes === 4 ? byteOrder === 0 ? data.readUInt32LE(at) : data.readUInt32BE(at) : byteOrder === 0 ? data[at] | data[at + 1] << 8 | data[at + 2] << 16 : data[at] << 16 | data[at + 1] << 8 | data[at + 2];
29723
+ for (let c = 0; c < 3; c++) rgb[o + c] = Math.round(((pixel & masks[c]) >>> 0 >>> shifts[c]) * scales[c]);
29724
+ }
29725
+ return { width, height, rgb };
29726
+ }
29727
+ function downscale(image, edge) {
29728
+ const scale = Math.min(1, edge / Math.max(image.width, image.height));
29729
+ if (scale >= 1) return image;
29730
+ const width = Math.max(1, Math.round(image.width * scale)), height = Math.max(1, Math.round(image.height * scale));
29731
+ const xs = Array.from({ length: width + 1 }, (_, x) => Math.min(image.width, Math.floor(x * image.width / width)));
29732
+ const ys = Array.from({ length: height + 1 }, (_, y) => Math.min(image.height, Math.floor(y * image.height / height)));
29733
+ const rgb = Buffer.alloc(width * height * 3), sums = new Float64Array(width * 3);
29734
+ for (let y = 0; y < height; y++) {
29735
+ sums.fill(0);
29736
+ for (let sy = ys[y]; sy < ys[y + 1]; sy++) for (let x = 0; x < width; x++) for (let sx = xs[x]; sx < xs[x + 1]; sx++) {
29737
+ const i = (sy * image.width + sx) * 3;
29738
+ sums[x * 3] = sums[x * 3] + image.rgb[i];
29739
+ sums[x * 3 + 1] = sums[x * 3 + 1] + image.rgb[i + 1];
29740
+ sums[x * 3 + 2] = sums[x * 3 + 2] + image.rgb[i + 2];
29741
+ }
29742
+ for (let x = 0; x < width; x++) {
29743
+ const count3 = (ys[y + 1] - ys[y]) * (xs[x + 1] - xs[x]);
29744
+ for (let c = 0; c < 3; c++) rgb[(y * width + x) * 3 + c] = Math.round(sums[x * 3 + c] / count3);
29745
+ }
29746
+ }
29747
+ return { width, height, rgb };
29748
+ }
29749
+ var ZIGZAG = [
29750
+ 0,
29751
+ 1,
29752
+ 5,
29753
+ 6,
29754
+ 14,
29755
+ 15,
29756
+ 27,
29757
+ 28,
29758
+ 2,
29759
+ 4,
29760
+ 7,
29761
+ 13,
29762
+ 16,
29763
+ 26,
29764
+ 29,
29765
+ 42,
29766
+ 3,
29767
+ 8,
29768
+ 12,
29769
+ 17,
29770
+ 25,
29771
+ 30,
29772
+ 41,
29773
+ 43,
29774
+ 9,
29775
+ 11,
29776
+ 18,
29777
+ 24,
29778
+ 31,
29779
+ 40,
29780
+ 44,
29781
+ 53,
29782
+ 10,
29783
+ 19,
29784
+ 23,
29785
+ 32,
29786
+ 39,
29787
+ 45,
29788
+ 52,
29789
+ 54,
29790
+ 20,
29791
+ 22,
29792
+ 33,
29793
+ 38,
29794
+ 46,
29795
+ 51,
29796
+ 55,
29797
+ 60,
29798
+ 21,
29799
+ 34,
29800
+ 37,
29801
+ 47,
29802
+ 50,
29803
+ 56,
29804
+ 59,
29805
+ 61,
29806
+ 35,
29807
+ 36,
29808
+ 48,
29809
+ 49,
29810
+ 57,
29811
+ 58,
29812
+ 62,
29813
+ 63
29814
+ ];
29815
+ var LUMA_QUANT = [
29816
+ 16,
29817
+ 11,
29818
+ 10,
29819
+ 16,
29820
+ 24,
29821
+ 40,
29822
+ 51,
29823
+ 61,
29824
+ 12,
29825
+ 12,
29826
+ 14,
29827
+ 19,
29828
+ 26,
29829
+ 58,
29830
+ 60,
29831
+ 55,
29832
+ 14,
29833
+ 13,
29834
+ 16,
29835
+ 24,
29836
+ 40,
29837
+ 57,
29838
+ 69,
29839
+ 56,
29840
+ 14,
29841
+ 17,
29842
+ 22,
29843
+ 29,
29844
+ 51,
29845
+ 87,
29846
+ 80,
29847
+ 62,
29848
+ 18,
29849
+ 22,
29850
+ 37,
29851
+ 56,
29852
+ 68,
29853
+ 109,
29854
+ 103,
29855
+ 77,
29856
+ 24,
29857
+ 35,
29858
+ 55,
29859
+ 64,
29860
+ 81,
29861
+ 104,
29862
+ 113,
29863
+ 92,
29864
+ 49,
29865
+ 64,
29866
+ 78,
29867
+ 87,
29868
+ 103,
29869
+ 121,
29870
+ 120,
29871
+ 101,
29872
+ 72,
29873
+ 92,
29874
+ 95,
29875
+ 98,
29876
+ 112,
29877
+ 100,
29878
+ 103,
29879
+ 99
29880
+ ];
29881
+ var CHROMA_QUANT = [17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, ...Array(38).fill(99)];
29882
+ var AC_LUMA_VALUES = [
29883
+ 1,
29884
+ 2,
29885
+ 3,
29886
+ 0,
29887
+ 4,
29888
+ 17,
29889
+ 5,
29890
+ 18,
29891
+ 33,
29892
+ 49,
29893
+ 65,
29894
+ 6,
29895
+ 19,
29896
+ 81,
29897
+ 97,
29898
+ 7,
29899
+ 34,
29900
+ 113,
29901
+ 20,
29902
+ 50,
29903
+ 129,
29904
+ 145,
29905
+ 161,
29906
+ 8,
29907
+ 35,
29908
+ 66,
29909
+ 177,
29910
+ 193,
29911
+ 21,
29912
+ 82,
29913
+ 209,
29914
+ 240,
29915
+ 36,
29916
+ 51,
29917
+ 98,
29918
+ 114,
29919
+ 130,
29920
+ 9,
29921
+ 10,
29922
+ 22,
29923
+ 23,
29924
+ 24,
29925
+ 25,
29926
+ 26,
29927
+ 37,
29928
+ 38,
29929
+ 39,
29930
+ 40,
29931
+ 41,
29932
+ 42,
29933
+ 52,
29934
+ 53,
29935
+ 54,
29936
+ 55,
29937
+ 56,
29938
+ 57,
29939
+ 58,
29940
+ 67,
29941
+ 68,
29942
+ 69,
29943
+ 70,
29944
+ 71,
29945
+ 72,
29946
+ 73,
29947
+ 74,
29948
+ 83,
29949
+ 84,
29950
+ 85,
29951
+ 86,
29952
+ 87,
29953
+ 88,
29954
+ 89,
29955
+ 90,
29956
+ 99,
29957
+ 100,
29958
+ 101,
29959
+ 102,
29960
+ 103,
29961
+ 104,
29962
+ 105,
29963
+ 106,
29964
+ 115,
29965
+ 116,
29966
+ 117,
29967
+ 118,
29968
+ 119,
29969
+ 120,
29970
+ 121,
29971
+ 122,
29972
+ 131,
29973
+ 132,
29974
+ 133,
29975
+ 134,
29976
+ 135,
29977
+ 136,
29978
+ 137,
29979
+ 138,
29980
+ 146,
29981
+ 147,
29982
+ 148,
29983
+ 149,
29984
+ 150,
29985
+ 151,
29986
+ 152,
29987
+ 153,
29988
+ 154,
29989
+ 162,
29990
+ 163,
29991
+ 164,
29992
+ 165,
29993
+ 166,
29994
+ 167,
29995
+ 168,
29996
+ 169,
29997
+ 170,
29998
+ 178,
29999
+ 179,
30000
+ 180,
30001
+ 181,
30002
+ 182,
30003
+ 183,
30004
+ 184,
30005
+ 185,
30006
+ 186,
30007
+ 194,
30008
+ 195,
30009
+ 196,
30010
+ 197,
30011
+ 198,
30012
+ 199,
30013
+ 200,
30014
+ 201,
30015
+ 202,
30016
+ 210,
30017
+ 211,
30018
+ 212,
30019
+ 213,
30020
+ 214,
30021
+ 215,
30022
+ 216,
30023
+ 217,
30024
+ 218,
30025
+ 225,
30026
+ 226,
30027
+ 227,
30028
+ 228,
30029
+ 229,
30030
+ 230,
30031
+ 231,
30032
+ 232,
30033
+ 233,
30034
+ 234,
30035
+ 241,
30036
+ 242,
30037
+ 243,
30038
+ 244,
30039
+ 245,
30040
+ 246,
30041
+ 247,
30042
+ 248,
30043
+ 249,
30044
+ 250
30045
+ ];
30046
+ var AC_CHROMA_VALUES = [
30047
+ 0,
30048
+ 1,
30049
+ 2,
30050
+ 3,
30051
+ 17,
30052
+ 4,
30053
+ 5,
30054
+ 33,
30055
+ 49,
30056
+ 6,
30057
+ 18,
30058
+ 65,
30059
+ 81,
30060
+ 7,
30061
+ 97,
30062
+ 113,
30063
+ 19,
30064
+ 34,
30065
+ 50,
30066
+ 129,
30067
+ 8,
30068
+ 20,
30069
+ 66,
30070
+ 145,
30071
+ 161,
30072
+ 177,
30073
+ 193,
30074
+ 9,
30075
+ 35,
30076
+ 51,
30077
+ 82,
30078
+ 240,
30079
+ 21,
30080
+ 98,
30081
+ 114,
30082
+ 209,
30083
+ 10,
30084
+ 22,
30085
+ 36,
30086
+ 52,
30087
+ 225,
30088
+ 37,
30089
+ 241,
30090
+ 23,
30091
+ 24,
30092
+ 25,
30093
+ 26,
30094
+ 38,
30095
+ 39,
30096
+ 40,
30097
+ 41,
30098
+ 42,
30099
+ 53,
30100
+ 54,
30101
+ 55,
30102
+ 56,
30103
+ 57,
30104
+ 58,
30105
+ 67,
30106
+ 68,
30107
+ 69,
30108
+ 70,
30109
+ 71,
30110
+ 72,
30111
+ 73,
30112
+ 74,
30113
+ 83,
30114
+ 84,
30115
+ 85,
30116
+ 86,
30117
+ 87,
30118
+ 88,
30119
+ 89,
30120
+ 90,
30121
+ 99,
30122
+ 100,
30123
+ 101,
30124
+ 102,
30125
+ 103,
30126
+ 104,
30127
+ 105,
30128
+ 106,
30129
+ 115,
30130
+ 116,
30131
+ 117,
30132
+ 118,
30133
+ 119,
30134
+ 120,
30135
+ 121,
30136
+ 122,
30137
+ 130,
30138
+ 131,
30139
+ 132,
30140
+ 133,
30141
+ 134,
30142
+ 135,
30143
+ 136,
30144
+ 137,
30145
+ 138,
30146
+ 146,
30147
+ 147,
30148
+ 148,
30149
+ 149,
30150
+ 150,
30151
+ 151,
30152
+ 152,
30153
+ 153,
30154
+ 154,
30155
+ 162,
30156
+ 163,
30157
+ 164,
30158
+ 165,
30159
+ 166,
30160
+ 167,
30161
+ 168,
30162
+ 169,
30163
+ 170,
30164
+ 178,
30165
+ 179,
30166
+ 180,
30167
+ 181,
30168
+ 182,
30169
+ 183,
30170
+ 184,
30171
+ 185,
30172
+ 186,
30173
+ 194,
30174
+ 195,
30175
+ 196,
30176
+ 197,
30177
+ 198,
30178
+ 199,
30179
+ 200,
30180
+ 201,
30181
+ 202,
30182
+ 210,
30183
+ 211,
30184
+ 212,
30185
+ 213,
30186
+ 214,
30187
+ 215,
30188
+ 216,
30189
+ 217,
30190
+ 218,
30191
+ 226,
30192
+ 227,
30193
+ 228,
30194
+ 229,
30195
+ 230,
30196
+ 231,
30197
+ 232,
30198
+ 233,
30199
+ 234,
30200
+ 242,
30201
+ 243,
30202
+ 244,
30203
+ 245,
30204
+ 246,
30205
+ 247,
30206
+ 248,
30207
+ 249,
30208
+ 250
30209
+ ];
30210
+ var DC_VALUES = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
30211
+ var HUFFMAN = [
30212
+ [0, [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], DC_VALUES],
30213
+ [16, [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125], AC_LUMA_VALUES],
30214
+ [1, [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], DC_VALUES],
30215
+ [17, [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119], AC_CHROMA_VALUES]
30216
+ ];
30217
+ var CODES = HUFFMAN.map(([, counts, values]) => {
30218
+ const table2 = [];
30219
+ let code = 0, at = 0;
30220
+ counts.forEach((count3, index) => {
30221
+ for (let i = 0; i < count3; i++) table2[values[at++]] = [code++, index + 1];
30222
+ code <<= 1;
30223
+ });
30224
+ return table2;
30225
+ });
30226
+ var AAN = [1, 1.387039845, 1.306562965, 1.175875602, 1, 0.785694958, 0.5411961, 0.275899379];
30227
+ function quantTables(quality) {
30228
+ const factor = quality < 50 ? 5e3 / quality : 200 - quality * 2;
30229
+ const scaled = (base) => base.map((value) => Math.min(255, Math.max(1, Math.floor((value * factor + 50) / 100))));
30230
+ const divisors = (table2) => Float64Array.from(table2, (value, k) => 1 / (value * AAN[k >> 3] * AAN[k & 7] * 8));
30231
+ const luma = scaled(LUMA_QUANT), chroma = scaled(CHROMA_QUANT);
30232
+ return { luma, chroma, lumaDivisors: divisors(luma), chromaDivisors: divisors(chroma) };
30233
+ }
30234
+ var BitWriter = class {
30235
+ buffer = Buffer.alloc(65536);
30236
+ length = 0;
30237
+ bits = 0;
30238
+ count = 0;
30239
+ byte(value) {
30240
+ if (this.length === this.buffer.length) {
30241
+ const next = Buffer.alloc(this.buffer.length * 2);
30242
+ this.buffer.copy(next);
30243
+ this.buffer = next;
30244
+ }
30245
+ this.buffer[this.length++] = value;
30246
+ }
30247
+ bytes(values) {
30248
+ for (const value of values) this.byte(value);
30249
+ }
30250
+ write(code, length) {
30251
+ this.bits = (this.bits << length | code) >>> 0;
30252
+ this.count += length;
30253
+ while (this.count >= 8) {
30254
+ const value = this.bits >>> this.count - 8 & 255;
30255
+ this.byte(value);
30256
+ if (value === 255) this.byte(0);
30257
+ this.count -= 8;
30258
+ this.bits &= (1 << this.count) - 1;
30259
+ }
30260
+ }
30261
+ flush() {
30262
+ if (this.count > 0) this.write((1 << 8 - this.count) - 1, 8 - this.count);
30263
+ }
30264
+ result() {
30265
+ return Buffer.from(this.buffer.subarray(0, this.length));
30266
+ }
30267
+ };
30268
+ function transform2(block, divisors, out) {
30269
+ for (let pass = 0; pass < 2; pass++) for (let i = 0; i < 8; i++) {
30270
+ const step = pass ? 8 : 1, base = pass ? i : i * 8, at = (k) => base + k * step;
30271
+ const d0 = block[at(0)], d1 = block[at(1)], d2 = block[at(2)], d3 = block[at(3)], d4 = block[at(4)], d5 = block[at(5)], d6 = block[at(6)], d7 = block[at(7)];
30272
+ const t0 = d0 + d7, t7 = d0 - d7, t1 = d1 + d6, t6 = d1 - d6, t2 = d2 + d5, t5 = d2 - d5, t3 = d3 + d4, t4 = d3 - d4;
30273
+ const t10 = t0 + t3, t13 = t0 - t3, t11 = t1 + t2, t12 = t1 - t2;
30274
+ block[at(0)] = t10 + t11;
30275
+ block[at(4)] = t10 - t11;
30276
+ const z1 = (t12 + t13) * 0.707106781;
30277
+ block[at(2)] = t13 + z1;
30278
+ block[at(6)] = t13 - z1;
30279
+ const o10 = t4 + t5, o11 = t5 + t6, o12 = t6 + t7;
30280
+ const z5 = (o10 - o12) * 0.382683433, z2 = 0.5411961 * o10 + z5, z4 = 1.306562965 * o12 + z5, z3 = o11 * 0.707106781;
30281
+ const z11 = t7 + z3, z13 = t7 - z3;
30282
+ block[at(5)] = z13 + z2;
30283
+ block[at(3)] = z13 - z2;
30284
+ block[at(1)] = z11 + z4;
30285
+ block[at(7)] = z11 - z4;
30286
+ }
30287
+ for (let k = 0; k < 64; k++) out[ZIGZAG[k]] = Math.round(block[k] * divisors[k]);
30288
+ }
30289
+ function magnitude(value) {
30290
+ const absolute2 = Math.abs(value);
30291
+ let length = 0;
30292
+ while (absolute2 >> length) length++;
30293
+ return [value < 0 ? value + (1 << length) - 1 : value, length];
30294
+ }
30295
+ function encodeJpeg(image, quality) {
30296
+ const { width, height, rgb } = image, tables = quantTables(Math.min(100, Math.max(1, Math.round(quality))));
30297
+ const out = new BitWriter(), word = (value) => [value >> 8, value & 255];
30298
+ out.bytes([255, 216, 255, 224, 0, 16, 74, 70, 73, 70, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]);
30299
+ out.bytes([255, 219, 0, 132]);
30300
+ for (const [id2, table2] of [[0, tables.luma], [1, tables.chroma]]) {
30301
+ const zig = new Array(64);
30302
+ table2.forEach((value, k) => {
30303
+ zig[ZIGZAG[k]] = value;
30304
+ });
30305
+ out.bytes([id2, ...zig]);
30306
+ }
30307
+ out.bytes([255, 192, 0, 17, 8, ...word(height), ...word(width), 3, 1, 34, 0, 2, 17, 1, 3, 17, 1]);
30308
+ out.bytes([255, 196, ...word(2 + HUFFMAN.reduce((sum, [, , values]) => sum + 17 + values.length, 0))]);
30309
+ for (const [id2, counts, values] of HUFFMAN) out.bytes([id2, ...counts, ...values]);
30310
+ out.bytes([255, 218, 0, 12, 3, 1, 0, 2, 17, 3, 17, 0, 63, 0]);
30311
+ const block = new Float64Array(64), coefficients = new Int32Array(64), dc = [0, 0, 0];
30312
+ const Y = new Float64Array(256), Cb = new Float64Array(256), Cr = new Float64Array(256);
30313
+ const encode5 = (component, divisors) => {
30314
+ transform2(block, divisors, coefficients);
30315
+ const dcCodes = CODES[component ? 2 : 0], acCodes = CODES[component ? 3 : 1];
30316
+ const diff = coefficients[0] - dc[component];
30317
+ dc[component] = coefficients[0];
30318
+ const [bits, size] = magnitude(diff);
30319
+ out.write(...dcCodes[size]);
30320
+ if (size) out.write(bits, size);
30321
+ let last = 63;
30322
+ while (last > 0 && coefficients[last] === 0) last--;
30323
+ for (let k = 1, zeros = 0; k <= last; k++) {
30324
+ if (coefficients[k] === 0) {
30325
+ zeros++;
30326
+ continue;
30327
+ }
30328
+ while (zeros >= 16) {
30329
+ out.write(...acCodes[240]);
30330
+ zeros -= 16;
30331
+ }
30332
+ const [value, length] = magnitude(coefficients[k]);
30333
+ out.write(...acCodes[(zeros << 4) + length]);
30334
+ out.write(value, length);
30335
+ zeros = 0;
30336
+ }
30337
+ if (last < 63) out.write(...acCodes[0]);
30338
+ };
30339
+ for (let my = 0; my < height; my += 16) for (let mx = 0; mx < width; mx += 16) {
30340
+ for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) {
30341
+ const i = (Math.min(height - 1, my + y) * width + Math.min(width - 1, mx + x)) * 3, r = rgb[i], g = rgb[i + 1], b = rgb[i + 2];
30342
+ Y[y * 16 + x] = 0.299 * r + 0.587 * g + 0.114 * b - 128;
30343
+ Cb[y * 16 + x] = -0.168736 * r - 0.331264 * g + 0.5 * b;
30344
+ Cr[y * 16 + x] = 0.5 * r - 0.418688 * g - 0.081312 * b;
30345
+ }
30346
+ for (const [ox, oy] of [[0, 0], [8, 0], [0, 8], [8, 8]]) {
30347
+ for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) block[y * 8 + x] = Y[(oy + y) * 16 + ox + x];
30348
+ encode5(0, tables.lumaDivisors);
30349
+ }
30350
+ for (const [component, plane] of [[1, Cb], [2, Cr]]) {
30351
+ for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) {
30352
+ const at = y * 32 + x * 2;
30353
+ block[y * 8 + x] = (plane[at] + plane[at + 1] + plane[at + 16] + plane[at + 17]) / 4;
30354
+ }
30355
+ encode5(component, tables.chromaDivisors);
30356
+ }
30357
+ }
30358
+ out.flush();
30359
+ out.bytes([255, 217]);
30360
+ return out.result();
30361
+ }
30362
+ function fitJpeg(image, maxEdge, maxBytes) {
30363
+ for (const edge of [maxEdge, 1280, 1024, 800, 640]) {
30364
+ const scaled = downscale(image, edge);
30365
+ for (const quality of [75, 60, 45, 35]) {
30366
+ const data = encodeJpeg(scaled, quality);
30367
+ if (data.length <= maxBytes) return { data, width: scaled.width, height: scaled.height };
30368
+ }
30369
+ }
30370
+ return null;
30371
+ }
30372
+
30373
+ // agent/src/screen-capture.ts
29372
30374
  var SCREENSHOT_MAX_JPEG_BYTES = 131072;
29373
30375
  var SCREENSHOT_MAX_EDGE = 1568;
29374
30376
  function screenshotEnabled(env = process.env) {
29375
30377
  return env.LC_SCREENSHOT_ENABLED === "true";
29376
30378
  }
29377
30379
  var SCREENSHOT_ACCEPTANCE_FILE = "screenshot-acceptance-enabled";
30380
+ var SCREENSHOT_OWNER_OFF_FILE = "screenshot-disabled-by-owner";
29378
30381
  var ScreenCaptureError = class extends Error {
29379
- constructor(code) {
30382
+ constructor(code, detail) {
29380
30383
  super(code);
29381
30384
  this.code = code;
30385
+ this.detail = detail;
29382
30386
  this.name = "ScreenCaptureError";
29383
30387
  }
29384
30388
  code;
30389
+ detail;
29385
30390
  };
29386
30391
  var KNOWN = /^(SCREEN_UNAVAILABLE|SCREEN_LOCKED|SCREEN_ENCODER_UNAVAILABLE|SCREENSHOT_TOO_LARGE|ARGUMENT_INVALID)$/;
29387
30392
  function jpegSize(data) {
@@ -29397,12 +30402,12 @@ function jpegSize(data) {
29397
30402
  }
29398
30403
  return null;
29399
30404
  }
29400
- function run(file2, args, signal, maxBuffer = 65536) {
30405
+ function run(file2, args, signal, maxBuffer = 65536, env = buildChildEnvironment(process.env, process.platform)) {
29401
30406
  return new Promise((resolve, reject) => {
29402
30407
  execFile4(
29403
30408
  file2,
29404
30409
  args,
29405
- { encoding: "buffer", timeout: 15e3, maxBuffer, windowsHide: true, shell: false, env: buildChildEnvironment(process.env, process.platform), signal },
30410
+ { encoding: "buffer", timeout: 15e3, maxBuffer, windowsHide: true, shell: false, env, signal },
29406
30411
  (error62, stdout, stderr) => error62 ? reject(Object.assign(error62, { stdout, stderr })) : resolve({ stdout, stderr })
29407
30412
  );
29408
30413
  });
@@ -29467,11 +30472,141 @@ async function mac3(signal) {
29467
30472
  });
29468
30473
  }
29469
30474
  }
30475
+ var SESSION_KEYS = ["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "XDG_SESSION_TYPE", "XDG_CURRENT_DESKTOP"];
30476
+ var SESSION_VALUE = /^[A-Za-z0-9_.:,;=@+/-]{1,256}$/;
30477
+ var LINUX_SOURCE_BYTES = 150994944;
30478
+ async function linuxTool(name2) {
30479
+ for (const directory of ["/usr/bin", "/bin", "/usr/local/bin"]) {
30480
+ const file2 = path17.posix.join(directory, name2);
30481
+ try {
30482
+ await access3(file2, constants7.X_OK);
30483
+ return file2;
30484
+ } catch {
30485
+ }
30486
+ }
30487
+ return null;
30488
+ }
30489
+ async function linuxSession(signal) {
30490
+ const session = {}, uid = process.getuid?.();
30491
+ const take = (key, value) => {
30492
+ if (value && !session[key] && SESSION_VALUE.test(value)) session[key] = value;
30493
+ };
30494
+ const base = buildChildEnvironment(process.env, "linux");
30495
+ for (const key of SESSION_KEYS) take(key, process.env[key]);
30496
+ if (!session.DISPLAY && !session.WAYLAND_DISPLAY) {
30497
+ const systemctl = await linuxTool("systemctl");
30498
+ if (systemctl) try {
30499
+ const { stdout } = await run(systemctl, ["--user", "show-environment"], signal, 262144, base);
30500
+ for (const line of stdout.toString("utf8").split("\n")) {
30501
+ const at = line.indexOf("=");
30502
+ if (at > 0 && SESSION_KEYS.includes(line.slice(0, at))) take(line.slice(0, at), line.slice(at + 1));
30503
+ }
30504
+ } catch {
30505
+ if (signal.aborted) throw new ScreenCaptureError("CANCELLED");
30506
+ }
30507
+ }
30508
+ if (uid !== void 0) take("XDG_RUNTIME_DIR", "/run/user/" + uid);
30509
+ if (!session.DISPLAY && !session.WAYLAND_DISPLAY) {
30510
+ if (session.XDG_RUNTIME_DIR) for (const name2 of ["wayland-0", "wayland-1"]) {
30511
+ const socket = await lstat7(path17.posix.join(session.XDG_RUNTIME_DIR, name2)).catch(() => null);
30512
+ if (socket?.isSocket() && socket.uid === uid) {
30513
+ session.WAYLAND_DISPLAY = name2;
30514
+ break;
30515
+ }
30516
+ }
30517
+ if (!session.WAYLAND_DISPLAY) {
30518
+ const servers = [];
30519
+ for (const name2 of await readdir4("/tmp/.X11-unix").catch(() => [])) {
30520
+ const n = /^X(\d{1,4})$/.exec(name2)?.[1], socket = n ? await lstat7("/tmp/.X11-unix/" + name2).catch(() => null) : null;
30521
+ if (n && socket?.isSocket()) servers.push({ n: Number(n), own: socket.uid === uid });
30522
+ }
30523
+ const server = servers.sort((a, b) => Number(b.own) - Number(a.own) || a.n - b.n)[0];
30524
+ if (server) session.DISPLAY = ":" + server.n;
30525
+ }
30526
+ }
30527
+ if (session.DISPLAY && !session.XAUTHORITY) {
30528
+ const file2 = path17.posix.join(os4.homedir(), ".Xauthority");
30529
+ if ((await lstat7(file2).catch(() => null))?.isFile()) take("XAUTHORITY", file2);
30530
+ }
30531
+ if (session.XDG_RUNTIME_DIR) take("DBUS_SESSION_BUS_ADDRESS", "unix:path=" + session.XDG_RUNTIME_DIR + "/bus");
30532
+ const wayland = !!session.WAYLAND_DISPLAY || session.XDG_SESSION_TYPE === "wayland";
30533
+ return { env: { ...base, ...session }, wayland, x11: !wayland && !!session.DISPLAY };
30534
+ }
30535
+ async function busSocket(env) {
30536
+ const socket = sessionBusSocket(env.DBUS_SESSION_BUS_ADDRESS);
30537
+ if (!socket || socket.startsWith("\0")) return socket;
30538
+ return (await lstat7(socket).catch(() => null))?.isSocket() ? socket : null;
30539
+ }
30540
+ async function portalCapture(socket, signal) {
30541
+ const token = "lc" + randomBytes6(8).toString("hex"), started = Date.now(), uid = process.getuid?.();
30542
+ if (uid === void 0) throw new ScreenCaptureError("SCREEN_UNAVAILABLE");
30543
+ let answer;
30544
+ try {
30545
+ answer = await portalScreenshot(socket, uid, token, AbortSignal.any([signal, AbortSignal.timeout(3e4)]));
30546
+ } catch {
30547
+ throw new ScreenCaptureError(signal.aborted ? "CANCELLED" : "SCREEN_UNAVAILABLE");
30548
+ }
30549
+ const { code, uri } = answer;
30550
+ if (code === 1) throw new ScreenCaptureError("SCREEN_RECORDING_PERMISSION_REQUIRED");
30551
+ if (code !== 0 || !uri?.startsWith("file://")) throw new ScreenCaptureError("SCREEN_UNAVAILABLE");
30552
+ const file2 = decodeURIComponent(new URL(uri).pathname), info = await lstat7(file2);
30553
+ const fresh = info.isFile() && info.uid === uid && info.mtimeMs >= started - 5e3;
30554
+ try {
30555
+ if (!fresh || info.size > LINUX_SOURCE_BYTES) throw new ScreenCaptureError("SCREEN_UNAVAILABLE");
30556
+ return await readFile6(file2);
30557
+ } finally {
30558
+ if (fresh) await unlink2(file2).catch(() => {
30559
+ });
30560
+ }
30561
+ }
30562
+ async function linux(signal) {
30563
+ const session = await linuxSession(signal);
30564
+ if (!session.wayland && !session.x11) throw new ScreenCaptureError("SCREENSHOT_UNSUPPORTED", { reason: "NO_DISPLAY" });
30565
+ const output2 = (args) => async (tool) => (await run(tool, args, signal, LINUX_SOURCE_BYTES, session.env)).stdout;
30566
+ const portal = (socket) => portalCapture(socket, signal);
30567
+ const methods = session.wayland ? [["grim", "grim", output2(["-t", "png", "-"])], ["portal", "", portal]] : [
30568
+ ["xwd", "xwd", output2(["-root", "-silent"])],
30569
+ ["import", "import", output2(["-silent", "-window", "root", "png:-"])],
30570
+ ["maim", "maim", output2(["-f", "png"])],
30571
+ ["portal", "", portal]
30572
+ ];
30573
+ const tried = [];
30574
+ for (const [name2, program, capture2] of methods) {
30575
+ const tool = program ? await linuxTool(program) : await busSocket(session.env);
30576
+ if (!tool) {
30577
+ tried.push(name2 + ":missing");
30578
+ continue;
30579
+ }
30580
+ let image;
30581
+ try {
30582
+ const source = await capture2(tool);
30583
+ image = decodePng(source) ?? decodeXwd(source);
30584
+ } catch (error62) {
30585
+ if (signal.aborted) throw new ScreenCaptureError("CANCELLED");
30586
+ if (error62 instanceof ScreenCaptureError && error62.code === "SCREEN_RECORDING_PERMISSION_REQUIRED") throw error62;
30587
+ tried.push(name2 + ":failed");
30588
+ continue;
30589
+ }
30590
+ if (!image) {
30591
+ tried.push(name2 + ":unreadable");
30592
+ continue;
30593
+ }
30594
+ const fitted = fitJpeg(image, SCREENSHOT_MAX_EDGE, SCREENSHOT_MAX_JPEG_BYTES);
30595
+ if (!fitted) throw new ScreenCaptureError("SCREENSHOT_TOO_LARGE");
30596
+ return { ...fitted, sourceWidth: image.width, sourceHeight: image.height };
30597
+ }
30598
+ throw new ScreenCaptureError("SCREENSHOT_UNSUPPORTED", {
30599
+ reason: tried.every((entry) => entry.endsWith(":missing")) ? "NO_CAPTURE_TOOL" : "CAPTURE_FAILED",
30600
+ session: session.wayland ? "wayland" : "x11",
30601
+ tried
30602
+ });
30603
+ }
29470
30604
  async function captureScreen(options) {
29471
30605
  if (options.signal.aborted) throw new ScreenCaptureError("CANCELLED");
29472
30606
  if (process.platform === "win32") return windows(options.ownerBridgePath, options.signal);
29473
30607
  if (process.platform === "darwin") return mac3(options.signal);
29474
- throw new ScreenCaptureError("SCREENSHOT_UNSUPPORTED");
30608
+ if (process.platform === "linux") return linux(options.signal);
30609
+ throw new ScreenCaptureError("SCREENSHOT_UNSUPPORTED", { reason: "PLATFORM_UNSUPPORTED" });
29475
30610
  }
29476
30611
 
29477
30612
  // agent/src/tools.ts
@@ -29504,7 +30639,7 @@ function stopped(signal) {
29504
30639
  if (signal.aborted) fail3("CANCELLED");
29505
30640
  }
29506
30641
  async function readBoundedFile(file2, maxBytes, bridge, signal) {
29507
- const stat2 = await lstat7(file2);
30642
+ const stat2 = await lstat8(file2);
29508
30643
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > maxBytes) fail3("FILE_UNSUPPORTED_OR_TOO_LARGE");
29509
30644
  if (process.platform === "win32") {
29510
30645
  if (maxBytes <= 1048576 || stat2.size <= 1048576) return readWindowsFile(bridge, file2, Math.min(maxBytes, 1048576), signal);
@@ -29512,7 +30647,7 @@ async function readBoundedFile(file2, maxBytes, bridge, signal) {
29512
30647
  if (read.truncated) fail3("FILE_UNSUPPORTED_OR_TOO_LARGE");
29513
30648
  return read.data;
29514
30649
  }
29515
- const handle = await open6(file2, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0));
30650
+ const handle = await open6(file2, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
29516
30651
  try {
29517
30652
  const current2 = await handle.stat();
29518
30653
  if (!current2.isFile() || current2.size > maxBytes) fail3("FILE_UNSUPPORTED_OR_TOO_LARGE");
@@ -29767,7 +30902,7 @@ var NativeTools = class {
29767
30902
  }
29768
30903
  if (bytes3.length > MAX_FILE_WRITE_BYTES) fail3("FILE_WRITE_LIMIT");
29769
30904
  const temp = path18.join(path18.dirname(target), ".lc-write-" + randomUUID7() + ".tmp");
29770
- const handle = await open6(temp, constants7.O_CREAT | constants7.O_EXCL | constants7.O_WRONLY, 384);
30905
+ const handle = await open6(temp, constants8.O_CREAT | constants8.O_EXCL | constants8.O_WRONLY, 384);
29771
30906
  try {
29772
30907
  await handle.writeFile(bytes3);
29773
30908
  await handle.sync();
@@ -29783,7 +30918,7 @@ var NativeTools = class {
29783
30918
  break;
29784
30919
  } catch (error62) {
29785
30920
  if (process.platform !== "win32" || !["EPERM", "EBUSY", "EACCES"].includes(error62.code ?? "")) throw error62;
29786
- if (attempt === 4) fail3((await lstat7(target)).mode & 128 ? "FILE_IN_USE" : "FILE_READ_ONLY");
30921
+ if (attempt === 4) fail3((await lstat8(target)).mode & 128 ? "FILE_IN_USE" : "FILE_READ_ONLY");
29787
30922
  await delay2(50 << attempt);
29788
30923
  stopped(signal);
29789
30924
  }
@@ -29899,14 +31034,26 @@ var NativeTools = class {
29899
31034
  } };
29900
31035
  }
29901
31036
  if (call.name === "take_screenshot") {
29902
- if (!screenshotEnabled() && !await lstat7(path18.join(this.options.stateDirectory, SCREENSHOT_ACCEPTANCE_FILE)).then((s) => s.isFile(), () => false)) fail3("SCREENSHOT_DISABLED");
31037
+ if (!screenshotEnabled() && !await lstat8(path18.join(this.options.stateDirectory, SCREENSHOT_ACCEPTANCE_FILE)).then((s) => s.isFile(), () => false)) fail3("SCREENSHOT_DISABLED");
29903
31038
  if (!workspace2.fullAccess) fail3("FULL_ACCESS_REQUIRED");
31039
+ if (await lstat8(path18.join(this.options.stateDirectory, SCREENSHOT_OWNER_OFF_FILE)).then(() => true, (error62) => error62.code !== "ENOENT")) fail3("SCREENSHOT_DISABLED_BY_OWNER");
29904
31040
  const bridge = this.options.ownerBridgePath ?? path18.join(path18.dirname(this.options.helperPath), "OwnerBridge.exe");
29905
31041
  return { call, claims: [{ path: path18.join(this.options.stateDirectory, "screen-capture"), mode: "read" }], run: async (signal) => {
29906
31042
  let shot;
29907
31043
  try {
29908
31044
  shot = await captureScreen({ ownerBridgePath: bridge, signal });
29909
31045
  } catch (error62) {
31046
+ if (error62 instanceof ScreenCaptureError && error62.detail) return {
31047
+ exitCode: 1,
31048
+ timedOut: false,
31049
+ cancelled: false,
31050
+ treeTerminated: true,
31051
+ stdout: JSON.stringify({ type: "screenshot_error", resultCode: error62.code, ...error62.detail }),
31052
+ stderr: "",
31053
+ stdoutTruncated: false,
31054
+ stderrTruncated: false,
31055
+ resultCode: error62.code
31056
+ };
29910
31057
  fail3(error62 instanceof Error && /^[A-Z_]{1,40}$/.test(error62.message) ? error62.message : "SCREEN_UNAVAILABLE");
29911
31058
  }
29912
31059
  return result({
@@ -30070,7 +31217,7 @@ var NativeTools = class {
30070
31217
  )?.file : void 0);
30071
31218
  if (!candidate || !path18.isAbsolute(candidate)) fail3("COMMAND_NOT_FOUND");
30072
31219
  const executable = await realpath7(candidate).catch(() => fail3("COMMAND_NOT_FOUND"));
30073
- if (!(await lstat7(executable)).isFile()) fail3("COMMAND_NOT_FOUND");
31220
+ if (!(await lstat8(executable)).isFile()) fail3("COMMAND_NOT_FOUND");
30074
31221
  if (denied.has(commandKey(executable))) fail3("COMMAND_NOT_ALLOWED");
30075
31222
  for (const key of workspace2.deniedCommands ?? []) {
30076
31223
  const configured = this.options.programs[key]?.executable;
@@ -30112,7 +31259,7 @@ var NativeTools = class {
30112
31259
  const candidate = process.platform === "win32" ? source : await resolvePosixExecutable(source);
30113
31260
  if (!candidate) continue;
30114
31261
  try {
30115
- const stat2 = await lstat7(candidate);
31262
+ const stat2 = await lstat8(candidate);
30116
31263
  if (!stat2.isFile() || stat2.isSymbolicLink() || !equalPath3(candidate, await realpath7(candidate))) continue;
30117
31264
  } catch {
30118
31265
  continue;
@@ -30130,7 +31277,7 @@ var NativeTools = class {
30130
31277
  const current2 = queue.shift();
30131
31278
  let names;
30132
31279
  try {
30133
- names = await readdir4(current2.path, { withFileTypes: true });
31280
+ names = await readdir5(current2.path, { withFileTypes: true });
30134
31281
  } catch (error62) {
30135
31282
  if (current2.level === 0) throw error62;
30136
31283
  continue;
@@ -30155,7 +31302,7 @@ var NativeTools = class {
30155
31302
  entries.push({ path: path18.relative(root, resolved), type: "directory" });
30156
31303
  if (current2.level < depth) queue.push({ path: resolved, level: current2.level + 1 });
30157
31304
  } else if (item.isFile()) {
30158
- const stat2 = await lstat7(resolved).catch(() => null);
31305
+ const stat2 = await lstat8(resolved).catch(() => null);
30159
31306
  if (stat2) entries.push({ path: path18.relative(root, resolved), type: "file", size: stat2.size });
30160
31307
  }
30161
31308
  }
@@ -30168,7 +31315,7 @@ var NativeTools = class {
30168
31315
  while (guard.isWithin(directory, workspace2.root)) {
30169
31316
  const dotGit = path18.join(directory, ".git");
30170
31317
  try {
30171
- const stat2 = await lstat7(dotGit);
31318
+ const stat2 = await lstat8(dotGit);
30172
31319
  if (stat2.isSymbolicLink()) fail3("GIT_METADATA_CHANGED");
30173
31320
  let gitDir;
30174
31321
  if (stat2.isDirectory()) gitDir = await realpath7(dotGit);
@@ -30186,7 +31333,7 @@ var NativeTools = class {
30186
31333
  } catch (e) {
30187
31334
  if (e.code !== "ENOENT") throw e;
30188
31335
  }
30189
- if (!(await lstat7(common)).isDirectory() || guard.isWithin(common, this.options.stateDirectory)) fail3("GIT_METADATA_CHANGED");
31336
+ if (!(await lstat8(common)).isDirectory() || guard.isWithin(common, this.options.stateDirectory)) fail3("GIT_METADATA_CHANGED");
30190
31337
  if (!guard.isWithin(common, workspace2.root) && (!workspace2.gitCommonDir || !equalPath3(common, workspace2.gitCommonDir))) fail3("GIT_COMMON_DIRECTORY_NOT_APPROVED");
30191
31338
  return common;
30192
31339
  } catch (e) {
@@ -30942,7 +32089,45 @@ function journalBinding(entry, binding2) {
30942
32089
  function journalResult(value, code) {
30943
32090
  return { ...value, resultCode: code ?? (value.treeTerminated ? value.cancelled ? "CANCELLED" : value.timedOut ? "TIMEOUT" : value.exitCode === 0 ? "SUCCESS" : "USER_PROGRAM_FAILED" : "EXECUTION_UNKNOWN") };
30944
32091
  }
30945
- var knownCodes = /* @__PURE__ */ new Set(["PROJECT_IDENTITY_UNKNOWN", "PROJECT_IDENTITY_MISMATCH", "INVALID_TOOL_ARGUMENTS", "LOCAL_PERMISSION_REQUIRED", "PATH_NOT_ALLOWED", "FILE_CHANGED", "FILE_NOT_FOUND", "FILE_ALREADY_EXISTS", "REPLACEMENT_NOT_UNIQUE", "OUTPUT_LIMIT_EXCEEDED", "BINARY_FILE_NOT_SUPPORTED", "FILE_UNSUPPORTED_OR_TOO_LARGE", "INVALID_LINE_RANGE", "FILE_IN_USE", "FILE_READ_ONLY", "FILE_WRITE_LIMIT", "GIT_METADATA_CHANGED", "GIT_COMMON_DIRECTORY_NOT_APPROVED", "GIT_NOT_INSTALLED", "LOCALHOST_NOT_ALLOWED", "COMMAND_NOT_ALLOWED", "WORKSPACE_CHANGED", "WORKSPACE_UNAVAILABLE", "RESOURCE_BUSY", "AGENT_PAUSED", "CANCELLED_BEFORE_ACCEPTANCE", "ADMISSION_DEADLINE_EXPIRED"]);
32092
+ var knownCodes = /* @__PURE__ */ new Set([
32093
+ "PROJECT_IDENTITY_UNKNOWN",
32094
+ "PROJECT_IDENTITY_MISMATCH",
32095
+ "INVALID_TOOL_ARGUMENTS",
32096
+ "LOCAL_PERMISSION_REQUIRED",
32097
+ "PATH_NOT_ALLOWED",
32098
+ "FILE_CHANGED",
32099
+ "FILE_NOT_FOUND",
32100
+ "FILE_ALREADY_EXISTS",
32101
+ "REPLACEMENT_NOT_UNIQUE",
32102
+ "OUTPUT_LIMIT_EXCEEDED",
32103
+ "BINARY_FILE_NOT_SUPPORTED",
32104
+ "FILE_UNSUPPORTED_OR_TOO_LARGE",
32105
+ "INVALID_LINE_RANGE",
32106
+ "FILE_IN_USE",
32107
+ "FILE_READ_ONLY",
32108
+ "FILE_WRITE_LIMIT",
32109
+ "GIT_METADATA_CHANGED",
32110
+ "GIT_COMMON_DIRECTORY_NOT_APPROVED",
32111
+ "GIT_NOT_INSTALLED",
32112
+ "LOCALHOST_NOT_ALLOWED",
32113
+ "COMMAND_NOT_ALLOWED",
32114
+ "WORKSPACE_CHANGED",
32115
+ "WORKSPACE_UNAVAILABLE",
32116
+ "RESOURCE_BUSY",
32117
+ "AGENT_PAUSED",
32118
+ "CANCELLED_BEFORE_ACCEPTANCE",
32119
+ "ADMISSION_DEADLINE_EXPIRED",
32120
+ // take_screenshot refusals (#434, #486): without these the client sees TOOL_FAILED.
32121
+ "FULL_ACCESS_REQUIRED",
32122
+ "SCREENSHOT_DISABLED",
32123
+ "SCREENSHOT_DISABLED_BY_OWNER",
32124
+ "SCREENSHOT_UNSUPPORTED",
32125
+ "SCREENSHOT_TOO_LARGE",
32126
+ "SCREEN_UNAVAILABLE",
32127
+ "SCREEN_LOCKED",
32128
+ "SCREEN_ENCODER_UNAVAILABLE",
32129
+ "SCREEN_RECORDING_PERMISSION_REQUIRED"
32130
+ ]);
30946
32131
  function safeCode(error62) {
30947
32132
  const code = error62 instanceof NativeToolError ? error62.code : error62 instanceof Error ? error62.message : "";
30948
32133
  return knownCodes.has(code) || /^GUARD_[A-Z_]{1,30}$/.test(code) ? code : "TOOL_FAILED";
@@ -31375,9 +32560,9 @@ var NativeRelayBridge = class {
31375
32560
  };
31376
32561
 
31377
32562
  // agent/src/local-direct.ts
31378
- import net from "node:net";
32563
+ import net2 from "node:net";
31379
32564
  import path20 from "node:path";
31380
- import { createHmac as createHmac2, hkdfSync, randomBytes as randomBytes6, randomUUID as randomUUID8, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
32565
+ import { createHmac as createHmac2, hkdfSync, randomBytes as randomBytes7, randomUUID as randomUUID8, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
31381
32566
  import { mkdir as mkdir7, readFile as readFile8, rename as rename5, rm as rm7, writeFile as writeFile3 } from "node:fs/promises";
31382
32567
  var LocalDirectError = class extends Error {
31383
32568
  constructor(code) {
@@ -31414,7 +32599,7 @@ function sameProof(candidate, expected) {
31414
32599
  const a = Buffer.from(candidate), b = Buffer.from(expected);
31415
32600
  return a.length === b.length && timingSafeEqual3(a, b);
31416
32601
  }
31417
- var nonce = () => randomBytes6(32).toString("base64url");
32602
+ var nonce = () => randomBytes7(32).toString("base64url");
31418
32603
  var NONCE = /^[A-Za-z0-9_-]{43}$/;
31419
32604
  function codeOf(error62) {
31420
32605
  const code = error62 instanceof NativeToolError || error62 instanceof LocalDirectError ? error62.code : error62 instanceof Error ? error62.message : "";
@@ -31496,7 +32681,7 @@ var LocalDirectServer = class _LocalDirectServer {
31496
32681
  });
31497
32682
  return null;
31498
32683
  }
31499
- const server = net.createServer(), self = new _LocalDirectServer(server, options);
32684
+ const server = net2.createServer(), self = new _LocalDirectServer(server, options);
31500
32685
  server.on("connection", (socket) => self.accept(socket));
31501
32686
  await new Promise((resolve, reject) => {
31502
32687
  server.once("error", reject);
@@ -31653,7 +32838,7 @@ var LocalDirectClient = class _LocalDirectClient {
31653
32838
  static async connect(options) {
31654
32839
  if (!await localDirectEnabled(options.directory)) fail4("LOCAL_ACCESS_DISABLED");
31655
32840
  const endpoint2 = await readEndpoint(options.directory);
31656
- const socket = net.createConnection({ host: "127.0.0.1", port: endpoint2.port });
32841
+ const socket = net2.createConnection({ host: "127.0.0.1", port: endpoint2.port });
31657
32842
  let handler = () => {
31658
32843
  };
31659
32844
  const lines = new Lines(socket, (frame) => handler(frame));
@@ -37176,8 +38361,8 @@ var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => {
37176
38361
  var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
37177
38362
  var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
37178
38363
  var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
37179
- exports.parse = parse3;
37180
- function parse3(string4) {
38364
+ exports.parse = parse4;
38365
+ function parse4(string4) {
37181
38366
  if (!string4) throw new TypeError("argument string is required");
37182
38367
  var header = typeof string4 === "object" ? getcontenttype(string4) : string4;
37183
38368
  if (typeof header !== "string") throw new TypeError("argument string is required to be a string");
@@ -37701,9 +38886,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37701
38886
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
37702
38887
  return `${varKind} ${this.name}${rhs};` + _n;
37703
38888
  }
37704
- optimizeNames(names, constants10) {
38889
+ optimizeNames(names, constants11) {
37705
38890
  if (!names[this.name.str]) return;
37706
- if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants10);
38891
+ if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants11);
37707
38892
  return this;
37708
38893
  }
37709
38894
  get names() {
@@ -37720,9 +38905,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37720
38905
  render({ _n }) {
37721
38906
  return `${this.lhs} = ${this.rhs};` + _n;
37722
38907
  }
37723
- optimizeNames(names, constants10) {
38908
+ optimizeNames(names, constants11) {
37724
38909
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return;
37725
- this.rhs = optimizeExpr(this.rhs, names, constants10);
38910
+ this.rhs = optimizeExpr(this.rhs, names, constants11);
37726
38911
  return this;
37727
38912
  }
37728
38913
  get names() {
@@ -37781,8 +38966,8 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37781
38966
  optimizeNodes() {
37782
38967
  return `${this.code}` ? this : void 0;
37783
38968
  }
37784
- optimizeNames(names, constants10) {
37785
- this.code = optimizeExpr(this.code, names, constants10);
38969
+ optimizeNames(names, constants11) {
38970
+ this.code = optimizeExpr(this.code, names, constants11);
37786
38971
  return this;
37787
38972
  }
37788
38973
  get names() {
@@ -37808,12 +38993,12 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37808
38993
  }
37809
38994
  return nodes.length > 0 ? this : void 0;
37810
38995
  }
37811
- optimizeNames(names, constants10) {
38996
+ optimizeNames(names, constants11) {
37812
38997
  const { nodes } = this;
37813
38998
  let i = nodes.length;
37814
38999
  while (i--) {
37815
39000
  const n = nodes[i];
37816
- if (n.optimizeNames(names, constants10)) continue;
39001
+ if (n.optimizeNames(names, constants11)) continue;
37817
39002
  subtractNames(names, n.names);
37818
39003
  nodes.splice(i, 1);
37819
39004
  }
@@ -37860,11 +39045,11 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37860
39045
  if (cond === false || !this.nodes.length) return void 0;
37861
39046
  return this;
37862
39047
  }
37863
- optimizeNames(names, constants10) {
39048
+ optimizeNames(names, constants11) {
37864
39049
  var _a3;
37865
- this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants10);
37866
- if (!(super.optimizeNames(names, constants10) || this.else)) return;
37867
- this.condition = optimizeExpr(this.condition, names, constants10);
39050
+ this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants11);
39051
+ if (!(super.optimizeNames(names, constants11) || this.else)) return;
39052
+ this.condition = optimizeExpr(this.condition, names, constants11);
37868
39053
  return this;
37869
39054
  }
37870
39055
  get names() {
@@ -37886,9 +39071,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37886
39071
  render(opts) {
37887
39072
  return `for(${this.iteration})` + super.render(opts);
37888
39073
  }
37889
- optimizeNames(names, constants10) {
37890
- if (!super.optimizeNames(names, constants10)) return;
37891
- this.iteration = optimizeExpr(this.iteration, names, constants10);
39074
+ optimizeNames(names, constants11) {
39075
+ if (!super.optimizeNames(names, constants11)) return;
39076
+ this.iteration = optimizeExpr(this.iteration, names, constants11);
37892
39077
  return this;
37893
39078
  }
37894
39079
  get names() {
@@ -37923,9 +39108,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37923
39108
  render(opts) {
37924
39109
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
37925
39110
  }
37926
- optimizeNames(names, constants10) {
37927
- if (!super.optimizeNames(names, constants10)) return;
37928
- this.iterable = optimizeExpr(this.iterable, names, constants10);
39111
+ optimizeNames(names, constants11) {
39112
+ if (!super.optimizeNames(names, constants11)) return;
39113
+ this.iterable = optimizeExpr(this.iterable, names, constants11);
37929
39114
  return this;
37930
39115
  }
37931
39116
  get names() {
@@ -37964,11 +39149,11 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37964
39149
  (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes();
37965
39150
  return this;
37966
39151
  }
37967
- optimizeNames(names, constants10) {
39152
+ optimizeNames(names, constants11) {
37968
39153
  var _a3, _b;
37969
- super.optimizeNames(names, constants10);
37970
- (_a3 = this.catch) === null || _a3 === void 0 || _a3.optimizeNames(names, constants10);
37971
- (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants10);
39154
+ super.optimizeNames(names, constants11);
39155
+ (_a3 = this.catch) === null || _a3 === void 0 || _a3.optimizeNames(names, constants11);
39156
+ (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants11);
37972
39157
  return this;
37973
39158
  }
37974
39159
  get names() {
@@ -38217,7 +39402,7 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
38217
39402
  function addExprNames(names, from) {
38218
39403
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
38219
39404
  }
38220
- function optimizeExpr(expr, names, constants10) {
39405
+ function optimizeExpr(expr, names, constants11) {
38221
39406
  if (expr instanceof code_1.Name) return replaceName(expr);
38222
39407
  if (!canOptimize(expr)) return expr;
38223
39408
  return new code_1._Code(expr._items.reduce((items, c) => {
@@ -38227,13 +39412,13 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
38227
39412
  return items;
38228
39413
  }, []));
38229
39414
  function replaceName(n) {
38230
- const c = constants10[n.str];
39415
+ const c = constants11[n.str];
38231
39416
  if (c === void 0 || names[n.str] !== 1) return n;
38232
39417
  delete names[n.str];
38233
39418
  return c;
38234
39419
  }
38235
39420
  function canOptimize(e) {
38236
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants10[c.str] !== void 0);
39421
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants11[c.str] !== void 0);
38237
39422
  }
38238
39423
  }
38239
39424
  function subtractNames(names, from) {
@@ -40365,21 +41550,21 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
40365
41550
  const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils();
40366
41551
  const { SCHEMES, getSchemeHandler } = require_schemes();
40367
41552
  function normalize(uri, options) {
40368
- if (typeof uri === "string") uri = serialize(parse3(uri, options), options);
40369
- else if (typeof uri === "object") uri = parse3(serialize(uri, options), options);
41553
+ if (typeof uri === "string") uri = serialize(parse4(uri, options), options);
41554
+ else if (typeof uri === "object") uri = parse4(serialize(uri, options), options);
40370
41555
  return uri;
40371
41556
  }
40372
41557
  function resolve(baseURI, relativeURI, options) {
40373
41558
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
40374
- const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true);
41559
+ const resolved = resolveComponent(parse4(baseURI, schemelessOptions), parse4(relativeURI, schemelessOptions), schemelessOptions, true);
40375
41560
  schemelessOptions.skipEscape = true;
40376
41561
  return serialize(resolved, schemelessOptions);
40377
41562
  }
40378
41563
  function resolveComponent(base, relative, options, skipNormalization) {
40379
41564
  const target = {};
40380
41565
  if (!skipNormalization) {
40381
- base = parse3(serialize(base, options), options);
40382
- relative = parse3(serialize(relative, options), options);
41566
+ base = parse4(serialize(base, options), options);
41567
+ relative = parse4(serialize(relative, options), options);
40383
41568
  }
40384
41569
  options = options || {};
40385
41570
  if (!options.tolerant && relative.scheme) {
@@ -40423,7 +41608,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
40423
41608
  function equal(uriA, uriB, options) {
40424
41609
  if (typeof uriA === "string") {
40425
41610
  uriA = unescape(uriA);
40426
- uriA = serialize(normalizeComponentEncoding(parse3(uriA, options), true), {
41611
+ uriA = serialize(normalizeComponentEncoding(parse4(uriA, options), true), {
40427
41612
  ...options,
40428
41613
  skipEscape: true
40429
41614
  });
@@ -40433,7 +41618,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
40433
41618
  });
40434
41619
  if (typeof uriB === "string") {
40435
41620
  uriB = unescape(uriB);
40436
- uriB = serialize(normalizeComponentEncoding(parse3(uriB, options), true), {
41621
+ uriB = serialize(normalizeComponentEncoding(parse4(uriB, options), true), {
40437
41622
  ...options,
40438
41623
  skipEscape: true
40439
41624
  });
@@ -40486,7 +41671,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
40486
41671
  return uriTokens.join("");
40487
41672
  }
40488
41673
  const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
40489
- function parse3(uri, opts) {
41674
+ function parse4(uri, opts) {
40490
41675
  const options = Object.assign({}, opts);
40491
41676
  const parsed = {
40492
41677
  scheme: void 0,
@@ -40547,7 +41732,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
40547
41732
  resolveComponent,
40548
41733
  equal,
40549
41734
  serialize,
40550
- parse: parse3
41735
+ parse: parse4
40551
41736
  };
40552
41737
  module.exports = fastUri;
40553
41738
  module.exports.default = fastUri;
@@ -45827,7 +47012,7 @@ var DESCRIPTIONS = {
45827
47012
  git_log: ["Recent Git commits of the repository at a workspace-relative path.", { readOnlyHint: true, openWorldHint: false }],
45828
47013
  project_snapshot: ["Compact project overview: Git state and, with startup, AGENTS.md policy and task continuation.", { readOnlyHint: true, openWorldHint: false }],
45829
47014
  command_run: ["Run one executable with an argument array (no shell parsing), hidden, with captured output. Uses this user account's rights within the owner's grant.", { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }],
45830
- take_screenshot: ["Take a still image of this computer's primary screen, returned as a JPEG image. Needs a Full Access workspace; the lock screen is never captured.", { readOnlyHint: true, openWorldHint: false }],
47015
+ take_screenshot: ["Take a still image of this computer's primary screen, returned as a JPEG image. It contains everything visible on the screen, including any open passwords, keys or private messages. Needs a Full Access workspace; the lock screen is never captured.", { readOnlyHint: true, openWorldHint: false }],
45831
47016
  localhost_request: ["HTTP request to a service on this computer (localhost only).", { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }]
45832
47017
  };
45833
47018
  var workspace = external_exports.string().min(1).max(4096).optional().describe("Workspace grant id, root path (for example D:\\) or display name from workspace_list. Optional when only one workspace is approved.");
@@ -46349,6 +47534,7 @@ async function connectOnce(options) {
46349
47534
  const incidents = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes("incidentBatchV1");
46350
47535
  const monitorHeartbeat = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes("monitorHeartbeatV1") && typeof readyFrame.heartbeatMs === "number" && Number.isInteger(readyFrame.heartbeatMs) && readyFrame.heartbeatMs >= 1e3 && readyFrame.heartbeatMs <= 6e4 ? readyFrame.heartbeatMs : void 0;
46351
47536
  const nativeStatus = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(NATIVE_STATUS_CAPABILITY) && options.status;
47537
+ const accessModes = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(WORKSPACE_ACCESS_MODE_CAPABILITY);
46352
47538
  const reportStatus = () => {
46353
47539
  if (!nativeStatus) return;
46354
47540
  const { safeSlots, active, queued, paused } = nativeStatus();
@@ -46575,7 +47761,16 @@ async function connectOnce(options) {
46575
47761
  registerWorkspace: (workspace2) => {
46576
47762
  if (pendingWorkspace.size >= 32) return Promise.reject(new RelayClientError("RELAY_PENDING_LIMIT"));
46577
47763
  const requestId = randomUUID10();
46578
- const event = { type: "workspace_grant", version: 1, requestId, workspaceGrantId: workspace2.workspaceGrantId, rootHash: workspace2.rootHash, displayName: workspace2.displayName, policyVersion: workspace2.policyVersion };
47764
+ const event = {
47765
+ type: "workspace_grant",
47766
+ version: 1,
47767
+ requestId,
47768
+ workspaceGrantId: workspace2.workspaceGrantId,
47769
+ rootHash: workspace2.rootHash,
47770
+ displayName: workspace2.displayName,
47771
+ policyVersion: workspace2.policyVersion,
47772
+ ...accessModes ? { accessMode: workspace2.fullAccess === true ? "full" : "scoped" } : {}
47773
+ };
46579
47774
  return new Promise((resolve, reject) => {
46580
47775
  const timer = setTimeout(() => {
46581
47776
  pendingWorkspace.delete(requestId);
@@ -46624,14 +47819,14 @@ import { spawn as spawn5 } from "node:child_process";
46624
47819
  import { createHash as createHash16 } from "node:crypto";
46625
47820
  import os6 from "node:os";
46626
47821
  import { open as open7 } from "node:fs/promises";
46627
- import { constants as constants8 } from "node:fs";
47822
+ import { constants as constants9 } from "node:fs";
46628
47823
  import path21 from "node:path";
46629
47824
  var MACHINE_GUID = /^\s*MachineGuid\s+REG_SZ\s+([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\s*$/m;
46630
47825
  async function readMachineGuid(timeoutMs2 = 5e3) {
46631
47826
  if (process.platform === "linux") {
46632
47827
  let handle;
46633
47828
  try {
46634
- handle = await open7("/etc/machine-id", constants8.O_RDONLY | constants8.O_NOFOLLOW);
47829
+ handle = await open7("/etc/machine-id", constants9.O_RDONLY | constants9.O_NOFOLLOW);
46635
47830
  const stat2 = await handle.stat();
46636
47831
  if (!stat2.isFile() || stat2.size > 128) return null;
46637
47832
  const data = Buffer.alloc(129);
@@ -46680,7 +47875,7 @@ async function readComputerName(timeoutMs2 = 5e3) {
46680
47875
  if (process.platform === "linux") {
46681
47876
  let handle;
46682
47877
  try {
46683
- handle = await open7("/etc/hostname", constants8.O_RDONLY | constants8.O_NOFOLLOW);
47878
+ handle = await open7("/etc/hostname", constants9.O_RDONLY | constants9.O_NOFOLLOW);
46684
47879
  const data = Buffer.alloc(257), { bytesRead } = await handle.read(data, 0, data.length, 0);
46685
47880
  const name2 = data.subarray(0, bytesRead).toString("utf8").trim();
46686
47881
  if (bytesRead <= 256 && valid(name2)) return name2;
@@ -47263,8 +48458,8 @@ async function deliverGuardEvidence(target, packet, options = {}) {
47263
48458
  }
47264
48459
 
47265
48460
  // agent/src/optimization-ledger.ts
47266
- import { constants as constants9 } from "node:fs";
47267
- import { lstat as lstat8, mkdir as mkdir8, open as open8, readFile as readFile9, realpath as realpath8 } from "node:fs/promises";
48461
+ import { constants as constants10 } from "node:fs";
48462
+ import { lstat as lstat9, mkdir as mkdir8, open as open8, readFile as readFile9, realpath as realpath8 } from "node:fs/promises";
47268
48463
  import path22 from "node:path";
47269
48464
  var MAX_LEDGER_BYTES = 64 * 1024 * 1024;
47270
48465
  var MAX_NOTICE_LEDGER_BYTES = 8 * 1024 * 1024;
@@ -47276,7 +48471,7 @@ async function safeDirectory2(directory) {
47276
48471
  let current2 = absolute2;
47277
48472
  for (; ; ) {
47278
48473
  try {
47279
- if ((await lstat8(current2)).isSymbolicLink()) throw failure5("OPTIMIZATION_LEDGER_DIRECTORY_INVALID");
48474
+ if ((await lstat9(current2)).isSymbolicLink()) throw failure5("OPTIMIZATION_LEDGER_DIRECTORY_INVALID");
47280
48475
  } catch (error62) {
47281
48476
  if (error62.code !== "ENOENT") throw error62;
47282
48477
  }
@@ -47285,7 +48480,7 @@ async function safeDirectory2(directory) {
47285
48480
  current2 = parent;
47286
48481
  }
47287
48482
  await mkdir8(absolute2, { recursive: true, mode: 448 });
47288
- const stat2 = await lstat8(absolute2);
48483
+ const stat2 = await lstat9(absolute2);
47289
48484
  if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw failure5("OPTIMIZATION_LEDGER_DIRECTORY_INVALID");
47290
48485
  return realpath8(absolute2);
47291
48486
  }
@@ -47319,7 +48514,7 @@ var OptimizationLedger = class _OptimizationLedger {
47319
48514
  const noticesFilename = path22.join(dir, "live-efficiency-notices.v1.jsonl");
47320
48515
  let existing = "";
47321
48516
  try {
47322
- const stat2 = await lstat8(filename);
48517
+ const stat2 = await lstat9(filename);
47323
48518
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > MAX_LEDGER_BYTES) {
47324
48519
  throw failure5("OPTIMIZATION_LEDGER_INVALID");
47325
48520
  }
@@ -47329,13 +48524,13 @@ var OptimizationLedger = class _OptimizationLedger {
47329
48524
  }
47330
48525
  const handle = await open8(
47331
48526
  filename,
47332
- constants9.O_CREAT | constants9.O_APPEND | constants9.O_WRONLY | (constants9.O_NOFOLLOW ?? 0),
48527
+ constants10.O_CREAT | constants10.O_APPEND | constants10.O_WRONLY | (constants10.O_NOFOLLOW ?? 0),
47333
48528
  384
47334
48529
  );
47335
48530
  const ledger = new _OptimizationLedger(filename, handle, noticesFilename);
47336
48531
  try {
47337
48532
  try {
47338
- const noticeStat = await lstat8(noticesFilename);
48533
+ const noticeStat = await lstat9(noticesFilename);
47339
48534
  if (!noticeStat.isFile() || noticeStat.isSymbolicLink() || noticeStat.size > MAX_NOTICE_LEDGER_BYTES) throw failure5("OPTIMIZATION_NOTICE_LEDGER_INVALID");
47340
48535
  const notices = await readFile9(noticesFilename, "utf8");
47341
48536
  for (const line of notices.split("\n")) {
@@ -47417,7 +48612,7 @@ var OptimizationLedger = class _OptimizationLedger {
47417
48612
  const marker = JSON.stringify({ sessionId: event.sessionId, checkpointCalls, deliveredAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n";
47418
48613
  let currentBytes = 0;
47419
48614
  try {
47420
- const stat2 = await lstat8(this.noticesFilename);
48615
+ const stat2 = await lstat9(this.noticesFilename);
47421
48616
  if (!stat2.isFile() || stat2.isSymbolicLink()) throw failure5("OPTIMIZATION_NOTICE_LEDGER_INVALID");
47422
48617
  currentBytes = stat2.size;
47423
48618
  } catch (error62) {
@@ -47426,7 +48621,7 @@ var OptimizationLedger = class _OptimizationLedger {
47426
48621
  if (currentBytes + Buffer.byteLength(marker, "utf8") > MAX_NOTICE_LEDGER_BYTES) throw failure5("OPTIMIZATION_NOTICE_LEDGER_CAPACITY_EXCEEDED");
47427
48622
  const markerHandle = await open8(
47428
48623
  this.noticesFilename,
47429
- constants9.O_CREAT | constants9.O_APPEND | constants9.O_WRONLY | (constants9.O_NOFOLLOW ?? 0),
48624
+ constants10.O_CREAT | constants10.O_APPEND | constants10.O_WRONLY | (constants10.O_NOFOLLOW ?? 0),
47430
48625
  384
47431
48626
  );
47432
48627
  try {
@@ -47465,7 +48660,7 @@ var OptimizationLedger = class _OptimizationLedger {
47465
48660
 
47466
48661
  // agent/src/monitor.ts
47467
48662
  import { createHash as createHash17, randomUUID as randomUUID12 } from "node:crypto";
47468
- import { lstat as lstat9, mkdir as mkdir9, open as open9, rename as rename6, rm as rm8 } from "node:fs/promises";
48663
+ import { lstat as lstat10, mkdir as mkdir9, open as open9, rename as rename6, rm as rm8 } from "node:fs/promises";
47469
48664
  import path23 from "node:path";
47470
48665
  import os7 from "node:os";
47471
48666
 
@@ -47732,7 +48927,7 @@ var ProductionMonitor = class {
47732
48927
  async write(file2, contents) {
47733
48928
  const directory = path23.dirname(file2);
47734
48929
  await mkdir9(directory, { recursive: true, mode: 448 });
47735
- const stat2 = await lstat9(directory);
48930
+ const stat2 = await lstat10(directory);
47736
48931
  if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw Error("MONITOR_DIRECTORY_INVALID");
47737
48932
  const temporary = file2 + "." + this.instanceId + ".tmp";
47738
48933
  const handle = await open9(temporary, "wx", 384);
@@ -48155,26 +49350,26 @@ var NativeFabricObserver = class {
48155
49350
  };
48156
49351
 
48157
49352
  // agent/src/native-fabric-startup.ts
48158
- import { lstat as lstat11, mkdir as mkdir12, open as open11, readFile as readFile10 } from "node:fs/promises";
49353
+ import { lstat as lstat12, mkdir as mkdir12, open as open11, readFile as readFile10 } from "node:fs/promises";
48159
49354
  import path26 from "node:path";
48160
49355
 
48161
49356
  // src/agent-fabric-service.ts
48162
- import { lstat as lstat10, mkdir as mkdir11, realpath as realpath9 } from "node:fs/promises";
49357
+ import { lstat as lstat11, mkdir as mkdir11, realpath as realpath9 } from "node:fs/promises";
48163
49358
  import { watch } from "node:fs";
48164
49359
  import path25 from "node:path";
48165
49360
 
48166
49361
  // src/agent-runtime-identity.ts
48167
- import { createHash as createHash19, randomBytes as randomBytes7, randomUUID as randomUUID14, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
49362
+ import { createHash as createHash19, randomBytes as randomBytes8, randomUUID as randomUUID14, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
48168
49363
 
48169
49364
  // src/agent-fabric-state.ts
48170
49365
  import { randomUUID as randomUUID13 } from "node:crypto";
48171
- import { mkdir as mkdir10, open as open10, rename as rename7, unlink as unlink2 } from "node:fs/promises";
49366
+ import { mkdir as mkdir10, open as open10, rename as rename7, unlink as unlink3 } from "node:fs/promises";
48172
49367
  import path24 from "node:path";
48173
49368
  var queues = /* @__PURE__ */ new Map();
48174
49369
  var FabricStateFile = class {
48175
- constructor(file2, maxBytes, parse3) {
49370
+ constructor(file2, maxBytes, parse4) {
48176
49371
  this.maxBytes = maxBytes;
48177
- this.parse = parse3;
49372
+ this.parse = parse4;
48178
49373
  this.file = path24.resolve(file2);
48179
49374
  }
48180
49375
  maxBytes;
@@ -48250,7 +49445,7 @@ var FabricStateFile = class {
48250
49445
  }
48251
49446
  await rename7(temporary, this.file);
48252
49447
  } finally {
48253
- await unlink2(temporary).catch((error62) => {
49448
+ await unlink3(temporary).catch((error62) => {
48254
49449
  if (error62.code !== "ENOENT") throw error62;
48255
49450
  });
48256
49451
  }
@@ -48264,7 +49459,7 @@ var FabricStateFile = class {
48264
49459
  } finally {
48265
49460
  await current2.close();
48266
49461
  }
48267
- await unlink2(lockPath);
49462
+ await unlink3(lockPath);
48268
49463
  }
48269
49464
  });
48270
49465
  }
@@ -48318,7 +49513,7 @@ var AgentRuntimeIdentityStore = class {
48318
49513
  return this.serial((state) => {
48319
49514
  if (state.bindings.length >= MAX_BINDINGS) throw Error("RUNTIME_IDENTITY_LIMIT");
48320
49515
  const runtimeId = "rt-" + randomUUID14();
48321
- const runtimeKey = randomBytes7(32).toString("base64url");
49516
+ const runtimeKey = randomBytes8(32).toString("base64url");
48322
49517
  const now = this.now();
48323
49518
  state.bindings.push({ runtimeId, keyHash: encodedDigest(runtimeKey), createdAt: now, lastUsedAt: now, revoked: false });
48324
49519
  return { runtimeId, runtimeKey };
@@ -48883,18 +50078,18 @@ var AgentFabricService = class _AgentFabricService {
48883
50078
  const absolute2 = path25.resolve(directory);
48884
50079
  for (let current2 = absolute2; ; current2 = path25.dirname(current2)) {
48885
50080
  try {
48886
- if ((await lstat10(current2)).isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
50081
+ if ((await lstat11(current2)).isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
48887
50082
  } catch (error62) {
48888
50083
  if (error62.code !== "ENOENT") throw error62;
48889
50084
  }
48890
50085
  if (path25.dirname(current2) === current2) break;
48891
50086
  }
48892
50087
  if (initialize) await mkdir11(absolute2, { recursive: true, mode: 448 });
48893
- if (!(await lstat10(absolute2)).isDirectory() || (await realpath9(absolute2)).toLowerCase() !== absolute2.toLowerCase())
50088
+ if (!(await lstat11(absolute2)).isDirectory() || (await realpath9(absolute2)).toLowerCase() !== absolute2.toLowerCase())
48894
50089
  throw Error("FABRIC_DIRECTORY_INVALID");
48895
50090
  const present = /* @__PURE__ */ new Set();
48896
50091
  for (const name2 of ["binding.json", "mailbox.json", "identities.json"]) {
48897
- const file2 = await lstat10(path25.join(absolute2, name2)).catch((error62) => {
50092
+ const file2 = await lstat11(path25.join(absolute2, name2)).catch((error62) => {
48898
50093
  if (error62.code === "ENOENT") return null;
48899
50094
  throw error62;
48900
50095
  });
@@ -48917,7 +50112,7 @@ var AgentFabricService = class _AgentFabricService {
48917
50112
  state.initialized = true;
48918
50113
  }
48919
50114
  const snapshot2 = await service2.mailbox.snapshot();
48920
- if (snapshot2.workers.some((worker) => worker.runtimeId !== null)) await lstat10(path25.join(absolute2, "identities.json"));
50115
+ if (snapshot2.workers.some((worker) => worker.runtimeId !== null)) await lstat11(path25.join(absolute2, "identities.json"));
48921
50116
  }, initialize ? () => expected : void 0);
48922
50117
  return service2;
48923
50118
  }
@@ -49010,12 +50205,12 @@ async function openNativeFabric(stateDirectory, enrollment, box, initialize = tr
49010
50205
  } catch (error62) {
49011
50206
  if (error62.code !== "EEXIST") throw error62;
49012
50207
  }
49013
- const parentInfo = await lstat11(parent);
50208
+ const parentInfo = await lstat12(parent);
49014
50209
  if (!parentInfo.isDirectory() || parentInfo.isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
49015
50210
  const expected = JSON.stringify({ version: 1, controllerId, tenantId });
49016
50211
  let fresh = false;
49017
50212
  try {
49018
- const info = await lstat11(marker);
50213
+ const info = await lstat12(marker);
49019
50214
  if (!info.isFile() || info.isSymbolicLink() || info.size > 2048 || await readFile10(marker, "utf8") !== expected)
49020
50215
  throw Error("FABRIC_BINDING_CHANGED");
49021
50216
  } catch (error62) {
@@ -49043,7 +50238,7 @@ async function openNativeFabric(stateDirectory, enrollment, box, initialize = tr
49043
50238
  return credential;
49044
50239
  };
49045
50240
  async function capability(workerId) {
49046
- const file2 = credentialFile(workerId), info = await lstat11(file2);
50241
+ const file2 = credentialFile(workerId), info = await lstat12(file2);
49047
50242
  if (!info.isFile() || info.isSymbolicLink() || info.size > 4096) throw Error("FABRIC_CREDENTIAL_UNKNOWN");
49048
50243
  const encoded = await readFile10(file2, "utf8");
49049
50244
  if (decode4(encoded).workerId !== workerId) throw Error("FABRIC_WORKER_DENIED");
@@ -49197,14 +50392,14 @@ function supervisorLiveness(helperPath, options = {}) {
49197
50392
 
49198
50393
  // agent/src/content-audit.ts
49199
50394
  import { createReadStream } from "node:fs";
49200
- import { appendFile, lstat as lstat12, mkdir as mkdir13, open as open12, readdir as readdir5, readFile as readFile11, rename as rename8, rm as rm9, writeFile as writeFile4 } from "node:fs/promises";
50395
+ import { appendFile, lstat as lstat13, mkdir as mkdir13, open as open12, readdir as readdir6, readFile as readFile11, rename as rename8, rm as rm9, writeFile as writeFile4 } from "node:fs/promises";
49201
50396
  import path28 from "node:path";
49202
50397
  import { performance as performance3 } from "node:perf_hooks";
49203
50398
  import { createInterface as createInterface2 } from "node:readline";
49204
- import { randomBytes as randomBytes9 } from "node:crypto";
50399
+ import { randomBytes as randomBytes10 } from "node:crypto";
49205
50400
 
49206
50401
  // src/audit-crypto.ts
49207
- import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, createHash as createHash20, randomBytes as randomBytes8 } from "node:crypto";
50402
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, createHash as createHash20, randomBytes as randomBytes9 } from "node:crypto";
49208
50403
  import { promisify as promisify3 } from "node:util";
49209
50404
  import { gunzipSync, gzip, gzipSync } from "node:zlib";
49210
50405
  var gzipAsync = promisify3(gzip);
@@ -49256,7 +50451,7 @@ async function encryptAuditRecordAsync(record2, keyInput, keyId2) {
49256
50451
  function sealCompressed(compressed, keyInput, keyId2) {
49257
50452
  const key = parseAuditRecoveryKey(keyInput);
49258
50453
  const kid = keyId2?.trim() || auditRecoveryKeyId(key);
49259
- const iv = randomBytes8(IV_BYTES);
50454
+ const iv = randomBytes9(IV_BYTES);
49260
50455
  try {
49261
50456
  const cipher = createCipheriv3("aes-256-gcm", key, iv, { authTagLength: TAG_BYTES });
49262
50457
  cipher.setAAD(additionalData(kid));
@@ -49371,13 +50566,13 @@ function contentAuditDirectory(stateDir) {
49371
50566
  }
49372
50567
  async function plainDirectory(dir) {
49373
50568
  await mkdir13(dir, { recursive: true, mode: 448 });
49374
- const info = await lstat12(dir);
50569
+ const info = await lstat13(dir);
49375
50570
  if (info.isSymbolicLink() || !info.isDirectory()) throw Error("AUDIT_DIRECTORY_INVALID");
49376
50571
  }
49377
50572
  async function auditFiles(dir) {
49378
50573
  let names;
49379
50574
  try {
49380
- names = await readdir5(dir);
50575
+ names = await readdir6(dir);
49381
50576
  } catch (error62) {
49382
50577
  if (error62.code === "ENOENT") return [];
49383
50578
  throw error62;
@@ -49386,13 +50581,13 @@ async function auditFiles(dir) {
49386
50581
  for (const name2 of names) {
49387
50582
  const match = FILE.exec(name2);
49388
50583
  if (!match) continue;
49389
- const info = await lstat12(path28.join(dir, name2));
50584
+ const info = await lstat13(path28.join(dir, name2));
49390
50585
  if (info.isFile()) files.push({ name: name2, kind: match[1], day: match[2], bytes: info.size });
49391
50586
  }
49392
50587
  return files.sort((a, b) => a.name.localeCompare(b.name));
49393
50588
  }
49394
50589
  async function writeJsonAtomic(file2, value) {
49395
- const temp = `${file2}.${randomBytes9(6).toString("hex")}.tmp`;
50590
+ const temp = `${file2}.${randomBytes10(6).toString("hex")}.tmp`;
49396
50591
  try {
49397
50592
  await writeFile4(temp, JSON.stringify(value) + "\n", { flag: "wx", mode: 384 });
49398
50593
  await rename8(temp, file2);
@@ -49629,7 +50824,7 @@ async function restoreContentAudit(input2, output2, key) {
49629
50824
  }
49630
50825
 
49631
50826
  // agent/src/main.ts
49632
- var AGENT_VERSION2 = true ? "0.3.46" : "0.3.2";
50827
+ var AGENT_VERSION2 = true ? "0.3.47" : "0.3.2";
49633
50828
  var NETWORK_PUBLIC_KEY = true ? "-----BEGIN PUBLIC KEY-----\nMIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAvmu+81vWtJBQDZNHcAIW\nzCSxpG+R9RBsum2df5mP2cOW+wyUDTpnYquFge1qgI5YYTF96j0xCyXL8B9FeNWs\n939opWNmv53j+CQlS4cEIQhBbZSCu0eC4icsVEzBhvf68MB+E668SOtZBcVTEnyh\n96PTcupxS10rQJBWDinbKBXRC2gvGYeu01rWa/nsrndy4vAYP5t3yQtdOC8e8mr0\n+2Mg2Qhiq+KiTCtDd+L9oXvoLqqJYbzUIveNGha25AWxF1Weblp0gOM87hell5gV\nK7q4ZLUq/wBRGYNmQRdLyV7/WRE1FFPSW21/SBZQ/5aU4UqJU/MjMcrJUrnRKngz\nYKmo0czkxS3N7Q2KVxomgR1AQSuQFKMrboZYKjShADp9RIYUxzs7cYg51Of5PnHh\n6Ax+VevDGfzjMD+yHuyxYZqCtX4OwgolJxz63UQbzKlris+8xb5lLYTbIuz90Pss\nn6HK/F5May25c6oMmS3nh/NsiZopL1OvdtWKTt1L4WlRAgMBAAE=\n-----END PUBLIC KEY-----\n" : "";
49634
50829
  var AI_CONNECTION_SHIPPED = false;
49635
50830
  function processAlive(pid) {