local-commander-agent 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
@@ -2125,7 +2125,7 @@ var require_extension = __commonJS({
2125
2125
  if (dest[name2] === void 0) dest[name2] = [elem];
2126
2126
  else dest[name2].push(elem);
2127
2127
  }
2128
- function parse3(header) {
2128
+ function parse4(header) {
2129
2129
  const offers = /* @__PURE__ */ Object.create(null);
2130
2130
  let params = /* @__PURE__ */ Object.create(null);
2131
2131
  let mustUnescape = false;
@@ -2265,7 +2265,7 @@ var require_extension = __commonJS({
2265
2265
  }).join(", ");
2266
2266
  }).join(", ");
2267
2267
  }
2268
- module.exports = { format, parse: parse3 };
2268
+ module.exports = { format, parse: parse4 };
2269
2269
  }
2270
2270
  });
2271
2271
 
@@ -2276,9 +2276,9 @@ var require_websocket = __commonJS({
2276
2276
  var EventEmitter = __require("events");
2277
2277
  var https2 = __require("https");
2278
2278
  var http2 = __require("http");
2279
- var net2 = __require("net");
2279
+ var net3 = __require("net");
2280
2280
  var tls2 = __require("tls");
2281
- var { randomBytes: randomBytes10, createHash: createHash21 } = __require("crypto");
2281
+ var { randomBytes: randomBytes11, createHash: createHash21 } = __require("crypto");
2282
2282
  var { Duplex, Readable } = __require("stream");
2283
2283
  var { URL: URL2 } = __require("url");
2284
2284
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -2299,7 +2299,7 @@ var require_websocket = __commonJS({
2299
2299
  var {
2300
2300
  EventTarget: { addEventListener, removeEventListener }
2301
2301
  } = require_event_target();
2302
- var { format, parse: parse3 } = require_extension();
2302
+ var { format, parse: parse4 } = require_extension();
2303
2303
  var { toBuffer } = require_buffer_util();
2304
2304
  var kAborted = /* @__PURE__ */ Symbol("kAborted");
2305
2305
  var protocolVersions = [8, 13];
@@ -2829,7 +2829,7 @@ var require_websocket = __commonJS({
2829
2829
  }
2830
2830
  }
2831
2831
  const defaultPort = isSecure ? 443 : 80;
2832
- const key = randomBytes10(16).toString("base64");
2832
+ const key = randomBytes11(16).toString("base64");
2833
2833
  const request = isSecure ? https2.request : http2.request;
2834
2834
  const protocolSet = /* @__PURE__ */ new Set();
2835
2835
  let perMessageDeflate;
@@ -2989,7 +2989,7 @@ var require_websocket = __commonJS({
2989
2989
  }
2990
2990
  let extensions;
2991
2991
  try {
2992
- extensions = parse3(secWebSocketExtensions);
2992
+ extensions = parse4(secWebSocketExtensions);
2993
2993
  } catch (err) {
2994
2994
  const message2 = "Invalid Sec-WebSocket-Extensions header";
2995
2995
  abortHandshake(websocket, socket, message2);
@@ -3033,12 +3033,12 @@ var require_websocket = __commonJS({
3033
3033
  }
3034
3034
  function netConnect2(options) {
3035
3035
  options.path = options.socketPath;
3036
- return net2.connect(options);
3036
+ return net3.connect(options);
3037
3037
  }
3038
3038
  function tlsConnect(options) {
3039
3039
  options.path = void 0;
3040
3040
  if (!options.servername && options.servername !== "") {
3041
- options.servername = net2.isIP(options.host) ? "" : options.host;
3041
+ options.servername = net3.isIP(options.host) ? "" : options.host;
3042
3042
  }
3043
3043
  return tls2.connect(options);
3044
3044
  }
@@ -3281,7 +3281,7 @@ var require_subprotocol = __commonJS({
3281
3281
  "../../node_modules/ws/lib/subprotocol.js"(exports, module) {
3282
3282
  "use strict";
3283
3283
  var { tokenChars } = require_validation();
3284
- function parse3(header) {
3284
+ function parse4(header) {
3285
3285
  const protocols = /* @__PURE__ */ new Set();
3286
3286
  let start = -1;
3287
3287
  let end = -1;
@@ -3317,7 +3317,7 @@ var require_subprotocol = __commonJS({
3317
3317
  protocols.add(protocol2);
3318
3318
  return protocols;
3319
3319
  }
3320
- module.exports = { parse: parse3 };
3320
+ module.exports = { parse: parse4 };
3321
3321
  }
3322
3322
  });
3323
3323
 
@@ -5570,18 +5570,18 @@ var validateAsync = async (schema, value, _ctx) => {
5570
5570
  return result2.issues.length === 0;
5571
5571
  };
5572
5572
  var _encode = (_Err) => {
5573
- const parse3 = _parse(_Err);
5573
+ const parse4 = _parse(_Err);
5574
5574
  const fn = (schema, value, _ctx, _params) => {
5575
5575
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
5576
- return parse3(schema, value, ctx, finalizeParams(fn, _params));
5576
+ return parse4(schema, value, ctx, finalizeParams(fn, _params));
5577
5577
  };
5578
5578
  return fn;
5579
5579
  };
5580
5580
  var encode = /* @__PURE__ */ _encode($ZodRealError);
5581
5581
  var _decode = (_Err) => {
5582
- const parse3 = _parse(_Err);
5582
+ const parse4 = _parse(_Err);
5583
5583
  const fn = (schema, value, _ctx, _params) => {
5584
- return parse3(schema, value, _ctx, finalizeParams(fn, _params));
5584
+ return parse4(schema, value, _ctx, finalizeParams(fn, _params));
5585
5585
  };
5586
5586
  return fn;
5587
5587
  };
@@ -26466,10 +26466,12 @@ var ServerFrameSchema = external_exports.discriminatedUnion("type", [
26466
26466
  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(),
26467
26467
  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()
26468
26468
  ]);
26469
+ var WORKSPACE_ACCESS_MODE_CAPABILITY = "workspaceAccessModeV1";
26470
+ var WorkspaceAccessModeSchema = external_exports.enum(["full", "scoped"]);
26469
26471
  var ClientFrameSchema = external_exports.discriminatedUnion("type", [
26470
26472
  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(),
26471
26473
  external_exports.object({ type: external_exports.literal("heartbeat"), version: external_exports.literal(1), connectionEpoch: epoch2 }).strict(),
26472
- 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(),
26474
+ 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(),
26473
26475
  external_exports.object({ type: external_exports.literal("workspace_revoke"), version: external_exports.literal(1), requestId: uuid11, workspaceGrantId: uuid11 }).strict(),
26474
26476
  external_exports.object({ type: external_exports.literal("prepared"), version: external_exports.literal(1), binding: ExecutionBindingSchema }).strict(),
26475
26477
  external_exports.object({ type: external_exports.literal("accepted"), version: external_exports.literal(1), binding: ExecutionBindingSchema }).strict(),
@@ -27030,9 +27032,9 @@ var NativeJournal = class _NativeJournal {
27030
27032
  if (!validPid(pid)) throw failure2("JOURNAL_INPUT_INVALID");
27031
27033
  if (e.state !== "running" || !e.supervisors) throw failure2("JOURNAL_STATE_INVALID");
27032
27034
  if (containment !== void 0) {
27033
- const linux = validLinuxContainment(containment), darwin = !linux && validDarwinContainment(containment);
27034
- 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");
27035
- if (linux) (e.linuxSupervisors ??= []).push({ pid, containment: clone2(containment) });
27035
+ const linux2 = validLinuxContainment(containment), darwin = !linux2 && validDarwinContainment(containment);
27036
+ 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");
27037
+ if (linux2) (e.linuxSupervisors ??= []).push({ pid, containment: clone2(containment) });
27036
27038
  else (e.darwinSupervisors ??= []).push({ pid, containment: clone2(containment) });
27037
27039
  } else {
27038
27040
  if (e.supervisors.length >= MAX_SUPERVISORS) throw failure2("JOURNAL_SUPERVISOR_LIMIT");
@@ -28905,8 +28907,8 @@ var HostMemory = class {
28905
28907
  };
28906
28908
 
28907
28909
  // agent/src/tools.ts
28908
- import { constants as constants7 } from "node:fs";
28909
- import { lstat as lstat7, open as open6, readdir as readdir4, realpath as realpath7, rename as rename4, rm as rm6 } from "node:fs/promises";
28910
+ import { constants as constants8 } from "node:fs";
28911
+ import { lstat as lstat8, open as open6, readdir as readdir5, realpath as realpath7, rename as rename4, rm as rm6 } from "node:fs/promises";
28910
28912
  import path18 from "node:path";
28911
28913
  import { createHash as createHash14, randomUUID as randomUUID7 } from "node:crypto";
28912
28914
 
@@ -29353,22 +29355,1025 @@ async function runSupervised(helper, request, options = {}) {
29353
29355
 
29354
29356
  // agent/src/screen-capture.ts
29355
29357
  import { execFile as execFile4 } from "node:child_process";
29356
- import { mkdtemp, readFile as readFile6, rm as rm5 } from "node:fs/promises";
29358
+ import { randomBytes as randomBytes6 } from "node:crypto";
29359
+ import { constants as constants7 } from "node:fs";
29360
+ import { access as access3, lstat as lstat7, mkdtemp, readFile as readFile6, readdir as readdir4, rm as rm5, unlink as unlink2 } from "node:fs/promises";
29357
29361
  import os4 from "node:os";
29358
29362
  import path17 from "node:path";
29363
+
29364
+ // agent/src/dbus-portal.ts
29365
+ import net from "node:net";
29366
+ function sessionBusSocket(address) {
29367
+ for (const entry of (address ?? "").split(";")) {
29368
+ if (!entry.startsWith("unix:")) continue;
29369
+ for (const part of entry.slice(5).split(",")) {
29370
+ const at = part.indexOf("="), key = part.slice(0, at), value = decodeURIComponent(part.slice(at + 1));
29371
+ if (at > 0 && value && key === "path") return value;
29372
+ if (at > 0 && value && key === "abstract") return "\0" + value;
29373
+ }
29374
+ }
29375
+ return null;
29376
+ }
29377
+ var Writer = class {
29378
+ bytes = [];
29379
+ align(n) {
29380
+ while (this.bytes.length % n) this.bytes.push(0);
29381
+ }
29382
+ byte(v) {
29383
+ this.bytes.push(v & 255);
29384
+ }
29385
+ u32(v) {
29386
+ this.align(4);
29387
+ this.bytes.push(v & 255, v >>> 8 & 255, v >>> 16 & 255, v >>> 24 & 255);
29388
+ }
29389
+ str(v) {
29390
+ const b = Buffer.from(v, "utf8");
29391
+ this.u32(b.length);
29392
+ this.bytes.push(...b, 0);
29393
+ }
29394
+ sig(v) {
29395
+ this.byte(v.length);
29396
+ this.bytes.push(...Buffer.from(v, "ascii"), 0);
29397
+ }
29398
+ /** Basic value or variant: `s`, `o`, `g`, `u`, `b`, `v` ([signature, value]). */
29399
+ put(type, value) {
29400
+ if (type === "s" || type === "o") this.str(String(value));
29401
+ else if (type === "g") this.sig(String(value));
29402
+ else if (type === "u") this.u32(Number(value));
29403
+ else if (type === "b") this.u32(value ? 1 : 0);
29404
+ else if (type === "v") {
29405
+ const [inner, v] = value;
29406
+ this.sig(inner);
29407
+ this.put(inner, v);
29408
+ } else throw Error("type " + type);
29409
+ }
29410
+ /** a{sv} */
29411
+ dict(entries) {
29412
+ this.u32(0);
29413
+ const lengthAt = this.bytes.length - 4;
29414
+ this.align(8);
29415
+ const start = this.bytes.length;
29416
+ for (const [key, value] of entries) {
29417
+ this.align(8);
29418
+ this.str(key);
29419
+ this.put("v", value);
29420
+ }
29421
+ const length = this.bytes.length - start;
29422
+ this.bytes.splice(lengthAt, 4, length & 255, length >>> 8 & 255, length >>> 16 & 255, length >>> 24 & 255);
29423
+ }
29424
+ };
29425
+ var Reader = class {
29426
+ constructor(data, at, le) {
29427
+ this.data = data;
29428
+ this.at = at;
29429
+ this.le = le;
29430
+ }
29431
+ data;
29432
+ at;
29433
+ le;
29434
+ align(n) {
29435
+ this.at = Math.ceil(this.at / n) * n;
29436
+ }
29437
+ u32() {
29438
+ this.align(4);
29439
+ const v = this.le ? this.data.readUInt32LE(this.at) : this.data.readUInt32BE(this.at);
29440
+ this.at += 4;
29441
+ return v;
29442
+ }
29443
+ /** Reads one complete type from `sig` starting at `i`; returns the value and the index after the type. */
29444
+ read(sig2, i) {
29445
+ const c = sig2[i];
29446
+ const fixed = { y: 1, n: 2, q: 2, b: 4, i: 4, u: 4, h: 4, x: 8, t: 8, d: 8 };
29447
+ if (c in fixed) {
29448
+ const size = fixed[c];
29449
+ this.align(size);
29450
+ 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;
29451
+ this.at += size;
29452
+ return [c === "b" ? v === 1 : v, i + 1];
29453
+ }
29454
+ if (c === "s" || c === "o") {
29455
+ const n = this.u32(), v = this.data.toString("utf8", this.at, this.at + n);
29456
+ this.at += n + 1;
29457
+ return [v, i + 1];
29458
+ }
29459
+ if (c === "g") {
29460
+ const n = this.data[this.at], v = this.data.toString("ascii", this.at + 1, this.at + 1 + n);
29461
+ this.at += n + 2;
29462
+ return [v, i + 1];
29463
+ }
29464
+ if (c === "v") {
29465
+ const [inner] = this.read("g", 0);
29466
+ return [this.read(inner, 0)[0], i + 1];
29467
+ }
29468
+ if (c === "(" || c === "{") {
29469
+ this.align(8);
29470
+ const close = c === "(" ? ")" : "}", values = [];
29471
+ let j = i + 1;
29472
+ while (sig2[j] !== close) {
29473
+ const [v, next] = this.read(sig2, j);
29474
+ values.push(v);
29475
+ j = next;
29476
+ }
29477
+ return [values, j + 1];
29478
+ }
29479
+ if (c === "a") {
29480
+ const n = this.u32(), element = sig2[i + 1];
29481
+ this.align("xtd({".includes(element) ? 8 : element === "n" || element === "q" ? 2 : element === "y" || element === "g" || element === "v" ? 1 : 4);
29482
+ const end = this.at + n, values = [];
29483
+ let next = skip(sig2, i + 1);
29484
+ while (this.at < end) {
29485
+ const [v, j] = this.read(sig2, i + 1);
29486
+ values.push(v);
29487
+ next = j;
29488
+ }
29489
+ return [values, next];
29490
+ }
29491
+ throw Error("signature " + sig2);
29492
+ }
29493
+ };
29494
+ function skip(sig2, i) {
29495
+ const c = sig2[i];
29496
+ if (c === "a") return skip(sig2, i + 1);
29497
+ if (c === "(" || c === "{") {
29498
+ let j = i + 1;
29499
+ while (sig2[j] !== (c === "(" ? ")" : "}")) j = skip(sig2, j);
29500
+ return j + 1;
29501
+ }
29502
+ return i + 1;
29503
+ }
29504
+ function parse3(data) {
29505
+ const le = data[0] === 108, r = new Reader(data, 4, le), bodyLength = r.u32(), serial = r.u32();
29506
+ const [fields] = r.read("a(yv)", 0);
29507
+ const message2 = { type: data[1], serial, signature: "", body: [] };
29508
+ for (const [code, value] of fields) {
29509
+ if (code === 1) message2.path = String(value);
29510
+ else if (code === 2) message2.interface = String(value);
29511
+ else if (code === 3) message2.member = String(value);
29512
+ else if (code === 4) message2.errorName = String(value);
29513
+ else if (code === 5) message2.replySerial = Number(value);
29514
+ else if (code === 8) message2.signature = String(value);
29515
+ }
29516
+ r.align(8);
29517
+ const end = r.at + bodyLength;
29518
+ for (let i = 0; i < message2.signature.length && r.at < end; ) {
29519
+ const [v, next] = r.read(message2.signature, i);
29520
+ message2.body.push(v);
29521
+ i = next;
29522
+ }
29523
+ return message2;
29524
+ }
29525
+ function frameLength(data) {
29526
+ if (data.length < 16) return 0;
29527
+ const le = data[0] === 108, u = (at) => le ? data.readUInt32LE(at) : data.readUInt32BE(at);
29528
+ const length = Math.ceil((16 + u(12)) / 8) * 8 + u(4);
29529
+ return data.length >= length ? length : 0;
29530
+ }
29531
+ async function portalScreenshot(socket, uid, token, signal) {
29532
+ const connection = net.createConnection({ path: socket });
29533
+ try {
29534
+ return await new Promise((resolve, reject) => {
29535
+ let serial = 0, buffer = Buffer.alloc(0), authenticated = false, requestPath = "";
29536
+ const pending = /* @__PURE__ */ new Map();
29537
+ const fail7 = (error62) => reject(error62 instanceof Error ? error62 : Error(String(error62)));
29538
+ const abort = () => fail7(Error("ABORTED"));
29539
+ if (signal.aborted) return abort();
29540
+ signal.addEventListener("abort", abort, { once: true });
29541
+ connection.on("error", fail7);
29542
+ connection.on("close", () => fail7(Error("CLOSED")));
29543
+ const call = (destination, path30, iface, member, signature = "", body = () => {
29544
+ }) => new Promise((done, failed) => {
29545
+ const payload2 = new Writer();
29546
+ body(payload2);
29547
+ const header = new Writer(), fields = [[1, "o", path30], [2, "s", iface], [3, "s", member], [6, "s", destination]];
29548
+ if (signature) fields.push([8, "g", signature]);
29549
+ header.byte(108);
29550
+ header.byte(1);
29551
+ header.byte(0);
29552
+ header.byte(1);
29553
+ header.u32(payload2.bytes.length);
29554
+ header.u32(++serial);
29555
+ header.u32(0);
29556
+ const lengthAt = header.bytes.length - 4;
29557
+ header.align(8);
29558
+ const start = header.bytes.length;
29559
+ for (const [code, type, value] of fields) {
29560
+ header.align(8);
29561
+ header.byte(code);
29562
+ header.sig(type);
29563
+ header.put(type, value);
29564
+ }
29565
+ const length = header.bytes.length - start;
29566
+ header.bytes.splice(lengthAt, 4, length & 255, length >>> 8 & 255, length >>> 16 & 255, length >>> 24 & 255);
29567
+ header.align(8);
29568
+ pending.set(serial, (reply) => reply.type === 3 ? failed(Error(reply.errorName ?? "DBUS_ERROR")) : done(reply));
29569
+ connection.write(Buffer.from([...header.bytes, ...payload2.bytes]));
29570
+ });
29571
+ const bus = (member, signature, body) => call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", member, signature, body);
29572
+ connection.on("data", (chunk) => {
29573
+ try {
29574
+ receive(chunk);
29575
+ } catch (error62) {
29576
+ fail7(error62);
29577
+ }
29578
+ });
29579
+ const receive = (chunk) => {
29580
+ buffer = Buffer.concat([buffer, chunk]);
29581
+ if (buffer.length > 1048576) return fail7(Error("OVERSIZED"));
29582
+ if (!authenticated) {
29583
+ const end = buffer.indexOf("\r\n");
29584
+ if (end < 0) return;
29585
+ const line = buffer.toString("ascii", 0, end);
29586
+ buffer = buffer.subarray(end + 2);
29587
+ if (!line.startsWith("OK ")) return fail7(Error("AUTH"));
29588
+ authenticated = true;
29589
+ connection.write("BEGIN\r\n");
29590
+ void (async () => {
29591
+ const unique = String((await bus("Hello")).body[0]);
29592
+ requestPath = "/org/freedesktop/portal/desktop/request/" + unique.slice(1).replace(/\./g, "_") + "/" + token;
29593
+ await bus("AddMatch", "s", (w) => w.put("s", "type='signal',interface='org.freedesktop.portal.Request',member='Response',path='" + requestPath + "'"));
29594
+ const handle = await call(
29595
+ "org.freedesktop.portal.Desktop",
29596
+ "/org/freedesktop/portal/desktop",
29597
+ "org.freedesktop.portal.Screenshot",
29598
+ "Screenshot",
29599
+ "sa{sv}",
29600
+ (w) => {
29601
+ w.put("s", "");
29602
+ w.dict([["handle_token", ["s", token]], ["interactive", ["b", false]]]);
29603
+ }
29604
+ );
29605
+ if (handle.body[0] !== requestPath) {
29606
+ requestPath = String(handle.body[0]);
29607
+ await bus("AddMatch", "s", (w) => w.put("s", "type='signal',interface='org.freedesktop.portal.Request',member='Response',path='" + requestPath + "'"));
29608
+ }
29609
+ })().catch(fail7);
29610
+ }
29611
+ for (let length = frameLength(buffer); authenticated && length; length = frameLength(buffer)) {
29612
+ const message2 = parse3(buffer.subarray(0, length));
29613
+ buffer = buffer.subarray(length);
29614
+ if ((message2.type === 2 || message2.type === 3) && message2.replySerial !== void 0) {
29615
+ pending.get(message2.replySerial)?.(message2);
29616
+ pending.delete(message2.replySerial);
29617
+ } else if (message2.type === 4 && message2.member === "Response" && message2.path === requestPath && message2.signature === "ua{sv}") {
29618
+ const results2 = message2.body[1], uri = results2.find(([key]) => key === "uri")?.[1];
29619
+ resolve({ code: Number(message2.body[0]), uri: typeof uri === "string" ? uri : void 0 });
29620
+ }
29621
+ }
29622
+ };
29623
+ connection.on("connect", () => connection.write("\0AUTH EXTERNAL " + Buffer.from(String(uid), "ascii").toString("hex") + "\r\n"));
29624
+ });
29625
+ } finally {
29626
+ connection.destroy();
29627
+ }
29628
+ }
29629
+
29630
+ // agent/src/screen-image.ts
29631
+ import { inflateSync } from "node:zlib";
29632
+ var MAX_EDGE = 16384;
29633
+ var MAX_PIXELS = 67108864;
29634
+ function sizeOk(width, height) {
29635
+ return Number.isSafeInteger(width) && Number.isSafeInteger(height) && width > 0 && height > 0 && width <= MAX_EDGE && height <= MAX_EDGE && width * height <= MAX_PIXELS;
29636
+ }
29637
+ function decodePng(data) {
29638
+ if (data.length < 33 || data.readUInt32BE(0) !== 2303741511 || data.readUInt32BE(4) !== 218765834) return null;
29639
+ let width = 0, height = 0, channels = 0;
29640
+ const idat = [];
29641
+ for (let at = 8; at + 12 <= data.length; ) {
29642
+ const length = data.readUInt32BE(at), type = data.toString("latin1", at + 4, at + 8), body = at + 8;
29643
+ if (body + length + 4 > data.length) return null;
29644
+ if (type === "IHDR") {
29645
+ if (length !== 13) return null;
29646
+ width = data.readUInt32BE(body);
29647
+ height = data.readUInt32BE(body + 4);
29648
+ const depth = data[body + 8], color = data[body + 9], interlace = data[body + 12];
29649
+ channels = color === 0 ? 1 : color === 2 ? 3 : color === 4 ? 2 : color === 6 ? 4 : 0;
29650
+ if (depth !== 8 || !channels || interlace !== 0 || data[body + 10] !== 0 || data[body + 11] !== 0 || !sizeOk(width, height)) return null;
29651
+ } else if (type === "IDAT") idat.push(data.subarray(body, body + length));
29652
+ else if (type === "IEND") break;
29653
+ at = body + length + 4;
29654
+ }
29655
+ if (!channels || !idat.length) return null;
29656
+ const stride = width * channels, expected = (stride + 1) * height;
29657
+ let raw;
29658
+ try {
29659
+ raw = inflateSync(Buffer.concat(idat), { maxOutputLength: expected });
29660
+ } catch {
29661
+ return null;
29662
+ }
29663
+ if (raw.length !== expected) return null;
29664
+ const rgb = Buffer.alloc(width * height * 3);
29665
+ let previous = Buffer.alloc(stride), current2 = Buffer.alloc(stride);
29666
+ for (let y = 0; y < height; y++) {
29667
+ const filter = raw[y * (stride + 1)], line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
29668
+ for (let x = 0; x < stride; x++) {
29669
+ const a = x >= channels ? current2[x - channels] : 0, b = previous[x], c = x >= channels ? previous[x - channels] : 0;
29670
+ let value = line[x];
29671
+ if (filter === 1) value += a;
29672
+ else if (filter === 2) value += b;
29673
+ else if (filter === 3) value += a + b >> 1;
29674
+ else if (filter === 4) {
29675
+ const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
29676
+ value += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
29677
+ } else if (filter !== 0) return null;
29678
+ current2[x] = value & 255;
29679
+ }
29680
+ for (let x = 0, o = y * width * 3; x < width; x++, o += 3) {
29681
+ const i = x * channels;
29682
+ if (channels <= 2) rgb[o] = rgb[o + 1] = rgb[o + 2] = current2[i];
29683
+ else {
29684
+ rgb[o] = current2[i];
29685
+ rgb[o + 1] = current2[i + 1];
29686
+ rgb[o + 2] = current2[i + 2];
29687
+ }
29688
+ }
29689
+ [previous, current2] = [current2, previous];
29690
+ }
29691
+ return { width, height, rgb };
29692
+ }
29693
+ function decodeXwd(data) {
29694
+ if (data.length < 100) return null;
29695
+ const field = (index) => data.readUInt32BE(index * 4);
29696
+ const headerSize = field(0), version2 = field(1), format = field(2), width = field(4), height = field(5), byteOrder = field(7);
29697
+ const bitsPerPixel = field(11), bytesPerLine = field(12), visualClass = field(13), masks = [field(14), field(15), field(16)], colors = field(19);
29698
+ if (version2 !== 7 || format !== 2 || headerSize < 100 || ![4, 5].includes(visualClass) || ![24, 32].includes(bitsPerPixel) || !sizeOk(width, height) || colors > 65536) return null;
29699
+ const pixelBytes = bitsPerPixel / 8, start = headerSize + colors * 12;
29700
+ if (bytesPerLine < width * pixelBytes || start + bytesPerLine * height > data.length || masks.some((mask) => !mask)) return null;
29701
+ const shifts = masks.map((mask) => {
29702
+ let shift = 0;
29703
+ while (!(mask >>> shift & 1)) shift++;
29704
+ return shift;
29705
+ });
29706
+ const scales = masks.map((mask, i) => 255 / (mask >>> shifts[i]));
29707
+ const rgb = Buffer.alloc(width * height * 3);
29708
+ 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) {
29709
+ 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];
29710
+ for (let c = 0; c < 3; c++) rgb[o + c] = Math.round(((pixel & masks[c]) >>> 0 >>> shifts[c]) * scales[c]);
29711
+ }
29712
+ return { width, height, rgb };
29713
+ }
29714
+ function downscale(image, edge) {
29715
+ const scale = Math.min(1, edge / Math.max(image.width, image.height));
29716
+ if (scale >= 1) return image;
29717
+ const width = Math.max(1, Math.round(image.width * scale)), height = Math.max(1, Math.round(image.height * scale));
29718
+ const xs = Array.from({ length: width + 1 }, (_, x) => Math.min(image.width, Math.floor(x * image.width / width)));
29719
+ const ys = Array.from({ length: height + 1 }, (_, y) => Math.min(image.height, Math.floor(y * image.height / height)));
29720
+ const rgb = Buffer.alloc(width * height * 3), sums = new Float64Array(width * 3);
29721
+ for (let y = 0; y < height; y++) {
29722
+ sums.fill(0);
29723
+ 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++) {
29724
+ const i = (sy * image.width + sx) * 3;
29725
+ sums[x * 3] = sums[x * 3] + image.rgb[i];
29726
+ sums[x * 3 + 1] = sums[x * 3 + 1] + image.rgb[i + 1];
29727
+ sums[x * 3 + 2] = sums[x * 3 + 2] + image.rgb[i + 2];
29728
+ }
29729
+ for (let x = 0; x < width; x++) {
29730
+ const count3 = (ys[y + 1] - ys[y]) * (xs[x + 1] - xs[x]);
29731
+ for (let c = 0; c < 3; c++) rgb[(y * width + x) * 3 + c] = Math.round(sums[x * 3 + c] / count3);
29732
+ }
29733
+ }
29734
+ return { width, height, rgb };
29735
+ }
29736
+ var ZIGZAG = [
29737
+ 0,
29738
+ 1,
29739
+ 5,
29740
+ 6,
29741
+ 14,
29742
+ 15,
29743
+ 27,
29744
+ 28,
29745
+ 2,
29746
+ 4,
29747
+ 7,
29748
+ 13,
29749
+ 16,
29750
+ 26,
29751
+ 29,
29752
+ 42,
29753
+ 3,
29754
+ 8,
29755
+ 12,
29756
+ 17,
29757
+ 25,
29758
+ 30,
29759
+ 41,
29760
+ 43,
29761
+ 9,
29762
+ 11,
29763
+ 18,
29764
+ 24,
29765
+ 31,
29766
+ 40,
29767
+ 44,
29768
+ 53,
29769
+ 10,
29770
+ 19,
29771
+ 23,
29772
+ 32,
29773
+ 39,
29774
+ 45,
29775
+ 52,
29776
+ 54,
29777
+ 20,
29778
+ 22,
29779
+ 33,
29780
+ 38,
29781
+ 46,
29782
+ 51,
29783
+ 55,
29784
+ 60,
29785
+ 21,
29786
+ 34,
29787
+ 37,
29788
+ 47,
29789
+ 50,
29790
+ 56,
29791
+ 59,
29792
+ 61,
29793
+ 35,
29794
+ 36,
29795
+ 48,
29796
+ 49,
29797
+ 57,
29798
+ 58,
29799
+ 62,
29800
+ 63
29801
+ ];
29802
+ var LUMA_QUANT = [
29803
+ 16,
29804
+ 11,
29805
+ 10,
29806
+ 16,
29807
+ 24,
29808
+ 40,
29809
+ 51,
29810
+ 61,
29811
+ 12,
29812
+ 12,
29813
+ 14,
29814
+ 19,
29815
+ 26,
29816
+ 58,
29817
+ 60,
29818
+ 55,
29819
+ 14,
29820
+ 13,
29821
+ 16,
29822
+ 24,
29823
+ 40,
29824
+ 57,
29825
+ 69,
29826
+ 56,
29827
+ 14,
29828
+ 17,
29829
+ 22,
29830
+ 29,
29831
+ 51,
29832
+ 87,
29833
+ 80,
29834
+ 62,
29835
+ 18,
29836
+ 22,
29837
+ 37,
29838
+ 56,
29839
+ 68,
29840
+ 109,
29841
+ 103,
29842
+ 77,
29843
+ 24,
29844
+ 35,
29845
+ 55,
29846
+ 64,
29847
+ 81,
29848
+ 104,
29849
+ 113,
29850
+ 92,
29851
+ 49,
29852
+ 64,
29853
+ 78,
29854
+ 87,
29855
+ 103,
29856
+ 121,
29857
+ 120,
29858
+ 101,
29859
+ 72,
29860
+ 92,
29861
+ 95,
29862
+ 98,
29863
+ 112,
29864
+ 100,
29865
+ 103,
29866
+ 99
29867
+ ];
29868
+ 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)];
29869
+ var AC_LUMA_VALUES = [
29870
+ 1,
29871
+ 2,
29872
+ 3,
29873
+ 0,
29874
+ 4,
29875
+ 17,
29876
+ 5,
29877
+ 18,
29878
+ 33,
29879
+ 49,
29880
+ 65,
29881
+ 6,
29882
+ 19,
29883
+ 81,
29884
+ 97,
29885
+ 7,
29886
+ 34,
29887
+ 113,
29888
+ 20,
29889
+ 50,
29890
+ 129,
29891
+ 145,
29892
+ 161,
29893
+ 8,
29894
+ 35,
29895
+ 66,
29896
+ 177,
29897
+ 193,
29898
+ 21,
29899
+ 82,
29900
+ 209,
29901
+ 240,
29902
+ 36,
29903
+ 51,
29904
+ 98,
29905
+ 114,
29906
+ 130,
29907
+ 9,
29908
+ 10,
29909
+ 22,
29910
+ 23,
29911
+ 24,
29912
+ 25,
29913
+ 26,
29914
+ 37,
29915
+ 38,
29916
+ 39,
29917
+ 40,
29918
+ 41,
29919
+ 42,
29920
+ 52,
29921
+ 53,
29922
+ 54,
29923
+ 55,
29924
+ 56,
29925
+ 57,
29926
+ 58,
29927
+ 67,
29928
+ 68,
29929
+ 69,
29930
+ 70,
29931
+ 71,
29932
+ 72,
29933
+ 73,
29934
+ 74,
29935
+ 83,
29936
+ 84,
29937
+ 85,
29938
+ 86,
29939
+ 87,
29940
+ 88,
29941
+ 89,
29942
+ 90,
29943
+ 99,
29944
+ 100,
29945
+ 101,
29946
+ 102,
29947
+ 103,
29948
+ 104,
29949
+ 105,
29950
+ 106,
29951
+ 115,
29952
+ 116,
29953
+ 117,
29954
+ 118,
29955
+ 119,
29956
+ 120,
29957
+ 121,
29958
+ 122,
29959
+ 131,
29960
+ 132,
29961
+ 133,
29962
+ 134,
29963
+ 135,
29964
+ 136,
29965
+ 137,
29966
+ 138,
29967
+ 146,
29968
+ 147,
29969
+ 148,
29970
+ 149,
29971
+ 150,
29972
+ 151,
29973
+ 152,
29974
+ 153,
29975
+ 154,
29976
+ 162,
29977
+ 163,
29978
+ 164,
29979
+ 165,
29980
+ 166,
29981
+ 167,
29982
+ 168,
29983
+ 169,
29984
+ 170,
29985
+ 178,
29986
+ 179,
29987
+ 180,
29988
+ 181,
29989
+ 182,
29990
+ 183,
29991
+ 184,
29992
+ 185,
29993
+ 186,
29994
+ 194,
29995
+ 195,
29996
+ 196,
29997
+ 197,
29998
+ 198,
29999
+ 199,
30000
+ 200,
30001
+ 201,
30002
+ 202,
30003
+ 210,
30004
+ 211,
30005
+ 212,
30006
+ 213,
30007
+ 214,
30008
+ 215,
30009
+ 216,
30010
+ 217,
30011
+ 218,
30012
+ 225,
30013
+ 226,
30014
+ 227,
30015
+ 228,
30016
+ 229,
30017
+ 230,
30018
+ 231,
30019
+ 232,
30020
+ 233,
30021
+ 234,
30022
+ 241,
30023
+ 242,
30024
+ 243,
30025
+ 244,
30026
+ 245,
30027
+ 246,
30028
+ 247,
30029
+ 248,
30030
+ 249,
30031
+ 250
30032
+ ];
30033
+ var AC_CHROMA_VALUES = [
30034
+ 0,
30035
+ 1,
30036
+ 2,
30037
+ 3,
30038
+ 17,
30039
+ 4,
30040
+ 5,
30041
+ 33,
30042
+ 49,
30043
+ 6,
30044
+ 18,
30045
+ 65,
30046
+ 81,
30047
+ 7,
30048
+ 97,
30049
+ 113,
30050
+ 19,
30051
+ 34,
30052
+ 50,
30053
+ 129,
30054
+ 8,
30055
+ 20,
30056
+ 66,
30057
+ 145,
30058
+ 161,
30059
+ 177,
30060
+ 193,
30061
+ 9,
30062
+ 35,
30063
+ 51,
30064
+ 82,
30065
+ 240,
30066
+ 21,
30067
+ 98,
30068
+ 114,
30069
+ 209,
30070
+ 10,
30071
+ 22,
30072
+ 36,
30073
+ 52,
30074
+ 225,
30075
+ 37,
30076
+ 241,
30077
+ 23,
30078
+ 24,
30079
+ 25,
30080
+ 26,
30081
+ 38,
30082
+ 39,
30083
+ 40,
30084
+ 41,
30085
+ 42,
30086
+ 53,
30087
+ 54,
30088
+ 55,
30089
+ 56,
30090
+ 57,
30091
+ 58,
30092
+ 67,
30093
+ 68,
30094
+ 69,
30095
+ 70,
30096
+ 71,
30097
+ 72,
30098
+ 73,
30099
+ 74,
30100
+ 83,
30101
+ 84,
30102
+ 85,
30103
+ 86,
30104
+ 87,
30105
+ 88,
30106
+ 89,
30107
+ 90,
30108
+ 99,
30109
+ 100,
30110
+ 101,
30111
+ 102,
30112
+ 103,
30113
+ 104,
30114
+ 105,
30115
+ 106,
30116
+ 115,
30117
+ 116,
30118
+ 117,
30119
+ 118,
30120
+ 119,
30121
+ 120,
30122
+ 121,
30123
+ 122,
30124
+ 130,
30125
+ 131,
30126
+ 132,
30127
+ 133,
30128
+ 134,
30129
+ 135,
30130
+ 136,
30131
+ 137,
30132
+ 138,
30133
+ 146,
30134
+ 147,
30135
+ 148,
30136
+ 149,
30137
+ 150,
30138
+ 151,
30139
+ 152,
30140
+ 153,
30141
+ 154,
30142
+ 162,
30143
+ 163,
30144
+ 164,
30145
+ 165,
30146
+ 166,
30147
+ 167,
30148
+ 168,
30149
+ 169,
30150
+ 170,
30151
+ 178,
30152
+ 179,
30153
+ 180,
30154
+ 181,
30155
+ 182,
30156
+ 183,
30157
+ 184,
30158
+ 185,
30159
+ 186,
30160
+ 194,
30161
+ 195,
30162
+ 196,
30163
+ 197,
30164
+ 198,
30165
+ 199,
30166
+ 200,
30167
+ 201,
30168
+ 202,
30169
+ 210,
30170
+ 211,
30171
+ 212,
30172
+ 213,
30173
+ 214,
30174
+ 215,
30175
+ 216,
30176
+ 217,
30177
+ 218,
30178
+ 226,
30179
+ 227,
30180
+ 228,
30181
+ 229,
30182
+ 230,
30183
+ 231,
30184
+ 232,
30185
+ 233,
30186
+ 234,
30187
+ 242,
30188
+ 243,
30189
+ 244,
30190
+ 245,
30191
+ 246,
30192
+ 247,
30193
+ 248,
30194
+ 249,
30195
+ 250
30196
+ ];
30197
+ var DC_VALUES = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
30198
+ var HUFFMAN = [
30199
+ [0, [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], DC_VALUES],
30200
+ [16, [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125], AC_LUMA_VALUES],
30201
+ [1, [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], DC_VALUES],
30202
+ [17, [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119], AC_CHROMA_VALUES]
30203
+ ];
30204
+ var CODES = HUFFMAN.map(([, counts, values]) => {
30205
+ const table2 = [];
30206
+ let code = 0, at = 0;
30207
+ counts.forEach((count3, index) => {
30208
+ for (let i = 0; i < count3; i++) table2[values[at++]] = [code++, index + 1];
30209
+ code <<= 1;
30210
+ });
30211
+ return table2;
30212
+ });
30213
+ var AAN = [1, 1.387039845, 1.306562965, 1.175875602, 1, 0.785694958, 0.5411961, 0.275899379];
30214
+ function quantTables(quality) {
30215
+ const factor = quality < 50 ? 5e3 / quality : 200 - quality * 2;
30216
+ const scaled = (base) => base.map((value) => Math.min(255, Math.max(1, Math.floor((value * factor + 50) / 100))));
30217
+ const divisors = (table2) => Float64Array.from(table2, (value, k) => 1 / (value * AAN[k >> 3] * AAN[k & 7] * 8));
30218
+ const luma = scaled(LUMA_QUANT), chroma = scaled(CHROMA_QUANT);
30219
+ return { luma, chroma, lumaDivisors: divisors(luma), chromaDivisors: divisors(chroma) };
30220
+ }
30221
+ var BitWriter = class {
30222
+ buffer = Buffer.alloc(65536);
30223
+ length = 0;
30224
+ bits = 0;
30225
+ count = 0;
30226
+ byte(value) {
30227
+ if (this.length === this.buffer.length) {
30228
+ const next = Buffer.alloc(this.buffer.length * 2);
30229
+ this.buffer.copy(next);
30230
+ this.buffer = next;
30231
+ }
30232
+ this.buffer[this.length++] = value;
30233
+ }
30234
+ bytes(values) {
30235
+ for (const value of values) this.byte(value);
30236
+ }
30237
+ write(code, length) {
30238
+ this.bits = (this.bits << length | code) >>> 0;
30239
+ this.count += length;
30240
+ while (this.count >= 8) {
30241
+ const value = this.bits >>> this.count - 8 & 255;
30242
+ this.byte(value);
30243
+ if (value === 255) this.byte(0);
30244
+ this.count -= 8;
30245
+ this.bits &= (1 << this.count) - 1;
30246
+ }
30247
+ }
30248
+ flush() {
30249
+ if (this.count > 0) this.write((1 << 8 - this.count) - 1, 8 - this.count);
30250
+ }
30251
+ result() {
30252
+ return Buffer.from(this.buffer.subarray(0, this.length));
30253
+ }
30254
+ };
30255
+ function transform2(block, divisors, out) {
30256
+ for (let pass = 0; pass < 2; pass++) for (let i = 0; i < 8; i++) {
30257
+ const step = pass ? 8 : 1, base = pass ? i : i * 8, at = (k) => base + k * step;
30258
+ 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)];
30259
+ 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;
30260
+ const t10 = t0 + t3, t13 = t0 - t3, t11 = t1 + t2, t12 = t1 - t2;
30261
+ block[at(0)] = t10 + t11;
30262
+ block[at(4)] = t10 - t11;
30263
+ const z1 = (t12 + t13) * 0.707106781;
30264
+ block[at(2)] = t13 + z1;
30265
+ block[at(6)] = t13 - z1;
30266
+ const o10 = t4 + t5, o11 = t5 + t6, o12 = t6 + t7;
30267
+ const z5 = (o10 - o12) * 0.382683433, z2 = 0.5411961 * o10 + z5, z4 = 1.306562965 * o12 + z5, z3 = o11 * 0.707106781;
30268
+ const z11 = t7 + z3, z13 = t7 - z3;
30269
+ block[at(5)] = z13 + z2;
30270
+ block[at(3)] = z13 - z2;
30271
+ block[at(1)] = z11 + z4;
30272
+ block[at(7)] = z11 - z4;
30273
+ }
30274
+ for (let k = 0; k < 64; k++) out[ZIGZAG[k]] = Math.round(block[k] * divisors[k]);
30275
+ }
30276
+ function magnitude(value) {
30277
+ const absolute2 = Math.abs(value);
30278
+ let length = 0;
30279
+ while (absolute2 >> length) length++;
30280
+ return [value < 0 ? value + (1 << length) - 1 : value, length];
30281
+ }
30282
+ function encodeJpeg(image, quality) {
30283
+ const { width, height, rgb } = image, tables = quantTables(Math.min(100, Math.max(1, Math.round(quality))));
30284
+ const out = new BitWriter(), word = (value) => [value >> 8, value & 255];
30285
+ out.bytes([255, 216, 255, 224, 0, 16, 74, 70, 73, 70, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]);
30286
+ out.bytes([255, 219, 0, 132]);
30287
+ for (const [id2, table2] of [[0, tables.luma], [1, tables.chroma]]) {
30288
+ const zig = new Array(64);
30289
+ table2.forEach((value, k) => {
30290
+ zig[ZIGZAG[k]] = value;
30291
+ });
30292
+ out.bytes([id2, ...zig]);
30293
+ }
30294
+ out.bytes([255, 192, 0, 17, 8, ...word(height), ...word(width), 3, 1, 34, 0, 2, 17, 1, 3, 17, 1]);
30295
+ out.bytes([255, 196, ...word(2 + HUFFMAN.reduce((sum, [, , values]) => sum + 17 + values.length, 0))]);
30296
+ for (const [id2, counts, values] of HUFFMAN) out.bytes([id2, ...counts, ...values]);
30297
+ out.bytes([255, 218, 0, 12, 3, 1, 0, 2, 17, 3, 17, 0, 63, 0]);
30298
+ const block = new Float64Array(64), coefficients = new Int32Array(64), dc = [0, 0, 0];
30299
+ const Y = new Float64Array(256), Cb = new Float64Array(256), Cr = new Float64Array(256);
30300
+ const encode5 = (component, divisors) => {
30301
+ transform2(block, divisors, coefficients);
30302
+ const dcCodes = CODES[component ? 2 : 0], acCodes = CODES[component ? 3 : 1];
30303
+ const diff = coefficients[0] - dc[component];
30304
+ dc[component] = coefficients[0];
30305
+ const [bits, size] = magnitude(diff);
30306
+ out.write(...dcCodes[size]);
30307
+ if (size) out.write(bits, size);
30308
+ let last = 63;
30309
+ while (last > 0 && coefficients[last] === 0) last--;
30310
+ for (let k = 1, zeros = 0; k <= last; k++) {
30311
+ if (coefficients[k] === 0) {
30312
+ zeros++;
30313
+ continue;
30314
+ }
30315
+ while (zeros >= 16) {
30316
+ out.write(...acCodes[240]);
30317
+ zeros -= 16;
30318
+ }
30319
+ const [value, length] = magnitude(coefficients[k]);
30320
+ out.write(...acCodes[(zeros << 4) + length]);
30321
+ out.write(value, length);
30322
+ zeros = 0;
30323
+ }
30324
+ if (last < 63) out.write(...acCodes[0]);
30325
+ };
30326
+ for (let my = 0; my < height; my += 16) for (let mx = 0; mx < width; mx += 16) {
30327
+ for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) {
30328
+ 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];
30329
+ Y[y * 16 + x] = 0.299 * r + 0.587 * g + 0.114 * b - 128;
30330
+ Cb[y * 16 + x] = -0.168736 * r - 0.331264 * g + 0.5 * b;
30331
+ Cr[y * 16 + x] = 0.5 * r - 0.418688 * g - 0.081312 * b;
30332
+ }
30333
+ for (const [ox, oy] of [[0, 0], [8, 0], [0, 8], [8, 8]]) {
30334
+ for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) block[y * 8 + x] = Y[(oy + y) * 16 + ox + x];
30335
+ encode5(0, tables.lumaDivisors);
30336
+ }
30337
+ for (const [component, plane] of [[1, Cb], [2, Cr]]) {
30338
+ for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) {
30339
+ const at = y * 32 + x * 2;
30340
+ block[y * 8 + x] = (plane[at] + plane[at + 1] + plane[at + 16] + plane[at + 17]) / 4;
30341
+ }
30342
+ encode5(component, tables.chromaDivisors);
30343
+ }
30344
+ }
30345
+ out.flush();
30346
+ out.bytes([255, 217]);
30347
+ return out.result();
30348
+ }
30349
+ function fitJpeg(image, maxEdge, maxBytes) {
30350
+ for (const edge of [maxEdge, 1280, 1024, 800, 640]) {
30351
+ const scaled = downscale(image, edge);
30352
+ for (const quality of [75, 60, 45, 35]) {
30353
+ const data = encodeJpeg(scaled, quality);
30354
+ if (data.length <= maxBytes) return { data, width: scaled.width, height: scaled.height };
30355
+ }
30356
+ }
30357
+ return null;
30358
+ }
30359
+
30360
+ // agent/src/screen-capture.ts
29359
30361
  var SCREENSHOT_MAX_JPEG_BYTES = 131072;
29360
30362
  var SCREENSHOT_MAX_EDGE = 1568;
29361
30363
  function screenshotEnabled(env = process.env) {
29362
30364
  return env.LC_SCREENSHOT_ENABLED === "true";
29363
30365
  }
29364
30366
  var SCREENSHOT_ACCEPTANCE_FILE = "screenshot-acceptance-enabled";
30367
+ var SCREENSHOT_OWNER_OFF_FILE = "screenshot-disabled-by-owner";
29365
30368
  var ScreenCaptureError = class extends Error {
29366
- constructor(code) {
30369
+ constructor(code, detail) {
29367
30370
  super(code);
29368
30371
  this.code = code;
30372
+ this.detail = detail;
29369
30373
  this.name = "ScreenCaptureError";
29370
30374
  }
29371
30375
  code;
30376
+ detail;
29372
30377
  };
29373
30378
  var KNOWN = /^(SCREEN_UNAVAILABLE|SCREEN_LOCKED|SCREEN_ENCODER_UNAVAILABLE|SCREENSHOT_TOO_LARGE|ARGUMENT_INVALID)$/;
29374
30379
  function jpegSize(data) {
@@ -29384,12 +30389,12 @@ function jpegSize(data) {
29384
30389
  }
29385
30390
  return null;
29386
30391
  }
29387
- function run(file2, args, signal, maxBuffer = 65536) {
30392
+ function run(file2, args, signal, maxBuffer = 65536, env = buildChildEnvironment(process.env, process.platform)) {
29388
30393
  return new Promise((resolve, reject) => {
29389
30394
  execFile4(
29390
30395
  file2,
29391
30396
  args,
29392
- { encoding: "buffer", timeout: 15e3, maxBuffer, windowsHide: true, shell: false, env: buildChildEnvironment(process.env, process.platform), signal },
30397
+ { encoding: "buffer", timeout: 15e3, maxBuffer, windowsHide: true, shell: false, env, signal },
29393
30398
  (error62, stdout, stderr) => error62 ? reject(Object.assign(error62, { stdout, stderr })) : resolve({ stdout, stderr })
29394
30399
  );
29395
30400
  });
@@ -29454,11 +30459,141 @@ async function mac3(signal) {
29454
30459
  });
29455
30460
  }
29456
30461
  }
30462
+ var SESSION_KEYS = ["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "XDG_SESSION_TYPE", "XDG_CURRENT_DESKTOP"];
30463
+ var SESSION_VALUE = /^[A-Za-z0-9_.:,;=@+/-]{1,256}$/;
30464
+ var LINUX_SOURCE_BYTES = 150994944;
30465
+ async function linuxTool(name2) {
30466
+ for (const directory of ["/usr/bin", "/bin", "/usr/local/bin"]) {
30467
+ const file2 = path17.posix.join(directory, name2);
30468
+ try {
30469
+ await access3(file2, constants7.X_OK);
30470
+ return file2;
30471
+ } catch {
30472
+ }
30473
+ }
30474
+ return null;
30475
+ }
30476
+ async function linuxSession(signal) {
30477
+ const session = {}, uid = process.getuid?.();
30478
+ const take = (key, value) => {
30479
+ if (value && !session[key] && SESSION_VALUE.test(value)) session[key] = value;
30480
+ };
30481
+ const base = buildChildEnvironment(process.env, "linux");
30482
+ for (const key of SESSION_KEYS) take(key, process.env[key]);
30483
+ if (!session.DISPLAY && !session.WAYLAND_DISPLAY) {
30484
+ const systemctl = await linuxTool("systemctl");
30485
+ if (systemctl) try {
30486
+ const { stdout } = await run(systemctl, ["--user", "show-environment"], signal, 262144, base);
30487
+ for (const line of stdout.toString("utf8").split("\n")) {
30488
+ const at = line.indexOf("=");
30489
+ if (at > 0 && SESSION_KEYS.includes(line.slice(0, at))) take(line.slice(0, at), line.slice(at + 1));
30490
+ }
30491
+ } catch {
30492
+ if (signal.aborted) throw new ScreenCaptureError("CANCELLED");
30493
+ }
30494
+ }
30495
+ if (uid !== void 0) take("XDG_RUNTIME_DIR", "/run/user/" + uid);
30496
+ if (!session.DISPLAY && !session.WAYLAND_DISPLAY) {
30497
+ if (session.XDG_RUNTIME_DIR) for (const name2 of ["wayland-0", "wayland-1"]) {
30498
+ const socket = await lstat7(path17.posix.join(session.XDG_RUNTIME_DIR, name2)).catch(() => null);
30499
+ if (socket?.isSocket() && socket.uid === uid) {
30500
+ session.WAYLAND_DISPLAY = name2;
30501
+ break;
30502
+ }
30503
+ }
30504
+ if (!session.WAYLAND_DISPLAY) {
30505
+ const servers = [];
30506
+ for (const name2 of await readdir4("/tmp/.X11-unix").catch(() => [])) {
30507
+ const n = /^X(\d{1,4})$/.exec(name2)?.[1], socket = n ? await lstat7("/tmp/.X11-unix/" + name2).catch(() => null) : null;
30508
+ if (n && socket?.isSocket()) servers.push({ n: Number(n), own: socket.uid === uid });
30509
+ }
30510
+ const server = servers.sort((a, b) => Number(b.own) - Number(a.own) || a.n - b.n)[0];
30511
+ if (server) session.DISPLAY = ":" + server.n;
30512
+ }
30513
+ }
30514
+ if (session.DISPLAY && !session.XAUTHORITY) {
30515
+ const file2 = path17.posix.join(os4.homedir(), ".Xauthority");
30516
+ if ((await lstat7(file2).catch(() => null))?.isFile()) take("XAUTHORITY", file2);
30517
+ }
30518
+ if (session.XDG_RUNTIME_DIR) take("DBUS_SESSION_BUS_ADDRESS", "unix:path=" + session.XDG_RUNTIME_DIR + "/bus");
30519
+ const wayland = !!session.WAYLAND_DISPLAY || session.XDG_SESSION_TYPE === "wayland";
30520
+ return { env: { ...base, ...session }, wayland, x11: !wayland && !!session.DISPLAY };
30521
+ }
30522
+ async function busSocket(env) {
30523
+ const socket = sessionBusSocket(env.DBUS_SESSION_BUS_ADDRESS);
30524
+ if (!socket || socket.startsWith("\0")) return socket;
30525
+ return (await lstat7(socket).catch(() => null))?.isSocket() ? socket : null;
30526
+ }
30527
+ async function portalCapture(socket, signal) {
30528
+ const token = "lc" + randomBytes6(8).toString("hex"), started = Date.now(), uid = process.getuid?.();
30529
+ if (uid === void 0) throw new ScreenCaptureError("SCREEN_UNAVAILABLE");
30530
+ let answer;
30531
+ try {
30532
+ answer = await portalScreenshot(socket, uid, token, AbortSignal.any([signal, AbortSignal.timeout(3e4)]));
30533
+ } catch {
30534
+ throw new ScreenCaptureError(signal.aborted ? "CANCELLED" : "SCREEN_UNAVAILABLE");
30535
+ }
30536
+ const { code, uri } = answer;
30537
+ if (code === 1) throw new ScreenCaptureError("SCREEN_RECORDING_PERMISSION_REQUIRED");
30538
+ if (code !== 0 || !uri?.startsWith("file://")) throw new ScreenCaptureError("SCREEN_UNAVAILABLE");
30539
+ const file2 = decodeURIComponent(new URL(uri).pathname), info = await lstat7(file2);
30540
+ const fresh = info.isFile() && info.uid === uid && info.mtimeMs >= started - 5e3;
30541
+ try {
30542
+ if (!fresh || info.size > LINUX_SOURCE_BYTES) throw new ScreenCaptureError("SCREEN_UNAVAILABLE");
30543
+ return await readFile6(file2);
30544
+ } finally {
30545
+ if (fresh) await unlink2(file2).catch(() => {
30546
+ });
30547
+ }
30548
+ }
30549
+ async function linux(signal) {
30550
+ const session = await linuxSession(signal);
30551
+ if (!session.wayland && !session.x11) throw new ScreenCaptureError("SCREENSHOT_UNSUPPORTED", { reason: "NO_DISPLAY" });
30552
+ const output2 = (args) => async (tool) => (await run(tool, args, signal, LINUX_SOURCE_BYTES, session.env)).stdout;
30553
+ const portal = (socket) => portalCapture(socket, signal);
30554
+ const methods = session.wayland ? [["grim", "grim", output2(["-t", "png", "-"])], ["portal", "", portal]] : [
30555
+ ["xwd", "xwd", output2(["-root", "-silent"])],
30556
+ ["import", "import", output2(["-silent", "-window", "root", "png:-"])],
30557
+ ["maim", "maim", output2(["-f", "png"])],
30558
+ ["portal", "", portal]
30559
+ ];
30560
+ const tried = [];
30561
+ for (const [name2, program, capture2] of methods) {
30562
+ const tool = program ? await linuxTool(program) : await busSocket(session.env);
30563
+ if (!tool) {
30564
+ tried.push(name2 + ":missing");
30565
+ continue;
30566
+ }
30567
+ let image;
30568
+ try {
30569
+ const source = await capture2(tool);
30570
+ image = decodePng(source) ?? decodeXwd(source);
30571
+ } catch (error62) {
30572
+ if (signal.aborted) throw new ScreenCaptureError("CANCELLED");
30573
+ if (error62 instanceof ScreenCaptureError && error62.code === "SCREEN_RECORDING_PERMISSION_REQUIRED") throw error62;
30574
+ tried.push(name2 + ":failed");
30575
+ continue;
30576
+ }
30577
+ if (!image) {
30578
+ tried.push(name2 + ":unreadable");
30579
+ continue;
30580
+ }
30581
+ const fitted = fitJpeg(image, SCREENSHOT_MAX_EDGE, SCREENSHOT_MAX_JPEG_BYTES);
30582
+ if (!fitted) throw new ScreenCaptureError("SCREENSHOT_TOO_LARGE");
30583
+ return { ...fitted, sourceWidth: image.width, sourceHeight: image.height };
30584
+ }
30585
+ throw new ScreenCaptureError("SCREENSHOT_UNSUPPORTED", {
30586
+ reason: tried.every((entry) => entry.endsWith(":missing")) ? "NO_CAPTURE_TOOL" : "CAPTURE_FAILED",
30587
+ session: session.wayland ? "wayland" : "x11",
30588
+ tried
30589
+ });
30590
+ }
29457
30591
  async function captureScreen(options) {
29458
30592
  if (options.signal.aborted) throw new ScreenCaptureError("CANCELLED");
29459
30593
  if (process.platform === "win32") return windows(options.ownerBridgePath, options.signal);
29460
30594
  if (process.platform === "darwin") return mac3(options.signal);
29461
- throw new ScreenCaptureError("SCREENSHOT_UNSUPPORTED");
30595
+ if (process.platform === "linux") return linux(options.signal);
30596
+ throw new ScreenCaptureError("SCREENSHOT_UNSUPPORTED", { reason: "PLATFORM_UNSUPPORTED" });
29462
30597
  }
29463
30598
 
29464
30599
  // agent/src/tools.ts
@@ -29491,7 +30626,7 @@ function stopped(signal) {
29491
30626
  if (signal.aborted) fail3("CANCELLED");
29492
30627
  }
29493
30628
  async function readBoundedFile(file2, maxBytes, bridge, signal) {
29494
- const stat2 = await lstat7(file2);
30629
+ const stat2 = await lstat8(file2);
29495
30630
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > maxBytes) fail3("FILE_UNSUPPORTED_OR_TOO_LARGE");
29496
30631
  if (process.platform === "win32") {
29497
30632
  if (maxBytes <= 1048576 || stat2.size <= 1048576) return readWindowsFile(bridge, file2, Math.min(maxBytes, 1048576), signal);
@@ -29499,7 +30634,7 @@ async function readBoundedFile(file2, maxBytes, bridge, signal) {
29499
30634
  if (read.truncated) fail3("FILE_UNSUPPORTED_OR_TOO_LARGE");
29500
30635
  return read.data;
29501
30636
  }
29502
- const handle = await open6(file2, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0));
30637
+ const handle = await open6(file2, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
29503
30638
  try {
29504
30639
  const current2 = await handle.stat();
29505
30640
  if (!current2.isFile() || current2.size > maxBytes) fail3("FILE_UNSUPPORTED_OR_TOO_LARGE");
@@ -29754,7 +30889,7 @@ var NativeTools = class {
29754
30889
  }
29755
30890
  if (bytes3.length > MAX_FILE_WRITE_BYTES) fail3("FILE_WRITE_LIMIT");
29756
30891
  const temp = path18.join(path18.dirname(target), ".lc-write-" + randomUUID7() + ".tmp");
29757
- const handle = await open6(temp, constants7.O_CREAT | constants7.O_EXCL | constants7.O_WRONLY, 384);
30892
+ const handle = await open6(temp, constants8.O_CREAT | constants8.O_EXCL | constants8.O_WRONLY, 384);
29758
30893
  try {
29759
30894
  await handle.writeFile(bytes3);
29760
30895
  await handle.sync();
@@ -29770,7 +30905,7 @@ var NativeTools = class {
29770
30905
  break;
29771
30906
  } catch (error62) {
29772
30907
  if (process.platform !== "win32" || !["EPERM", "EBUSY", "EACCES"].includes(error62.code ?? "")) throw error62;
29773
- if (attempt === 4) fail3((await lstat7(target)).mode & 128 ? "FILE_IN_USE" : "FILE_READ_ONLY");
30908
+ if (attempt === 4) fail3((await lstat8(target)).mode & 128 ? "FILE_IN_USE" : "FILE_READ_ONLY");
29774
30909
  await delay2(50 << attempt);
29775
30910
  stopped(signal);
29776
30911
  }
@@ -29886,14 +31021,26 @@ var NativeTools = class {
29886
31021
  } };
29887
31022
  }
29888
31023
  if (call.name === "take_screenshot") {
29889
- if (!screenshotEnabled() && !await lstat7(path18.join(this.options.stateDirectory, SCREENSHOT_ACCEPTANCE_FILE)).then((s) => s.isFile(), () => false)) fail3("SCREENSHOT_DISABLED");
31024
+ if (!screenshotEnabled() && !await lstat8(path18.join(this.options.stateDirectory, SCREENSHOT_ACCEPTANCE_FILE)).then((s) => s.isFile(), () => false)) fail3("SCREENSHOT_DISABLED");
29890
31025
  if (!workspace2.fullAccess) fail3("FULL_ACCESS_REQUIRED");
31026
+ if (await lstat8(path18.join(this.options.stateDirectory, SCREENSHOT_OWNER_OFF_FILE)).then(() => true, (error62) => error62.code !== "ENOENT")) fail3("SCREENSHOT_DISABLED_BY_OWNER");
29891
31027
  const bridge = this.options.ownerBridgePath ?? path18.join(path18.dirname(this.options.helperPath), "OwnerBridge.exe");
29892
31028
  return { call, claims: [{ path: path18.join(this.options.stateDirectory, "screen-capture"), mode: "read" }], run: async (signal) => {
29893
31029
  let shot;
29894
31030
  try {
29895
31031
  shot = await captureScreen({ ownerBridgePath: bridge, signal });
29896
31032
  } catch (error62) {
31033
+ if (error62 instanceof ScreenCaptureError && error62.detail) return {
31034
+ exitCode: 1,
31035
+ timedOut: false,
31036
+ cancelled: false,
31037
+ treeTerminated: true,
31038
+ stdout: JSON.stringify({ type: "screenshot_error", resultCode: error62.code, ...error62.detail }),
31039
+ stderr: "",
31040
+ stdoutTruncated: false,
31041
+ stderrTruncated: false,
31042
+ resultCode: error62.code
31043
+ };
29897
31044
  fail3(error62 instanceof Error && /^[A-Z_]{1,40}$/.test(error62.message) ? error62.message : "SCREEN_UNAVAILABLE");
29898
31045
  }
29899
31046
  return result({
@@ -30057,7 +31204,7 @@ var NativeTools = class {
30057
31204
  )?.file : void 0);
30058
31205
  if (!candidate || !path18.isAbsolute(candidate)) fail3("COMMAND_NOT_FOUND");
30059
31206
  const executable = await realpath7(candidate).catch(() => fail3("COMMAND_NOT_FOUND"));
30060
- if (!(await lstat7(executable)).isFile()) fail3("COMMAND_NOT_FOUND");
31207
+ if (!(await lstat8(executable)).isFile()) fail3("COMMAND_NOT_FOUND");
30061
31208
  if (denied.has(commandKey(executable))) fail3("COMMAND_NOT_ALLOWED");
30062
31209
  for (const key of workspace2.deniedCommands ?? []) {
30063
31210
  const configured = this.options.programs[key]?.executable;
@@ -30099,7 +31246,7 @@ var NativeTools = class {
30099
31246
  const candidate = process.platform === "win32" ? source : await resolvePosixExecutable(source);
30100
31247
  if (!candidate) continue;
30101
31248
  try {
30102
- const stat2 = await lstat7(candidate);
31249
+ const stat2 = await lstat8(candidate);
30103
31250
  if (!stat2.isFile() || stat2.isSymbolicLink() || !equalPath3(candidate, await realpath7(candidate))) continue;
30104
31251
  } catch {
30105
31252
  continue;
@@ -30117,7 +31264,7 @@ var NativeTools = class {
30117
31264
  const current2 = queue.shift();
30118
31265
  let names;
30119
31266
  try {
30120
- names = await readdir4(current2.path, { withFileTypes: true });
31267
+ names = await readdir5(current2.path, { withFileTypes: true });
30121
31268
  } catch (error62) {
30122
31269
  if (current2.level === 0) throw error62;
30123
31270
  continue;
@@ -30142,7 +31289,7 @@ var NativeTools = class {
30142
31289
  entries.push({ path: path18.relative(root, resolved), type: "directory" });
30143
31290
  if (current2.level < depth) queue.push({ path: resolved, level: current2.level + 1 });
30144
31291
  } else if (item.isFile()) {
30145
- const stat2 = await lstat7(resolved).catch(() => null);
31292
+ const stat2 = await lstat8(resolved).catch(() => null);
30146
31293
  if (stat2) entries.push({ path: path18.relative(root, resolved), type: "file", size: stat2.size });
30147
31294
  }
30148
31295
  }
@@ -30155,7 +31302,7 @@ var NativeTools = class {
30155
31302
  while (guard.isWithin(directory, workspace2.root)) {
30156
31303
  const dotGit = path18.join(directory, ".git");
30157
31304
  try {
30158
- const stat2 = await lstat7(dotGit);
31305
+ const stat2 = await lstat8(dotGit);
30159
31306
  if (stat2.isSymbolicLink()) fail3("GIT_METADATA_CHANGED");
30160
31307
  let gitDir;
30161
31308
  if (stat2.isDirectory()) gitDir = await realpath7(dotGit);
@@ -30173,7 +31320,7 @@ var NativeTools = class {
30173
31320
  } catch (e) {
30174
31321
  if (e.code !== "ENOENT") throw e;
30175
31322
  }
30176
- if (!(await lstat7(common)).isDirectory() || guard.isWithin(common, this.options.stateDirectory)) fail3("GIT_METADATA_CHANGED");
31323
+ if (!(await lstat8(common)).isDirectory() || guard.isWithin(common, this.options.stateDirectory)) fail3("GIT_METADATA_CHANGED");
30177
31324
  if (!guard.isWithin(common, workspace2.root) && (!workspace2.gitCommonDir || !equalPath3(common, workspace2.gitCommonDir))) fail3("GIT_COMMON_DIRECTORY_NOT_APPROVED");
30178
31325
  return common;
30179
31326
  } catch (e) {
@@ -30929,7 +32076,45 @@ function journalBinding(entry, binding2) {
30929
32076
  function journalResult(value, code) {
30930
32077
  return { ...value, resultCode: code ?? (value.treeTerminated ? value.cancelled ? "CANCELLED" : value.timedOut ? "TIMEOUT" : value.exitCode === 0 ? "SUCCESS" : "USER_PROGRAM_FAILED" : "EXECUTION_UNKNOWN") };
30931
32078
  }
30932
- 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"]);
32079
+ var knownCodes = /* @__PURE__ */ new Set([
32080
+ "PROJECT_IDENTITY_UNKNOWN",
32081
+ "PROJECT_IDENTITY_MISMATCH",
32082
+ "INVALID_TOOL_ARGUMENTS",
32083
+ "LOCAL_PERMISSION_REQUIRED",
32084
+ "PATH_NOT_ALLOWED",
32085
+ "FILE_CHANGED",
32086
+ "FILE_NOT_FOUND",
32087
+ "FILE_ALREADY_EXISTS",
32088
+ "REPLACEMENT_NOT_UNIQUE",
32089
+ "OUTPUT_LIMIT_EXCEEDED",
32090
+ "BINARY_FILE_NOT_SUPPORTED",
32091
+ "FILE_UNSUPPORTED_OR_TOO_LARGE",
32092
+ "INVALID_LINE_RANGE",
32093
+ "FILE_IN_USE",
32094
+ "FILE_READ_ONLY",
32095
+ "FILE_WRITE_LIMIT",
32096
+ "GIT_METADATA_CHANGED",
32097
+ "GIT_COMMON_DIRECTORY_NOT_APPROVED",
32098
+ "GIT_NOT_INSTALLED",
32099
+ "LOCALHOST_NOT_ALLOWED",
32100
+ "COMMAND_NOT_ALLOWED",
32101
+ "WORKSPACE_CHANGED",
32102
+ "WORKSPACE_UNAVAILABLE",
32103
+ "RESOURCE_BUSY",
32104
+ "AGENT_PAUSED",
32105
+ "CANCELLED_BEFORE_ACCEPTANCE",
32106
+ "ADMISSION_DEADLINE_EXPIRED",
32107
+ // take_screenshot refusals (#434, #486): without these the client sees TOOL_FAILED.
32108
+ "FULL_ACCESS_REQUIRED",
32109
+ "SCREENSHOT_DISABLED",
32110
+ "SCREENSHOT_DISABLED_BY_OWNER",
32111
+ "SCREENSHOT_UNSUPPORTED",
32112
+ "SCREENSHOT_TOO_LARGE",
32113
+ "SCREEN_UNAVAILABLE",
32114
+ "SCREEN_LOCKED",
32115
+ "SCREEN_ENCODER_UNAVAILABLE",
32116
+ "SCREEN_RECORDING_PERMISSION_REQUIRED"
32117
+ ]);
30933
32118
  function safeCode(error62) {
30934
32119
  const code = error62 instanceof NativeToolError ? error62.code : error62 instanceof Error ? error62.message : "";
30935
32120
  return knownCodes.has(code) || /^GUARD_[A-Z_]{1,30}$/.test(code) ? code : "TOOL_FAILED";
@@ -31362,9 +32547,9 @@ var NativeRelayBridge = class {
31362
32547
  };
31363
32548
 
31364
32549
  // agent/src/local-direct.ts
31365
- import net from "node:net";
32550
+ import net2 from "node:net";
31366
32551
  import path20 from "node:path";
31367
- import { createHmac as createHmac2, hkdfSync, randomBytes as randomBytes6, randomUUID as randomUUID8, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
32552
+ import { createHmac as createHmac2, hkdfSync, randomBytes as randomBytes7, randomUUID as randomUUID8, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
31368
32553
  import { mkdir as mkdir7, readFile as readFile8, rename as rename5, rm as rm7, writeFile as writeFile3 } from "node:fs/promises";
31369
32554
  var LocalDirectError = class extends Error {
31370
32555
  constructor(code) {
@@ -31401,7 +32586,7 @@ function sameProof(candidate, expected) {
31401
32586
  const a = Buffer.from(candidate), b = Buffer.from(expected);
31402
32587
  return a.length === b.length && timingSafeEqual3(a, b);
31403
32588
  }
31404
- var nonce = () => randomBytes6(32).toString("base64url");
32589
+ var nonce = () => randomBytes7(32).toString("base64url");
31405
32590
  var NONCE = /^[A-Za-z0-9_-]{43}$/;
31406
32591
  function codeOf(error62) {
31407
32592
  const code = error62 instanceof NativeToolError || error62 instanceof LocalDirectError ? error62.code : error62 instanceof Error ? error62.message : "";
@@ -31483,7 +32668,7 @@ var LocalDirectServer = class _LocalDirectServer {
31483
32668
  });
31484
32669
  return null;
31485
32670
  }
31486
- const server = net.createServer(), self = new _LocalDirectServer(server, options);
32671
+ const server = net2.createServer(), self = new _LocalDirectServer(server, options);
31487
32672
  server.on("connection", (socket) => self.accept(socket));
31488
32673
  await new Promise((resolve, reject) => {
31489
32674
  server.once("error", reject);
@@ -31640,7 +32825,7 @@ var LocalDirectClient = class _LocalDirectClient {
31640
32825
  static async connect(options) {
31641
32826
  if (!await localDirectEnabled(options.directory)) fail4("LOCAL_ACCESS_DISABLED");
31642
32827
  const endpoint2 = await readEndpoint(options.directory);
31643
- const socket = net.createConnection({ host: "127.0.0.1", port: endpoint2.port });
32828
+ const socket = net2.createConnection({ host: "127.0.0.1", port: endpoint2.port });
31644
32829
  let handler = () => {
31645
32830
  };
31646
32831
  const lines = new Lines(socket, (frame) => handler(frame));
@@ -37163,8 +38348,8 @@ var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => {
37163
38348
  var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
37164
38349
  var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
37165
38350
  var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
37166
- exports.parse = parse3;
37167
- function parse3(string4) {
38351
+ exports.parse = parse4;
38352
+ function parse4(string4) {
37168
38353
  if (!string4) throw new TypeError("argument string is required");
37169
38354
  var header = typeof string4 === "object" ? getcontenttype(string4) : string4;
37170
38355
  if (typeof header !== "string") throw new TypeError("argument string is required to be a string");
@@ -37688,9 +38873,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37688
38873
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
37689
38874
  return `${varKind} ${this.name}${rhs};` + _n;
37690
38875
  }
37691
- optimizeNames(names, constants10) {
38876
+ optimizeNames(names, constants11) {
37692
38877
  if (!names[this.name.str]) return;
37693
- if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants10);
38878
+ if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants11);
37694
38879
  return this;
37695
38880
  }
37696
38881
  get names() {
@@ -37707,9 +38892,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37707
38892
  render({ _n }) {
37708
38893
  return `${this.lhs} = ${this.rhs};` + _n;
37709
38894
  }
37710
- optimizeNames(names, constants10) {
38895
+ optimizeNames(names, constants11) {
37711
38896
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return;
37712
- this.rhs = optimizeExpr(this.rhs, names, constants10);
38897
+ this.rhs = optimizeExpr(this.rhs, names, constants11);
37713
38898
  return this;
37714
38899
  }
37715
38900
  get names() {
@@ -37768,8 +38953,8 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37768
38953
  optimizeNodes() {
37769
38954
  return `${this.code}` ? this : void 0;
37770
38955
  }
37771
- optimizeNames(names, constants10) {
37772
- this.code = optimizeExpr(this.code, names, constants10);
38956
+ optimizeNames(names, constants11) {
38957
+ this.code = optimizeExpr(this.code, names, constants11);
37773
38958
  return this;
37774
38959
  }
37775
38960
  get names() {
@@ -37795,12 +38980,12 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37795
38980
  }
37796
38981
  return nodes.length > 0 ? this : void 0;
37797
38982
  }
37798
- optimizeNames(names, constants10) {
38983
+ optimizeNames(names, constants11) {
37799
38984
  const { nodes } = this;
37800
38985
  let i = nodes.length;
37801
38986
  while (i--) {
37802
38987
  const n = nodes[i];
37803
- if (n.optimizeNames(names, constants10)) continue;
38988
+ if (n.optimizeNames(names, constants11)) continue;
37804
38989
  subtractNames(names, n.names);
37805
38990
  nodes.splice(i, 1);
37806
38991
  }
@@ -37847,11 +39032,11 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37847
39032
  if (cond === false || !this.nodes.length) return void 0;
37848
39033
  return this;
37849
39034
  }
37850
- optimizeNames(names, constants10) {
39035
+ optimizeNames(names, constants11) {
37851
39036
  var _a3;
37852
- this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants10);
37853
- if (!(super.optimizeNames(names, constants10) || this.else)) return;
37854
- this.condition = optimizeExpr(this.condition, names, constants10);
39037
+ this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants11);
39038
+ if (!(super.optimizeNames(names, constants11) || this.else)) return;
39039
+ this.condition = optimizeExpr(this.condition, names, constants11);
37855
39040
  return this;
37856
39041
  }
37857
39042
  get names() {
@@ -37873,9 +39058,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37873
39058
  render(opts) {
37874
39059
  return `for(${this.iteration})` + super.render(opts);
37875
39060
  }
37876
- optimizeNames(names, constants10) {
37877
- if (!super.optimizeNames(names, constants10)) return;
37878
- this.iteration = optimizeExpr(this.iteration, names, constants10);
39061
+ optimizeNames(names, constants11) {
39062
+ if (!super.optimizeNames(names, constants11)) return;
39063
+ this.iteration = optimizeExpr(this.iteration, names, constants11);
37879
39064
  return this;
37880
39065
  }
37881
39066
  get names() {
@@ -37910,9 +39095,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37910
39095
  render(opts) {
37911
39096
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
37912
39097
  }
37913
- optimizeNames(names, constants10) {
37914
- if (!super.optimizeNames(names, constants10)) return;
37915
- this.iterable = optimizeExpr(this.iterable, names, constants10);
39098
+ optimizeNames(names, constants11) {
39099
+ if (!super.optimizeNames(names, constants11)) return;
39100
+ this.iterable = optimizeExpr(this.iterable, names, constants11);
37916
39101
  return this;
37917
39102
  }
37918
39103
  get names() {
@@ -37951,11 +39136,11 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37951
39136
  (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes();
37952
39137
  return this;
37953
39138
  }
37954
- optimizeNames(names, constants10) {
39139
+ optimizeNames(names, constants11) {
37955
39140
  var _a3, _b;
37956
- super.optimizeNames(names, constants10);
37957
- (_a3 = this.catch) === null || _a3 === void 0 || _a3.optimizeNames(names, constants10);
37958
- (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants10);
39141
+ super.optimizeNames(names, constants11);
39142
+ (_a3 = this.catch) === null || _a3 === void 0 || _a3.optimizeNames(names, constants11);
39143
+ (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants11);
37959
39144
  return this;
37960
39145
  }
37961
39146
  get names() {
@@ -38204,7 +39389,7 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
38204
39389
  function addExprNames(names, from) {
38205
39390
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
38206
39391
  }
38207
- function optimizeExpr(expr, names, constants10) {
39392
+ function optimizeExpr(expr, names, constants11) {
38208
39393
  if (expr instanceof code_1.Name) return replaceName(expr);
38209
39394
  if (!canOptimize(expr)) return expr;
38210
39395
  return new code_1._Code(expr._items.reduce((items, c) => {
@@ -38214,13 +39399,13 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
38214
39399
  return items;
38215
39400
  }, []));
38216
39401
  function replaceName(n) {
38217
- const c = constants10[n.str];
39402
+ const c = constants11[n.str];
38218
39403
  if (c === void 0 || names[n.str] !== 1) return n;
38219
39404
  delete names[n.str];
38220
39405
  return c;
38221
39406
  }
38222
39407
  function canOptimize(e) {
38223
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants10[c.str] !== void 0);
39408
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants11[c.str] !== void 0);
38224
39409
  }
38225
39410
  }
38226
39411
  function subtractNames(names, from) {
@@ -40352,21 +41537,21 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
40352
41537
  const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils();
40353
41538
  const { SCHEMES, getSchemeHandler } = require_schemes();
40354
41539
  function normalize(uri, options) {
40355
- if (typeof uri === "string") uri = serialize(parse3(uri, options), options);
40356
- else if (typeof uri === "object") uri = parse3(serialize(uri, options), options);
41540
+ if (typeof uri === "string") uri = serialize(parse4(uri, options), options);
41541
+ else if (typeof uri === "object") uri = parse4(serialize(uri, options), options);
40357
41542
  return uri;
40358
41543
  }
40359
41544
  function resolve(baseURI, relativeURI, options) {
40360
41545
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
40361
- const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true);
41546
+ const resolved = resolveComponent(parse4(baseURI, schemelessOptions), parse4(relativeURI, schemelessOptions), schemelessOptions, true);
40362
41547
  schemelessOptions.skipEscape = true;
40363
41548
  return serialize(resolved, schemelessOptions);
40364
41549
  }
40365
41550
  function resolveComponent(base, relative, options, skipNormalization) {
40366
41551
  const target = {};
40367
41552
  if (!skipNormalization) {
40368
- base = parse3(serialize(base, options), options);
40369
- relative = parse3(serialize(relative, options), options);
41553
+ base = parse4(serialize(base, options), options);
41554
+ relative = parse4(serialize(relative, options), options);
40370
41555
  }
40371
41556
  options = options || {};
40372
41557
  if (!options.tolerant && relative.scheme) {
@@ -40410,7 +41595,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
40410
41595
  function equal(uriA, uriB, options) {
40411
41596
  if (typeof uriA === "string") {
40412
41597
  uriA = unescape(uriA);
40413
- uriA = serialize(normalizeComponentEncoding(parse3(uriA, options), true), {
41598
+ uriA = serialize(normalizeComponentEncoding(parse4(uriA, options), true), {
40414
41599
  ...options,
40415
41600
  skipEscape: true
40416
41601
  });
@@ -40420,7 +41605,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
40420
41605
  });
40421
41606
  if (typeof uriB === "string") {
40422
41607
  uriB = unescape(uriB);
40423
- uriB = serialize(normalizeComponentEncoding(parse3(uriB, options), true), {
41608
+ uriB = serialize(normalizeComponentEncoding(parse4(uriB, options), true), {
40424
41609
  ...options,
40425
41610
  skipEscape: true
40426
41611
  });
@@ -40473,7 +41658,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
40473
41658
  return uriTokens.join("");
40474
41659
  }
40475
41660
  const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
40476
- function parse3(uri, opts) {
41661
+ function parse4(uri, opts) {
40477
41662
  const options = Object.assign({}, opts);
40478
41663
  const parsed = {
40479
41664
  scheme: void 0,
@@ -40534,7 +41719,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
40534
41719
  resolveComponent,
40535
41720
  equal,
40536
41721
  serialize,
40537
- parse: parse3
41722
+ parse: parse4
40538
41723
  };
40539
41724
  module.exports = fastUri;
40540
41725
  module.exports.default = fastUri;
@@ -45814,7 +46999,7 @@ var DESCRIPTIONS = {
45814
46999
  git_log: ["Recent Git commits of the repository at a workspace-relative path.", { readOnlyHint: true, openWorldHint: false }],
45815
47000
  project_snapshot: ["Compact project overview: Git state and, with startup, AGENTS.md policy and task continuation.", { readOnlyHint: true, openWorldHint: false }],
45816
47001
  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 }],
45817
- 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 }],
47002
+ 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 }],
45818
47003
  localhost_request: ["HTTP request to a service on this computer (localhost only).", { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }]
45819
47004
  };
45820
47005
  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.");
@@ -46336,6 +47521,7 @@ async function connectOnce(options) {
46336
47521
  const incidents = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes("incidentBatchV1");
46337
47522
  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;
46338
47523
  const nativeStatus = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(NATIVE_STATUS_CAPABILITY) && options.status;
47524
+ const accessModes = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(WORKSPACE_ACCESS_MODE_CAPABILITY);
46339
47525
  const reportStatus = () => {
46340
47526
  if (!nativeStatus) return;
46341
47527
  const { safeSlots, active, queued, paused } = nativeStatus();
@@ -46562,7 +47748,16 @@ async function connectOnce(options) {
46562
47748
  registerWorkspace: (workspace2) => {
46563
47749
  if (pendingWorkspace.size >= 32) return Promise.reject(new RelayClientError("RELAY_PENDING_LIMIT"));
46564
47750
  const requestId = randomUUID10();
46565
- const event = { type: "workspace_grant", version: 1, requestId, workspaceGrantId: workspace2.workspaceGrantId, rootHash: workspace2.rootHash, displayName: workspace2.displayName, policyVersion: workspace2.policyVersion };
47751
+ const event = {
47752
+ type: "workspace_grant",
47753
+ version: 1,
47754
+ requestId,
47755
+ workspaceGrantId: workspace2.workspaceGrantId,
47756
+ rootHash: workspace2.rootHash,
47757
+ displayName: workspace2.displayName,
47758
+ policyVersion: workspace2.policyVersion,
47759
+ ...accessModes ? { accessMode: workspace2.fullAccess === true ? "full" : "scoped" } : {}
47760
+ };
46566
47761
  return new Promise((resolve, reject) => {
46567
47762
  const timer = setTimeout(() => {
46568
47763
  pendingWorkspace.delete(requestId);
@@ -46611,14 +47806,14 @@ import { spawn as spawn5 } from "node:child_process";
46611
47806
  import { createHash as createHash16 } from "node:crypto";
46612
47807
  import os6 from "node:os";
46613
47808
  import { open as open7 } from "node:fs/promises";
46614
- import { constants as constants8 } from "node:fs";
47809
+ import { constants as constants9 } from "node:fs";
46615
47810
  import path21 from "node:path";
46616
47811
  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;
46617
47812
  async function readMachineGuid(timeoutMs2 = 5e3) {
46618
47813
  if (process.platform === "linux") {
46619
47814
  let handle;
46620
47815
  try {
46621
- handle = await open7("/etc/machine-id", constants8.O_RDONLY | constants8.O_NOFOLLOW);
47816
+ handle = await open7("/etc/machine-id", constants9.O_RDONLY | constants9.O_NOFOLLOW);
46622
47817
  const stat2 = await handle.stat();
46623
47818
  if (!stat2.isFile() || stat2.size > 128) return null;
46624
47819
  const data = Buffer.alloc(129);
@@ -46667,7 +47862,7 @@ async function readComputerName(timeoutMs2 = 5e3) {
46667
47862
  if (process.platform === "linux") {
46668
47863
  let handle;
46669
47864
  try {
46670
- handle = await open7("/etc/hostname", constants8.O_RDONLY | constants8.O_NOFOLLOW);
47865
+ handle = await open7("/etc/hostname", constants9.O_RDONLY | constants9.O_NOFOLLOW);
46671
47866
  const data = Buffer.alloc(257), { bytesRead } = await handle.read(data, 0, data.length, 0);
46672
47867
  const name2 = data.subarray(0, bytesRead).toString("utf8").trim();
46673
47868
  if (bytesRead <= 256 && valid(name2)) return name2;
@@ -47250,8 +48445,8 @@ async function deliverGuardEvidence(target, packet, options = {}) {
47250
48445
  }
47251
48446
 
47252
48447
  // agent/src/optimization-ledger.ts
47253
- import { constants as constants9 } from "node:fs";
47254
- import { lstat as lstat8, mkdir as mkdir8, open as open8, readFile as readFile9, realpath as realpath8 } from "node:fs/promises";
48448
+ import { constants as constants10 } from "node:fs";
48449
+ import { lstat as lstat9, mkdir as mkdir8, open as open8, readFile as readFile9, realpath as realpath8 } from "node:fs/promises";
47255
48450
  import path22 from "node:path";
47256
48451
  var MAX_LEDGER_BYTES = 64 * 1024 * 1024;
47257
48452
  var MAX_NOTICE_LEDGER_BYTES = 8 * 1024 * 1024;
@@ -47263,7 +48458,7 @@ async function safeDirectory2(directory) {
47263
48458
  let current2 = absolute2;
47264
48459
  for (; ; ) {
47265
48460
  try {
47266
- if ((await lstat8(current2)).isSymbolicLink()) throw failure5("OPTIMIZATION_LEDGER_DIRECTORY_INVALID");
48461
+ if ((await lstat9(current2)).isSymbolicLink()) throw failure5("OPTIMIZATION_LEDGER_DIRECTORY_INVALID");
47267
48462
  } catch (error62) {
47268
48463
  if (error62.code !== "ENOENT") throw error62;
47269
48464
  }
@@ -47272,7 +48467,7 @@ async function safeDirectory2(directory) {
47272
48467
  current2 = parent;
47273
48468
  }
47274
48469
  await mkdir8(absolute2, { recursive: true, mode: 448 });
47275
- const stat2 = await lstat8(absolute2);
48470
+ const stat2 = await lstat9(absolute2);
47276
48471
  if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw failure5("OPTIMIZATION_LEDGER_DIRECTORY_INVALID");
47277
48472
  return realpath8(absolute2);
47278
48473
  }
@@ -47306,7 +48501,7 @@ var OptimizationLedger = class _OptimizationLedger {
47306
48501
  const noticesFilename = path22.join(dir, "live-efficiency-notices.v1.jsonl");
47307
48502
  let existing = "";
47308
48503
  try {
47309
- const stat2 = await lstat8(filename);
48504
+ const stat2 = await lstat9(filename);
47310
48505
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > MAX_LEDGER_BYTES) {
47311
48506
  throw failure5("OPTIMIZATION_LEDGER_INVALID");
47312
48507
  }
@@ -47316,13 +48511,13 @@ var OptimizationLedger = class _OptimizationLedger {
47316
48511
  }
47317
48512
  const handle = await open8(
47318
48513
  filename,
47319
- constants9.O_CREAT | constants9.O_APPEND | constants9.O_WRONLY | (constants9.O_NOFOLLOW ?? 0),
48514
+ constants10.O_CREAT | constants10.O_APPEND | constants10.O_WRONLY | (constants10.O_NOFOLLOW ?? 0),
47320
48515
  384
47321
48516
  );
47322
48517
  const ledger = new _OptimizationLedger(filename, handle, noticesFilename);
47323
48518
  try {
47324
48519
  try {
47325
- const noticeStat = await lstat8(noticesFilename);
48520
+ const noticeStat = await lstat9(noticesFilename);
47326
48521
  if (!noticeStat.isFile() || noticeStat.isSymbolicLink() || noticeStat.size > MAX_NOTICE_LEDGER_BYTES) throw failure5("OPTIMIZATION_NOTICE_LEDGER_INVALID");
47327
48522
  const notices = await readFile9(noticesFilename, "utf8");
47328
48523
  for (const line of notices.split("\n")) {
@@ -47404,7 +48599,7 @@ var OptimizationLedger = class _OptimizationLedger {
47404
48599
  const marker = JSON.stringify({ sessionId: event.sessionId, checkpointCalls, deliveredAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n";
47405
48600
  let currentBytes = 0;
47406
48601
  try {
47407
- const stat2 = await lstat8(this.noticesFilename);
48602
+ const stat2 = await lstat9(this.noticesFilename);
47408
48603
  if (!stat2.isFile() || stat2.isSymbolicLink()) throw failure5("OPTIMIZATION_NOTICE_LEDGER_INVALID");
47409
48604
  currentBytes = stat2.size;
47410
48605
  } catch (error62) {
@@ -47413,7 +48608,7 @@ var OptimizationLedger = class _OptimizationLedger {
47413
48608
  if (currentBytes + Buffer.byteLength(marker, "utf8") > MAX_NOTICE_LEDGER_BYTES) throw failure5("OPTIMIZATION_NOTICE_LEDGER_CAPACITY_EXCEEDED");
47414
48609
  const markerHandle = await open8(
47415
48610
  this.noticesFilename,
47416
- constants9.O_CREAT | constants9.O_APPEND | constants9.O_WRONLY | (constants9.O_NOFOLLOW ?? 0),
48611
+ constants10.O_CREAT | constants10.O_APPEND | constants10.O_WRONLY | (constants10.O_NOFOLLOW ?? 0),
47417
48612
  384
47418
48613
  );
47419
48614
  try {
@@ -47452,7 +48647,7 @@ var OptimizationLedger = class _OptimizationLedger {
47452
48647
 
47453
48648
  // agent/src/monitor.ts
47454
48649
  import { createHash as createHash17, randomUUID as randomUUID12 } from "node:crypto";
47455
- import { lstat as lstat9, mkdir as mkdir9, open as open9, rename as rename6, rm as rm8 } from "node:fs/promises";
48650
+ import { lstat as lstat10, mkdir as mkdir9, open as open9, rename as rename6, rm as rm8 } from "node:fs/promises";
47456
48651
  import path23 from "node:path";
47457
48652
  import os7 from "node:os";
47458
48653
 
@@ -47719,7 +48914,7 @@ var ProductionMonitor = class {
47719
48914
  async write(file2, contents) {
47720
48915
  const directory = path23.dirname(file2);
47721
48916
  await mkdir9(directory, { recursive: true, mode: 448 });
47722
- const stat2 = await lstat9(directory);
48917
+ const stat2 = await lstat10(directory);
47723
48918
  if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw Error("MONITOR_DIRECTORY_INVALID");
47724
48919
  const temporary = file2 + "." + this.instanceId + ".tmp";
47725
48920
  const handle = await open9(temporary, "wx", 384);
@@ -48142,26 +49337,26 @@ var NativeFabricObserver = class {
48142
49337
  };
48143
49338
 
48144
49339
  // agent/src/native-fabric-startup.ts
48145
- import { lstat as lstat11, mkdir as mkdir12, open as open11, readFile as readFile10 } from "node:fs/promises";
49340
+ import { lstat as lstat12, mkdir as mkdir12, open as open11, readFile as readFile10 } from "node:fs/promises";
48146
49341
  import path26 from "node:path";
48147
49342
 
48148
49343
  // src/agent-fabric-service.ts
48149
- import { lstat as lstat10, mkdir as mkdir11, realpath as realpath9 } from "node:fs/promises";
49344
+ import { lstat as lstat11, mkdir as mkdir11, realpath as realpath9 } from "node:fs/promises";
48150
49345
  import { watch } from "node:fs";
48151
49346
  import path25 from "node:path";
48152
49347
 
48153
49348
  // src/agent-runtime-identity.ts
48154
- import { createHash as createHash19, randomBytes as randomBytes7, randomUUID as randomUUID14, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
49349
+ import { createHash as createHash19, randomBytes as randomBytes8, randomUUID as randomUUID14, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
48155
49350
 
48156
49351
  // src/agent-fabric-state.ts
48157
49352
  import { randomUUID as randomUUID13 } from "node:crypto";
48158
- import { mkdir as mkdir10, open as open10, rename as rename7, unlink as unlink2 } from "node:fs/promises";
49353
+ import { mkdir as mkdir10, open as open10, rename as rename7, unlink as unlink3 } from "node:fs/promises";
48159
49354
  import path24 from "node:path";
48160
49355
  var queues = /* @__PURE__ */ new Map();
48161
49356
  var FabricStateFile = class {
48162
- constructor(file2, maxBytes, parse3) {
49357
+ constructor(file2, maxBytes, parse4) {
48163
49358
  this.maxBytes = maxBytes;
48164
- this.parse = parse3;
49359
+ this.parse = parse4;
48165
49360
  this.file = path24.resolve(file2);
48166
49361
  }
48167
49362
  maxBytes;
@@ -48237,7 +49432,7 @@ var FabricStateFile = class {
48237
49432
  }
48238
49433
  await rename7(temporary, this.file);
48239
49434
  } finally {
48240
- await unlink2(temporary).catch((error62) => {
49435
+ await unlink3(temporary).catch((error62) => {
48241
49436
  if (error62.code !== "ENOENT") throw error62;
48242
49437
  });
48243
49438
  }
@@ -48251,7 +49446,7 @@ var FabricStateFile = class {
48251
49446
  } finally {
48252
49447
  await current2.close();
48253
49448
  }
48254
- await unlink2(lockPath);
49449
+ await unlink3(lockPath);
48255
49450
  }
48256
49451
  });
48257
49452
  }
@@ -48305,7 +49500,7 @@ var AgentRuntimeIdentityStore = class {
48305
49500
  return this.serial((state) => {
48306
49501
  if (state.bindings.length >= MAX_BINDINGS) throw Error("RUNTIME_IDENTITY_LIMIT");
48307
49502
  const runtimeId = "rt-" + randomUUID14();
48308
- const runtimeKey = randomBytes7(32).toString("base64url");
49503
+ const runtimeKey = randomBytes8(32).toString("base64url");
48309
49504
  const now = this.now();
48310
49505
  state.bindings.push({ runtimeId, keyHash: encodedDigest(runtimeKey), createdAt: now, lastUsedAt: now, revoked: false });
48311
49506
  return { runtimeId, runtimeKey };
@@ -48870,18 +50065,18 @@ var AgentFabricService = class _AgentFabricService {
48870
50065
  const absolute2 = path25.resolve(directory);
48871
50066
  for (let current2 = absolute2; ; current2 = path25.dirname(current2)) {
48872
50067
  try {
48873
- if ((await lstat10(current2)).isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
50068
+ if ((await lstat11(current2)).isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
48874
50069
  } catch (error62) {
48875
50070
  if (error62.code !== "ENOENT") throw error62;
48876
50071
  }
48877
50072
  if (path25.dirname(current2) === current2) break;
48878
50073
  }
48879
50074
  if (initialize) await mkdir11(absolute2, { recursive: true, mode: 448 });
48880
- if (!(await lstat10(absolute2)).isDirectory() || (await realpath9(absolute2)).toLowerCase() !== absolute2.toLowerCase())
50075
+ if (!(await lstat11(absolute2)).isDirectory() || (await realpath9(absolute2)).toLowerCase() !== absolute2.toLowerCase())
48881
50076
  throw Error("FABRIC_DIRECTORY_INVALID");
48882
50077
  const present = /* @__PURE__ */ new Set();
48883
50078
  for (const name2 of ["binding.json", "mailbox.json", "identities.json"]) {
48884
- const file2 = await lstat10(path25.join(absolute2, name2)).catch((error62) => {
50079
+ const file2 = await lstat11(path25.join(absolute2, name2)).catch((error62) => {
48885
50080
  if (error62.code === "ENOENT") return null;
48886
50081
  throw error62;
48887
50082
  });
@@ -48904,7 +50099,7 @@ var AgentFabricService = class _AgentFabricService {
48904
50099
  state.initialized = true;
48905
50100
  }
48906
50101
  const snapshot2 = await service2.mailbox.snapshot();
48907
- if (snapshot2.workers.some((worker) => worker.runtimeId !== null)) await lstat10(path25.join(absolute2, "identities.json"));
50102
+ if (snapshot2.workers.some((worker) => worker.runtimeId !== null)) await lstat11(path25.join(absolute2, "identities.json"));
48908
50103
  }, initialize ? () => expected : void 0);
48909
50104
  return service2;
48910
50105
  }
@@ -48997,12 +50192,12 @@ async function openNativeFabric(stateDirectory, enrollment, box, initialize = tr
48997
50192
  } catch (error62) {
48998
50193
  if (error62.code !== "EEXIST") throw error62;
48999
50194
  }
49000
- const parentInfo = await lstat11(parent);
50195
+ const parentInfo = await lstat12(parent);
49001
50196
  if (!parentInfo.isDirectory() || parentInfo.isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
49002
50197
  const expected = JSON.stringify({ version: 1, controllerId, tenantId });
49003
50198
  let fresh = false;
49004
50199
  try {
49005
- const info = await lstat11(marker);
50200
+ const info = await lstat12(marker);
49006
50201
  if (!info.isFile() || info.isSymbolicLink() || info.size > 2048 || await readFile10(marker, "utf8") !== expected)
49007
50202
  throw Error("FABRIC_BINDING_CHANGED");
49008
50203
  } catch (error62) {
@@ -49030,7 +50225,7 @@ async function openNativeFabric(stateDirectory, enrollment, box, initialize = tr
49030
50225
  return credential;
49031
50226
  };
49032
50227
  async function capability(workerId) {
49033
- const file2 = credentialFile(workerId), info = await lstat11(file2);
50228
+ const file2 = credentialFile(workerId), info = await lstat12(file2);
49034
50229
  if (!info.isFile() || info.isSymbolicLink() || info.size > 4096) throw Error("FABRIC_CREDENTIAL_UNKNOWN");
49035
50230
  const encoded = await readFile10(file2, "utf8");
49036
50231
  if (decode4(encoded).workerId !== workerId) throw Error("FABRIC_WORKER_DENIED");
@@ -49184,14 +50379,14 @@ function supervisorLiveness(helperPath, options = {}) {
49184
50379
 
49185
50380
  // agent/src/content-audit.ts
49186
50381
  import { createReadStream } from "node:fs";
49187
- 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";
50382
+ 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";
49188
50383
  import path28 from "node:path";
49189
50384
  import { performance as performance3 } from "node:perf_hooks";
49190
50385
  import { createInterface as createInterface2 } from "node:readline";
49191
- import { randomBytes as randomBytes9 } from "node:crypto";
50386
+ import { randomBytes as randomBytes10 } from "node:crypto";
49192
50387
 
49193
50388
  // src/audit-crypto.ts
49194
- import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, createHash as createHash20, randomBytes as randomBytes8 } from "node:crypto";
50389
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, createHash as createHash20, randomBytes as randomBytes9 } from "node:crypto";
49195
50390
  import { promisify as promisify3 } from "node:util";
49196
50391
  import { gunzipSync, gzip, gzipSync } from "node:zlib";
49197
50392
  var gzipAsync = promisify3(gzip);
@@ -49243,7 +50438,7 @@ async function encryptAuditRecordAsync(record2, keyInput, keyId2) {
49243
50438
  function sealCompressed(compressed, keyInput, keyId2) {
49244
50439
  const key = parseAuditRecoveryKey(keyInput);
49245
50440
  const kid = keyId2?.trim() || auditRecoveryKeyId(key);
49246
- const iv = randomBytes8(IV_BYTES);
50441
+ const iv = randomBytes9(IV_BYTES);
49247
50442
  try {
49248
50443
  const cipher = createCipheriv3("aes-256-gcm", key, iv, { authTagLength: TAG_BYTES });
49249
50444
  cipher.setAAD(additionalData(kid));
@@ -49358,13 +50553,13 @@ function contentAuditDirectory(stateDir) {
49358
50553
  }
49359
50554
  async function plainDirectory(dir) {
49360
50555
  await mkdir13(dir, { recursive: true, mode: 448 });
49361
- const info = await lstat12(dir);
50556
+ const info = await lstat13(dir);
49362
50557
  if (info.isSymbolicLink() || !info.isDirectory()) throw Error("AUDIT_DIRECTORY_INVALID");
49363
50558
  }
49364
50559
  async function auditFiles(dir) {
49365
50560
  let names;
49366
50561
  try {
49367
- names = await readdir5(dir);
50562
+ names = await readdir6(dir);
49368
50563
  } catch (error62) {
49369
50564
  if (error62.code === "ENOENT") return [];
49370
50565
  throw error62;
@@ -49373,13 +50568,13 @@ async function auditFiles(dir) {
49373
50568
  for (const name2 of names) {
49374
50569
  const match = FILE.exec(name2);
49375
50570
  if (!match) continue;
49376
- const info = await lstat12(path28.join(dir, name2));
50571
+ const info = await lstat13(path28.join(dir, name2));
49377
50572
  if (info.isFile()) files.push({ name: name2, kind: match[1], day: match[2], bytes: info.size });
49378
50573
  }
49379
50574
  return files.sort((a, b) => a.name.localeCompare(b.name));
49380
50575
  }
49381
50576
  async function writeJsonAtomic(file2, value) {
49382
- const temp = `${file2}.${randomBytes9(6).toString("hex")}.tmp`;
50577
+ const temp = `${file2}.${randomBytes10(6).toString("hex")}.tmp`;
49383
50578
  try {
49384
50579
  await writeFile4(temp, JSON.stringify(value) + "\n", { flag: "wx", mode: 384 });
49385
50580
  await rename8(temp, file2);
@@ -49616,7 +50811,7 @@ async function restoreContentAudit(input2, output2, key) {
49616
50811
  }
49617
50812
 
49618
50813
  // agent/src/main.ts
49619
- var AGENT_VERSION2 = true ? "0.3.46" : "0.3.2";
50814
+ var AGENT_VERSION2 = true ? "0.3.47" : "0.3.2";
49620
50815
  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" : "";
49621
50816
  var AI_CONNECTION_SHIPPED = false;
49622
50817
  function processAlive(pid) {